Skip to main content

FDA +011

· 4 min read

Bias

  • Bias quantifies how much on average the predicted values differ from the actual values.
  • High bias implies the model is under-performing.

Variance

  • Variance quantifies how sensitive the model is to small changes in the training samples.

Ensemble Methods

  • The intuition behind ensemble methods is to decrease bias and variance by using multiple machine learning algorithms.
  • Any machine learning algorithm can be used in ensemble methods.
    • decision trees, neural networks, logistic regressions, etc.
  • Base models are as diverse as possible.
  • Train each base model to predict as accurately as possible.

Sequential ensemble methods

  • Arrange weak learners in a sequence, such that weak learners learn from next learner in the sequence to create better predictive models.
  • Each model fits the residual of its predecessor.

Parallel ensemble methods

  • to use different variations of the same dataset, of the smae classifier, and aggregate the results.

Bootstraping

  • Sampling technique that creates multiple subsets of datasets from the original dataset.
  • when inferring results for a population from results found on a collection of smaller random samples of that population.

Bagging

Bootstrap aggregating

  • Generates subsets (bags) of traning data by sampling from the original training dataset with replacement.
  • To overcome the complexity of models that overfit the training data.

Boosting

  • fits multiple models sequentially
  • each model in the sequence is fitted giving more weight to the data points that were poorly handled by the previous models in the sequence.
  • This process is iterated until the error function does not change, or the maximum limit of the number of estimators is reached.

Random Forest

  • Shallow trees have lower variance and higher bias, whereas deep trees have low bias but high variance.
    • Shallow trees are chosen for sequential ensemble methods
    • Deep trees are chosen for bagging methods (or parallel ensemble methods).
  • a bagging method where deep trees are used and fitted on bootstrap samples, and then combined to produce an output with lower variance.
  • selects randomly a set of features which are then used to decide the best split at each node of the tree.
  • can be applied to both regression and classification tasks.
  • can learn binary features, categorical features and numerical features.
  1. create from the original dataset multiple bootstrap samples.
  2. at each node in the decision tree, a random set of features is considered to decide the most beneficial split.
  3. train a decision tree on each bootstrap sample.
  4. final prediction is computed by averaging the prediction from all decision trees combined.

Advantages of Random Forest

  • generally accurate, quick to train
  • can handle very large datasets
  • can estimate importance of features
  • generates an internal unbiased estimate of accuracy, which can use to know when to stop buildling
  • can handle missing data
  • can handle datasets with imbalanced classes
  • can compute proximity between data points
  • unsupervised for clustering and outlier detection

but don't handle large numbers of irrelevant attributes as well as some other methods.

Applications of Random Forest

IndustryApplicationsPurpose / Advantages
FinanceAssessing high credit-risk customers, detecting fraud, and addressing option pricing problemsPreferred over other algorithms due to its ability to minimize time spent on data management and pre-processing tasks
HealthcareGene expression classification, biomarker discovery, and sequence annotationHelps doctors estimate drug responses to specific medications
E-commerceRecommendation enginesUsed to achieve cross-selling objectives

AdaBoost

Adaptive Boosting

  • simplest boosting algorithm, usaully uses decision trees for modelling
  • multiple sequential models are created, each correcting the errors from the previous model.

GBM

Gradient Boosting Machine

  • works on both regression and classification problems.
  • usually, regression trees are used as base models.

XGBoost

eXtreme Gradient Boosting

  • another implementation of gradient boosting algorithm.
  • has proven to be a highly effective machine learning algorithm.
  • extensively used in machine learning competitions due to its speed and performance.

Combining predictions

Voting

  • Hard voting selection process uses predicted class labels for majority rule voting.
  • Soft voting uses the predicted probabilities given by each base model, and the class label with the maximum sum of its probabilities is selected.
    • 1Ni=1NPi(cx)\frac{1}{N} \sum_{i=1}^{N} P_{i}(c|x)
    • where NN is the number of base models, and Pi(cx)P_{i}(c|x) is the probability predicted by model ii for class cc given input xx.

FSD +009

· 5 min read

Exception

  • Exeptions are throwable objects.
  • Checked Exceptions are checked by the compiler and should be handled (thrown or caught).
  • Unchecked or runtime Exceptions are not flagged by the compiler. Their occurrence during execution interrupts the program.
  • Exceptions can be thrown by developers. Throwing an exception delegates handling the exception to a different class or different level of the program.
  • Thrown exception is left not handled, it will cause runtime error.

Error

  • Java Errors usually indicate problems with the JVM or system resources.
    • it is not meant to be caught or handled by applications.
    • the base class is Error.
  • Python is no separate Error class hierarchy. Errors are represented as exceptions.
    • ValueError, TypeError, MemoryError, SystemError, etc. are subclasses of Exception.

Java vs Pythone Exceiptions

FeatureJavaPython
Syntaxtry-catch-finallytry-except-else-finally
tryattempts to execute a block of codeattempts to execute a block of code
catch/exceptexecute alternative code if exception arisesexecute alternative code if exception arises
finally (optional)executes code regardless of try/catch outcomeexecutes code regardless of try/except outcome
else (optional)Xexecutes code if no exception arises
public class ExceptionExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
System.out.print("Enter first number: ");
int a = scanner.nextInt();
System.out.print("Enter second number: ");
int b = scanner.nextInt();
int result = a / b; // This will raise ArithmeticException
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Caught an exception: " + e.getMessage());
} catch (NumberFormatException e) {
System.out.println("Caught a number format exception: " + e.getMessage());
} finally {
System.out.println("This block always executes.");
}
}
}
def div(a, b):
return a / b

a = input("Enter first number: ")
b = input("Enter second number: ")

try:
result = div(int(a), int(b)) # This will raise ZeroDivisionError
print("Result:", result)
except ZeroDivisionError as e:
print("Caught an exception:", e)
except ValueError as e:
print("Caught a value error:", e)
else:
print("No exception occurred.")
finally:
print("This block always executes.")

Throwing Exceptions

class IncorrectAgeError(Exception):
def __init__(self, age):
self.age = age
self.message = f"Age {age} is not valid. Age must be between 0 and 120."
super().__init__(self.message)

number = int(input("Enter your age: "))

try:
if number < 0 or number > 120:
raise IncorrectAgeError(number)
print(f"Your age is {number}.")
except IncorrectAgeError as e:
print(e)

File Handlers

  • "r": Opens a file for reading, requires the file to exist
  • "w": Opens a file for writing. If the file exists, it is truncated to zero length. If the file does not exist, a new text file is created.
  • "a": Opens file for open for writing. The file is created if it does not exist.
  • "+": Opens a file in updating mode (reading and writing). It can be used with reading (r+) and writing (w+) modes.
  • "t": Opens a file in text mode (default mode).
  • "b": Opens a file in binary mode. It can be used with reading (rb) and writing (wb) modes.

File Handler Methods

os.path.exists("file.txt") # Check if file exists
os.remove("file.txt") # Delete a file
os.remove("dir") # Delete an empty directory
os.chdir("path/dir") # Change current working directory
os.getcwd() # Get current working directory
os.mkdir("path/dir") # Create a new directory

file_handler = open("file.txt", "r") # Open a file in read mode
file_handler.read() # Read the entire file content
file_handler.readline() # Read a single line from the file
file_handler.close() # Close the file

file_handler = open("file.txt", "w") # Open a file in write mode
file_handler.write("Hello, World!") # Write to the file
file_handler.write("\n") # Write a newline character
file_handler.close() # Close the file


import csv
with open("file.txt", "r") as file_handler: # Using 'with' to handle file
csv_object = csv.reader(file_handler)
for row in csv_object:
print(row)
file_handler.close()

with open("file.txt", "a") as file_handler: # Append mode
csv_writer = csv.writer(file_handler)
row = ["1", "gracefullight", "100"]
csv_writer.writerow(row)
file_handler.close()

import json
with open("data.json", "r") as file_handler:
data = json.load(file_handler) # Load JSON data from file
print(data)
file_handler.close()

with open("data.json", "w") as file_handler:
json.dump(data, file_handler) # Write JSON data to file
file_handler.close()
  • InputStream: reads byte-based input from various sources like files, memory, or network connections.
  • OutputStream: writes byte-based output to various network connections.

Unit Testing

  • tests and verifies the smallest unis of an application such as functions, procedures, modules, or objects.
  • the conducted during the development phase of the SDLC.
  • Developers aim to identify defects and code bugs, which can save time and reduce costs in later testing stages.
  • software testing encompasses the fourmain testing phases, and unit testing is at the foundational level of the process.
    • Unit Testing
    • Integration Testing
    • System Testing
    • Acceptance Testing

Python unit testing

  • test cases are defined using classes that inherit from unittest.TestCase
  • assertions are used to validate results self.assertEquals()
  • the unittest.TextTestRunner class can be used to run tests
import unittest

class TestMathOperations(unittest.TestCase):

def test_addition(self):
self.assertEqual(2 + 3, 5)

def test_subtraction(self):
self.assertEqual(5 - 2, 3)

def test_multiplication(self):
self.assertEqual(4 * 3, 12)

def test_division(self):
self.assertEqual(10 / 2, 5)

IAI +010

· 11 min read

Knowledge representation

  • Intelligent agents need knowledge about the world in order to reach good decisions.
  • Declarative knowledge is represented in a form of sentences in a knowledge representation language and stored in a knowledge base.
  • Knowledge base is used by an inference engine to infer a new sentence which will be used for the agent to decide what action to take next.
  • Formal languages are defined by its grammar and semantic rules
    • grammar: defines the syntax of legal sentences
    • semantic rules: defines the meaning.
  • Common knowledge representation formalisms:
    • Propositional logic
    • First-order logic
    • Fuzzy logic
    • Semantic networks
    • Ontologies

Propositional logic

  • a declarative language in which can handle propositions that are known true, known false, or completely (unknown true or false)
  • a BNK (Backus-Naur Form) grammer of sentences in propositional logic.
    • ¬\neg = NOT
    • \land = AND
    • \lor = OR
    •     \implies = IMPLIES
    •     \iff = IF AND ONLY IF
  • Negation: a sentence using ¬\neg is called negation
  • Literal: either an atomic sentence or a negated atomic sentence
  • Conjunction: two sentences connected by \land. Eac hof them is called conjunct
  • Disjunction: two sentences connected by \lor. Each of them is called disjunct
  • Implication: two sentences connected by     \implies. P    QP \implies Q. P is called premise or antecedent and Q is the conclusion or consequent.
    • An implication is if-then statement.

Truth tables

PQ¬\negPP \land QP \lor QP     \implies QP     \iff Q
TTFTTTT
TFFFTFF
FTTFTTF
FFTFFTT

FOL, First-order logic

  • a declarative language
  • Syntax of FOL builds on that of propositional logic
  • terms to represent objects, universal quantifier, and existential quantifier
  • a model in FOL must provide the information required to determine the truth value of every atomic sentence in the language.
  • xP(x)\forall x P(x) means for all x, P(x) is true
  • xP(x)\exists x P(x) means there exists an x such that P(x) is true

Logical equivalence

logical equivalencemeaning
(αβ)(βα)(\alpha \land \beta) \equiv (\beta \land \alpha)Commutativity of \land
(αβ)(βα)(\alpha \lor \beta) \equiv (\beta \lor \alpha)Commutativity of \lor
(α(βγ))((αβ)γ)(\alpha \land (\beta \land \gamma)) \equiv ((\alpha \land \beta) \land \gamma)Associativity of \land
(α(βγ))((αβ)γ)(\alpha \lor (\beta \lor \gamma)) \equiv ((\alpha \lor \beta) \lor \gamma)Associativity of \lor
¬(¬α)α\neg(\neg \alpha) \equiv \alphaDouble negation elimination
(α    β)(¬αβ)(\alpha \implies \beta) \equiv (\neg \alpha \lor \beta)Implication elimination
(α    β)(¬β    ¬α)(\alpha \implies \beta) \equiv (\neg \beta \implies \neg \alpha)Contraposition
(α    β)((α    β)(β    α))\alpha \iff \beta) \equiv ((\alpha \implies \beta) \land (\beta \implies \alpha))Biconditional elimination
¬(αβ)(¬α¬β)\neg(\alpha \land \beta) \equiv (\neg \alpha \lor \neg \beta)De Morgan's law for \land
¬(αβ)(¬α¬β)\neg(\alpha \lor \beta) \equiv (\neg \alpha \land \neg \beta)De Morgan's law for \lor
(α(βγ))((αβ)(αγ))(\alpha \land (\beta \lor \gamma)) \equiv ((\alpha \land \beta) \lor (\alpha \land \gamma))Distributivity of \land over \lor
(α(βγ))((αβ)(αγ))(\alpha \lor (\beta \land \gamma)) \equiv ((\alpha \lor \beta) \land (\alpha \lor \gamma))Distributivity of \lor over \land

x¬P(x)¬xP(x)\forall x \neg P(x) \equiv \neg \exists x P(x)

  • For all x, not P(x) is logically equivalent to "it is not the case that there exists an x such that P(x) is true."

Reasoning

Deductive reasoning

  • a process of reasoning from one or more statements (premises) to reach a logical conclusion.
  • first premise, second premise, therefore conclusion.

Inductive reasoning

  • the process of resoning from specific observations to borader generalizations and theories.
  • also described as a method where one's experiences and observations are synthesized to cmoe up with a general truth.
  • premises and then conclusion

Inference

  • steps in reasoning
  • moves from premises to logical consequences
  • In AI Context, inference is to derive new logical sentences (as the conclusion) from existing logical sentences (as premises).
  • researchers develop automated inference systems to emulate human inference.

Inference Problem

KBγKB \models \gamma

  • KB, Knowledge Base, is a set of propositions that represent what is known about the world.
  • γ\gamma, Query sentence, is the target conclusion which needs to be confirmed based on the given KB.
  • where \models denotes the relation of logical entailment between KB and the sentence γ\gamma, reading as "KB entails γ\gamma" or "if KB is true, then γ\gamma must also be true".
  • αβ    M(α)M(β)\alpha \models \beta \iff M(\alpha) \subseteq M(\beta)
    • M(α)M(\alpha) is the set of all models that satisfy α\alpha.
    • M(β)M(\beta) is the set of all models that satisfy β\beta.
    • The statement αβ\alpha \models \beta means that in every model where α\alpha is true, β\beta is also true. In other words, if α\alpha holds, then β\beta must also hold.
  • Model Checking: enumerates all possible models and checks if the entailment holds in each model.
    • Knowledge base will be used to draw inferences.
    • Query sentence, γ\gamma, is needed to be checked whether it is entailed by the KB.
    • Symbols, a list of all symbols (or atomic propositions) used in the problem context.
    • Models, assignments of truth and false values to those identified symbols.
  • Model Checking Procedure
    1. Identify the propositional symbols involved in the KB sentences and query sentence
    2. Enumerate all possible models by assigning truth values to the identified symbols.
    3. Evaluate the KB sentence in each model and fined the models in which KB is true.
    4. Evaluate the query sentence in the models from step 3 and check if query sentence is true in these models.
    5. Conclude that the KB entails the query sentence γ\gamma if and only if the query sentence is true in all models where the KB is true.

Inference Problem Example

  • Obersvation P: "It is raining"
  • Query sentence Q: "The ground is wet"
  • Knowledge: P    QP \implies Q (If it is raining, then the ground is wet)
  • Knowledge Base KB: P(P    Q)P \land (P \implies Q)
  • Inference Problem: KBQKB \models Q from KB=T, get Q=T
  • Proof:
    1. From the 4 possible models, only Model 1 makes KB true.
    2. M(KB) = model 1
    3. Model 1 also makes Q true.
    4. M(Q) = model 1
    5. M(KB)M(Q)M(KB) \subseteq M(Q), therefore KBQKB \models Q
ModelPQP     \implies QP \land (P     \implies Q)
1TTTT
2TFFF
3FTTF
4FFTF

Inference by theorem proving

to apply rules of inference directly to the sentences in the KB to construct a proof of the desired sentence without consulting models.

  • Proof: a chain of consequences that leads to the desired goal.
  • KB will be used to draw inferences.
  • Desired sentence is needed to be checked whether it is entailed by the KB.
  • The rules of inference are the approved logical equivalences and rules.
AspectModel CheckingTheorem Proving
방식참/거짓으로 실제 계산논리 규칙을 사용해 증명
예시진리표Modus Ponens, Resolution
장점단순함복잡한 문장도 처리 가능
단점계산 많음규칙 익혀야 함

Modus Ponens Rule

α    β,αβ\frac{\alpha \implies \beta, \alpha}{\therefore \beta}

  • whenever any sentences of the form α    β\alpha \implies \beta and α\alpha are given, then the sentence β\beta can be inferred.

Add-Elimination Rule

αβα\frac{\alpha \land \beta}{\therefore \alpha}

  • from a conjunction, one of the conjuncts can be inferred.

Terms to contradiction and resolution

CNF
┌────────────────────────────────────────────────┐
(P ∨ Q)(¬Q ∨ R)
│ ┌──────────────────────┐ ┌───────────────┐ │
│ │ Clause 1 │ │ Clause 2 │ │
│ │ (P ∨ Q) │ │ (¬Q ∨ R) │ │
│ │ ┌───────┬───────┐ │ │ ┌──────┬─────┐ │
│ │ │ P │ Q │ │ │ │ ¬Q │ R │ │
│ │ └───────┴───────┘ │ │ └──────┴─────┘ │
│ └──────────────────────┘ └───────────────┘ │
└────────────────────────────────────────────────┘
  • Literal: an atomic sentence or its negation
  • Complementary literals: a literal and its negation are complementary literals
  • Clause: an expression formed from a collection of finite literals
    • In most l1l2...lnl_1 \lor l_2 \lor ... \lor l_n cases, a clause is a disjunction of finite literals.
    • written as the symbol lil_i.
  • Conjunctive Normal Form: a sentence expressed as a conjunction of clauses.
  • Satisfiability: a sentence is satisfiable if it is true in, or satisfied by, some models.

Propositional satisfiability (SAT) problem

  • to determine the satisfiability of sentences in propositional logic.
  • if there exists a model that satisfies a given logical sentence, then the sentence is satisfiable.
  • Satisfiability can be checked by enumerating the possible models until one is found that satisfies the sentence, or by resolving complementary literals until an empty clause is derived.
  • many problems in CS are really SAT problems.

Resolution rule

Unit resolution rule

(l1l2...li1lili+1...lk, m)l1...li1li+1...lk \frac{(l_1 \lor l_2 \lor ... \lor l_{i-1} \lor l_i \lor l_{i+1} \lor ... \lor l_k,\space m)}{l_1 \lor ... \lor l_{i-1} \lor l_{i+1} \lor ... \lor l_k}

  • where ll is a literal and lil_i and mm are complementary literals.
  • Unit resolution rule takes a clause which is a disjunction of literals, and a literal and produces a new clause as the resolvent.

Full resolution rule

(l1l2...li1lili+1...lk, m1m2...mj1mjmj+1...mn)(l1...li1li+1...lkm1...mj1mj+1...mn) \frac{(l_1 \lor l_2 \lor ... \lor l_{i-1} \lor l_i \lor l_{i+1} \lor ... \lor l_k,\space m_1 \lor m_2 \lor ... \lor m_{j-1} \lor m_j \lor m_{j+1} \lor ... \lor m_n)}{(l_1 \lor ... \lor l_{i-1} \lor l_{i+1} \lor ... \lor l_k \lor m_1 \lor ... \lor m_{j-1} \lor m_{j+1} \lor ... \lor m_n)}

  • where ll is a literal and lil_i and mjm_j are complementary literals.
  • Full resolution rule takes two clauses which are disjuctions of literals and produces a new clause containing all the literals of the two original clauses except for the two complementary literals.

Inference via proof by contradiction through resolution

αβ \alpha \models \beta

  • to prove that αβ\alpha \models \beta, we can show that the sentence α¬β\alpha \land \neg \beta is unsatisfiable.
  • by deriving an empty clause ()() from α¬β\alpha \land \neg \beta using the resolution rule.
  • In order to derive an empty clause, we use resolution which is a process to resolve complementary literals until to find an empty clause.
    1. R1: P (observation)
    2. R2: P     \implies Q (knowledge, raining implies ground is wet)
    3. KB=P(P    Q)KB = P \land (P \implies Q)
    4. Query sentence: Q
    5. Inference problem: KBQKB \models Q, i.e. from KB=TKB=T, get Q=TQ=T
    6. Proof:
    • Let (P(P    Q))¬Q(P \land (P \implies Q)) \land \neg Q valid
    • Convert (P(P    Q))¬Q(P \land (P \implies Q)) \land \neg Q to CNF
    • Apply implication elimination rule, one has (P(¬PQ))¬Q(P \land (\neg P \lor Q)) \land \neg Q
      • C1:PC_1: P
      • C2:¬PQC_2: \neg P \lor Q
      • C3:¬QC_3: \neg Q
    • Apply unit resolution rule to C1C_1 and C2C_2, resolve PP and ¬P\neg P, one has C4:QC_4: Q
    • Apply unit resolution rule to C3C_3 and C4C_4, resolve QQ and ¬Q\neg Q, one has C5:()C_5: ()

Inference in FOL

  • convert the first-order inference to propositional inference using the ruls for quantifiers.
    • universal instantiation (UI)
    • existential instantiation (EI)
  • do inference in propositional logic using the methods about inference in propositional logic.
  • this approach to first-order logic inference via propositionalization is complete, means any entailed sentences can be proved.
    • in most cases, this approach works
    • in some cases, it is slow and only useful when the domain is small.
  • get rid of quantifiers by instantiating them with specific constants or variables.

Universal instantiation (UI)

v αSubst({v/g},α)\frac{\forall v \space \alpha}{\text{Subst}(\{v/g\},\alpha)}

  • to convert sentences with universal quantifiers to sentences without universal quantifiers.
  • it can infer any sentence obtained by substituting a ground term for the universally quantified variable.
  • Subst({θ,α})Subst(\{\theta, \alpha\}) denotes the result of applying the subsitution θ\theta to the sentence α\alpha and gg is a ground term or a constant symbol.
  • universal instantiation can be applied many times to produce may different consequences.
  • xLoves(x,Mary)\forall x Loves(x, Mary)
    • Loves(John,Mary)Loves(John, Mary)
    • Loves(Sue,Mary)Loves(Sue, Mary)
    • Loves(Bill,Mary)Loves(Bill, Mary)
    • ...

Existential instantiation (EI)

  • to convert sentences with existential quantifiers to sentences without existential quantifiers.
  • the quantified variable can be replaced by a single new constant symbol.
  • for any sentence α\alpha, variable vv, and constant symbol kk not appear elsewhere in the knowldge base, the following rule is sound: v αSubst({v/k},α)\frac{\exists v \space \alpha}{\text{Subst}(\{v/k\},\alpha)}
  • Subst{θ,α}\text{Subst}\{\theta, \alpha\} denotes the result of applying the subsitiution θ=v/k\theta={v/k} in the sentence α\alpha and kk is ground term or a new constant symbol.
  • Existential instantiation can be applied only once, and then the existentially quantified sentence can be discarded.
  • xLoves(x,Mary)\exists x Loves(x, Mary)
    • Loves(K,Mary)Loves(K, Mary)
    • where KK is a new constant symbol not appear elsewhere in the knowledge base

CNF, Conjunctive Normal Form

StepRule NameDescriptionExample
1제거    \implies,     \iff 없애기P    QP \implies Q¬PQ\neg P \lor Q
2De Morgan's¬\lnot 분배¬(PQ)(¬P¬Q)\lnot(P \lor Q) \rightarrow (\lnot P \land \lnot Q)
3Double negation이중부정 제거¬(¬P)P\lnot(\lnot P) \rightarrow P
4Distribution\lor over \land 분배(P(QR))(P \lor (Q \land R))(PQ)(PR)(P \lor Q) \land (P \lor R)
5And-Elimination\land 분리(AB)A,B(A \land B) \rightarrow A, B 따로

Vocabulary for AI 011

· 5 min read

Vocabulary & Expressions

Term/ExpressionDefinitionSimpler ParaphraseMeaning
formalisma system of rules and symbols used to represent concepts in a precise and unambiguous waystructured system형식주의, 형식 체계
disjointnot connected or relatedseparate분리된, 연결되지 않은
caveata warning or cautionary detail to considerwarning경고, 주의 사항
instantaneoushappening immediatelyimmediate즉각적인, 순간적인
dwellera person or animal that lives in a specific placeinhabitant거주자, 주민
scantyinsufficient in quantity or qualitymeager부족한, 빈약한
synthesizeto combine different elements to form a coherent wholecombine합성하다, 종합하다
angstroma unit of length equal to one ten-billionth of a meter, used to measure very small distancesunit of length옹스트롬 (10억분의 1미터)
treatya formal agreement between two or more countriesagreement조약, 협정
enticeto attract or tempt by offering something desirableattract유혹하다, 꾀다
simplistictreating complex issues in an overly simple wayoversimplified지나치게 단순화된
Event Calculusa formalism for representing and reasoning about events and their effects over timetemporal reasoning system이벤트 연산
reifyto make something abstract more concrete or realconcretize구체화하다, 실체화하다
reificationthe process of making an abstract concept more concrete or realconcretization구체화, 실체화
ceaseto stop or bring to an endstop중단하다, 멈추다
exogenousoriginating from outside a systemexternal외부의, 외생적인
reignto hold royal office; to rule as a monarchrule통치하다, 군림하다
obscuredhidden or made less visiblehidden가려진, 숨겨진
by virtue ofbecause of; as a result ofbecause of~덕분에, ~때문에
semidecidablea property of a problem where a solution can be verified if given, but not necessarily foundpartially decidable반결정 문제
singlyone at a time; individuallyone at a time하나씩, 개별적으로
negateto nullify or make ineffectivenullify부정하다, 무효화하다
subsumptionthe process of including one concept within another, more general conceptinclusion포섭, 포함
thrustthe main idea, subject, or opinion that is discussed or written aboutmain idea요지, 핵심
tractabilitythe quality of being easy to manage or deal withmanageability계산 가능성
resolventa clause derived from two clauses containing complementary literals, used in resolution-based theorem provingderived clause해석자, 해결책
propositionalzationthe process of converting first-order logic statements into propositional logic statementsconversion to propositional logic명제화
transductionthe process of converting one form of data into anotherdata conversion변환, 전환
transductive learninga type of machine learning where the model makes predictions on specific test cases based on the training data, rather than generalizing to unseen datacase-based learning전이 학습
representationthe way in which information or knowledge is structured and organizeddepiction표현, 나타냄
dispensethe act of distributing or providing somethingdistribution분배, 제공
factorto break down a problem into smaller, more manageable partsbreakdown분해하다
inherentlyin a way that is a permanent, essential, or characteristic attributeintrinsically본질적으로, 내재적으로
precludeto prevent something from happening or to make it impossibleprevent배제하다, 막다
integralnecessary to make a whole complete; essentialessential필수적인, 완전한
eschewto deliberately avoid or abstain from somethingavoid피하다, 삼가다
logarithmicallyin a way that relates to logarithms or logarithmic functionsin terms of logarithms로그적으로
counteractto act in opposition to something to reduce its effectoppose대응하다, 반작용하다
point-wiseapplying a function or operation to each individual element separatelyindividually점별로, 개별적으로
tedioustoo long, slow, or dull; tiresome or monotonousboring지루한, 따분한
multiplicativerelating to multiplication or the process of multiplyingrelating to multiplication곱셈의, 증가하는
leftwardmoving or directed to the leftto the left왼쪽으로
recurrencethe act of returning or happening againreturn재발, 반복
sinusoida mathematical curve that describes a smooth, periodic oscillationwave-like curve사인 곡선
desideratumsomething that is desired or wanteddesired thing바람직한 것, 필요조건
contiguoussharing a common border; touchingadjacent인접한, 접촉하는
dilatedmade larger or expandedexpanded확장된, 팽창된
exhibitto show or display something publiclydisplay전시하다, 나타내다
regimea system or planned way of doing things, especially one imposed from abovesystem체제, 제도
perplexitya state of confusion or uncertaintyconfusion당혹, 혼란
reliancedependence on or trust in someone or somethingdependence의존, 신뢰

Ontology

ConceptWhat it isRole / FunctionExample
OntologyThe representation itself — a structured map of concepts and relationsDescribes the general framework of the worldThe hierarchy (Anything → PhysicalObjects → Humans, etc.)
Ontology SystemThe platform or implementation that holds and reasons about ontologiesStores, queries, and integrates knowledgeCYC, DBpedia, Google Knowledge Graph
Ontological EngineeringThe process of designing and maintaining ontologiesDefines general concepts and their logical structureDefining "PhysicalObject" → later "Robot," "Television," etc.

Semantic Network

  • Semantic networks let us represent logical relationships visually, but their meaning remains purely logical — about objects, categories, and relations.

Tractability

AspectSemantic NetworkDescription LogicFirst-Order Logic
형식성낮음 (그래픽 기반)중간 (논리 기반)높음 (수학적)
표현력제한적중간매우 높음
추론 효율성매우 높음높음 (다항시간 목표)낮음 (NP-hard~undecidable)

IAI +009

· 7 min read

Generative AI

  • Gen AI refers to a category of AI models designed to generte new content, synt99hetic data that resembles a given dataset.
  • Gen AI models create new content, including text, images, audio, and video.

Historcal context of Gen AI

  • 1980s: The development of statistical approaches to AI emerged, focusing on probabilistic models
  • 1990s: Hidden Markov Models (HMMs) became popular in speech recognition and sequence generation tasks, making a shift towards using statistical methods in generative processes.
  • 1990s-2000s: The resurgence of Neural Networks, with the introduction of deep learning techniques. However, hardware and data limitations hampered progress.
  • 2010s: The advent of deep learning algorithms, especially convolutional neural networks (CNNs) and recurrent neural networks (RNNs), transformed the landscape of AI.
  • 2013: VAEs were introduced, providing a probabilistic approach to data generation, allowing for smooth latent space interpolation and structure.
  • 2014: GANs, a novel framework where two neural networks (a generator and a discriminator) are trained simultaneously, allowing for the generation of highly realistic images and other data types.
  • 2015-2020: Generative models began to find applications beyond image synthesis, including text generation, music composition, and even video generation. OpenAI's GPT-2 showcased the potential of transformer-based models for generating coherent text.
  • 2020s: The introduction of larger and more capable models like OpenAI's GPT-3 and subsequent iterations revolutionized natural language processing.
    • DALL-E and Stable Diffusion pushed the boundaries of image generation, allowing users to create images from textual descriptions. This sparked creative exploration and practical applications in marketing, art, and design.
  • Present: The integration of multiple data modalities (text, image, audio) led to the development of models like CLIP and GPT-4, which can understand and generate content across different formats, enhancing the versatility of generative AI.

Variational Autoencoders, VAEs

  • VAEs are from the probabilistic approach to build a generative AI model
  • VAE learns a latent distribution instead of a fixed latent presentation, allowing for the generation of new samples.
  • Latent space
    • sample from a Gaussian distribution
    • μ\mu and σ\sigma are learned during training
    • zz is a new sample from the latent space
  • qϕ(zx)q_\phi(z|x) is the encoder that maps input data xx to a distribution over the latent space zz
  • pθ(xz)p_\theta(x|z) is the decoder that maps a latent variable zz back to the data space xx
  • During training, the model optimizes the reconstruction loss and a regularization term (KL divergence) to ensure the learned latent distribution is close to a prior distribution (usually a standard normal distribution).
  • Latent Representation
    • Dimensionality Reduction: latent space is typically lower-dimensional than the input space
    • Smoothness: In a well-structured latent space, similar inputs will be represented by nearby points.
    • Generative Capabilities: Once trained, can sample from the latent space to generate new data that resembles the training set.
    • Regularization: The VAE incorporates a regularization term in its loss function (KL divergence), which encourages the lerned latent distribution to be close to a standard normal distribution.
  • Decoder
    • The decoder takes the sampled latent representation zz and reconstructs the original input data.
    • The goal is to make the reconstructed data as close as possible to the original input.

VAE Examples

Face Generation Example

  • Trains a VAE on face photos.
  • Latent space learns meaningful features (e.g. hair color, glasses, smile)
  • By sampling and interpolating in latent space, can generate new faces or smoothly morph one face into another.

Anomaly Detection Example

  • Train a VAE on normal sensor data.
  • When fed unusual data, reconstruction error will be high.
  • Use this for fault detection in machines, fraud detction, etc.

Autoencoder

  • Encoder
    • Input Layer: takes in the original data
    • Hidden Layer: These layers progrssively reduce the dimensionality of the input through operations like linear transformations and non-linear activations. (e.g., ReLU-Rectified Linear Unit)
    • Ouput Layer: Produces the final latent represntation. Sometimes Sigmoid or Tanh are used depending on the nature of the input data.
    • Learns to capture meaningful patterns in the data by minimizaing reconstruction loss, which mesures the difference between the original input and the reconstructed output produced by the decoder.
  • Decoder
    • typically mirrors the structure of the encoder but in reverse.
    • During trainng, Mean squared Error (MSE) for continuous data or Binary Cross-Entropy (BCE) for binary data are commonly used to quantify the reconstruction loss.

Image Reconstuction Example

  • input: 28x28 pixel
  • encoder: compresses it to just 16 numbers (latent vector)
  • decoder: expands those 16 numbers back into a 28x28 image
  • result: the reconstructed digit looks similar to the original but not in the training set.

Denoising Images

  • input: a noisy photo of a cat
  • encoder: learns to ignore the noise and compress meaningful features.
  • decoder: rebuilds the image without the noise.
  • output: a clearer cat image.

Loss function

  • Reconstruction loss: Ensure output similar to input
  • KL divergence loss: Push the learned distribution to be close to a standard normal distribution. (can sample new data)

Generative Adversarial Network, GAN

  • Generator: Learns to generate fake (generated) data that resembles data distribution.
  • Discriminator: Learns to distinguish between real data and data generated by the Generator.
  • Steps
    1. Generator creates fake data samples fro mrandom input (noise).
    2. Discriminator evaludates these samples together with real data samples.
    3. Discriminator outputs probabilities indicatcing whether each sample is real or fake.
    4. Based on the prediction of the Discriminator, the Generator and Discriminator are updated using specific loss functions.
  • Applications
    • Labels to Street Scenes
    • Labels to Facade
    • BW to Color
    • Aerial to Map
    • Day to Nihght
    • Edges to Photo
    • Text-to-Image Synthesis

Autoregressive Models

  • a class of generative models where the current value of a time series is expressed as a linear function of its own past values plus some noise.
  • foundational in generative AI and widely used in generative AI, particularly for tasks like text generation, speech synthesis.
  • Examples
    • GPT series: state-of-the-art autoregressive language models used for text generation.
    • WaveNet: an autoregressive model for generating high-quality audio by predicting each sample conditioned on previous samples.

Training Autoregressive Models

  • Pretraining
    • the model sees sequences of tokens and learns to guess the next token.
    • objective: minimize cross-entropy loss between its guess and the true next token.
    • this teaches grammar, facts, reasoning patterns, and style from raw text.
  • Supervised fine-tuning (optional)
    • smaller curated datasets (questions to answer, instructions to respond) teach it to follow directions.
  • Reinforcement learning from Human Feedback (optional)
    • Humans rank multiple model outputs; a reward model is trained on those rankings; GPT is then optimized to produce higher-reward responses (safer, more helpful, less toxic)
  • Text to Tokens via a tokenizer (e.g. BPE, Byte Pair Encoding)
  • Each token becomes a vector (Embedding)
  • Positional encodings inject order information.
  • Transformer layer
    • self-attention: each token looks at all previous token (causal mask) and decides which ones matter, computing weighted combinations.
    • Multiple heads let it attend to different patterns (syntax, long-range links, etc.).
    • feed-forward network: a nonlinear MLP refines each token's representation.
    • residual connections & layer norm stabilize tranining.

Interfence

  • a prompt (the context)
  • GPT computes probabiliites for the next token.
  • A decoding stragety samples a token
    • Decoding knobs
      • Greedy: take the top token
      • Top-K
      • Nucleus (Top-p) sampling (limit to likely options)
      • Temperature scales randomness, controls how random the next token choice is
        • lower = more determistic, higher = more creative
  • append the token and repeat autoregressive generation.

FDA +010

· 4 min read

SVM

a supervised learning framework for finding a boundary between data points belonging to different classes.

Convex Hull

Convex Hull

  • the lines surrounding the outermost points of each class.
  • since the classes are linearly separable, convex hulls do not intersect.

Margins

  • the distance between data points of different classes seprarated by a hyperplane.
  • multiple possible hyperplanes can separate the classes, but the optimal hyperplane maximizes the margin.
  • Maximum Margin Hyperplane
    • a separation line/plane orthogonal to the shortest line connecting the convex hull.
    • the line that is farthest apart from each convex hull.
    • it separates the data points with the widest margin.

Kernels

  • kernel is used to represent kernel functions
    • which are used to convert low-dimensional space to high-dimensional space
    • by applying a function on low-dimensional data points to come up with higher dimensions
      • which can be used to linearly separate the data points of classes using a hyperplane.
  • the function of a kernel is to take data as input and transform it into the required form.
    • different algorithms use different types of kernel functions.
    • linear, non-linear, polynomial, radial basis function (RBF), and sigmoid.

Kernel trick

  • Basic idea of SVM and Kernel trick is to find the plane which can separate, classify or split the data with maximum margin as possible.
  • The distance from a point (x0,y0)(x_0, y_0) to a line Ax+By+C=0Ax + By + C = 0 is given by the formula: Distance=Ax0+By0+CA2+B2\text{Distance} = \frac{|Ax_0 + By_0 + C|}{\sqrt{A^2 + B^2}}
  • The distance between H0H_0, H1H_1 is then: wx+b/w=1/w|w \cdot x + b| / ||w|| = 1/||w||.
    • The total distance between H1H_1 and H2H_2 is 2/w2/||w||.
    • H1:wx+b=1H_1: w \cdot x + b = 1
    • H2:wx+b=1H_2: w \cdot x + b = -1.
    Distance=(+1)(1)w=2w \text{Distance} = \frac{|(+1) - (-1)|}{||w||} = \frac{2}{||w||}
  • to maximiza the margin, we need to minimize w||w||
  • this can be solved through Lagrangian formula or Lagrangian multipliers. L=12w2i=1nαi[yi(wxi+b)1] L = \frac{1}{2} ||w||^2 - \sum_{i=1}^{n} \alpha_i [y_i (w \cdot x_i + b) - 1]
  • Setting the gradient of LL Lw=0w=i=1nαiyixi \frac{\partial L}{\partial w} = 0 \Rightarrow w = \sum_{i=1}^{n} \alpha_i y_i x_i Lb=0i=1nαiyi=0 \frac{\partial L}{\partial b} = 0 \Rightarrow \sum_{i=1}^{n} \alpha_i y_i = 0
  • The dual form of the optimization problem is: Maximize W(α)=i=1nαi12i=1nj=1nαiαjyiyj(xixj) \text{Maximize } W(\alpha) = \sum_{i=1}^{n} \alpha_i - \frac{1}{2} \sum_{i=1}^{n} \sum_{j=1}^{n} \alpha_i \alpha_j y_i y_j (x_i \cdot x_j)
  • Capital letters such as A, X, Y denote matrices;
  • Greek letters such as Φ\Phi, κ\kappa denote functions;
  • lower-case bold letters such as aa, bb denote vectors;
  • script letters such as A\mathcal{A}, B\mathcal{B}, V\mathcal{V}, E\mathcal{E} denote sets or spaces;
  • a||a|| denotes the L2L^2 norm of vector;
  • xF||x||_F denotes the Frobenius norm of matrix, and is given by xF=(i,jxij2)1/2||x||_F = \big(\sum_{i,j} |x_{ij}|^2\big)^{1/2};

Linear Kernel

K(xi,xj)=xixjK(x_i, x_j) = x_i \cdot x_j

Gaussian Kernel / RBF Kernel

K(xi,xj)=exp(xixj22σ2)K(x_i, x_j) = \exp\Big(-\frac{||x_i - x_j||^2}{2\sigma^2}\Big)

Polynomial Kernel

K(xi,xj)=(xixj+1)hK(x_i, x_j) = (x_i \cdot x_j + 1)^h

Sequential Minimal Optimization (SMO)

  • an algorithm for solving the quadratic programming (QP) problem that arises during the training of support vector machines (SVMs).

Advantages

  • Overfitting is unlikely
    • SVM uses the maximum margin hyperplane, which is relatively stable.
    • the maximum margin hyperplane is only sensitive to the changes in the support vectors.
    • the variance in the data may have a relatively low effect on the performance
  • Computational complexity
    • since every time we need to classify a new sample we need to examine that sample with all the support vectors.
    • Using the kernel trick can help to alleviate this by calculating the dot product before doing the nonlinear mapping.

Disadvantages

  • not perform very well when the data set has more noise
  • where the number of features for each data point exceeds the number of training data samples, the SVM will underperform.

Applications

Vocabulary for AI 010

· 2 min read

Vocabulary & Expressions

Term/ExpressionDefinitionSimpler ParaphraseMeaning
cavitya hollow space within a solid objecthollow space구멍, 공동
marginalizationtreatment of a person, group, or concept as insignificant or peripheralsidelining주변화
abbreviateshorten a word, phrase, or textshorten줄이다, 생략하다
summationthe process of adding things togetheraddition합계, 총합
multivaluehaving multiple values or meaningsmultiple values다중 값
quantifyexpress or measure the quantity of somethingmeasure수량화하다
deriveobtain something from (a specified source)obtain끌어내다, 얻다
meningitisinflammation of the protective membranes covering the brain and spinal cordbrain inflammation수막염
casualrelating to or showing the cause of somethingcause-related인과 관계의
epidemica widespread occurrence of an infectious disease in a community at a particular timeoutbreak유행병
proportionatelyin a way that corresponds in size or amount to something elsecorrespondingly비례하여
achingexperiencing a continuous or prolonged dull painpainful아픈, 쑤시는
soup sth upmodify or improve something to make it more powerful or effectiveenhance성능을 향상시키다
perpendicularat an angle of 90 degrees to a given line, plane, or surfaceat right angles수직의
wigglyhaving many curves or bendscurvy구불구불한
versatilityability to adapt or be adapted to many different functions or activitiesadaptability다재다능함
interpolateestimate or insert (a value or function) between two known values in a sequenceestimate between보간하다
commutativitythe property that the order of applying an operation does not change the resultorder-independence교환법칙
associativitythe property that the grouping of operations does not change the resultgrouping-independence결합법칙
contrapositiona logical operation that involves reversing and negating both the hypothesis and conclusion of a conditional statementreverse and negate대우
distributivitythe property that an operation can be distributed over another operationdistribution property분배법칙

Vocabulary for AI 009

· 6 min read

Vocabulary & Expressions

Term/ExpressionDefinitionSimpler ParaphraseMeaning
canonicalconforming to a general rule or acceptable procedurestandard정통의, 표준의
assertstate a fact or belief confidently and forcefullydeclare단언하다, 주장하다
lurkingremaining hidden so as to wait in ambushhidden숨어있는, 잠복하는
bleak(of an area of land) lacking vegetation and exposed to the elementsdesolate황량한, 적막한
albeitalthoughthough비록 ~일지라도
stencha strong and very unpleasant smellfoul smell악취
woefulcharacterized by, expressive of, or causing sorrow or miserysorrowful슬픈, 비참한
As forwith regard to; concerningregarding~에 관하여
ignorancelack of knowledge or informationunawareness무지, 무식
utterlycompletely and without qualification; absolutelycompletely완전히, 전적으로
prudentacting with or showing care and thought for the futurewise신중한, 현명한
arithmeticthe branch of mathematics dealing with the properties and manipulation of numbersmath산수, 계산
entailmenta relationship between sentences in which one sentence logically follows from one or more othersimplication함축, 수반
syntacticrelating to the arrangement of words and phrases to create well-formed sentences in a languagegrammatical구문의, 통사론의
stands forrepresents or signifiesrepresents~을 나타내다
mnemonica device such as a pattern of letters, ideas, or associations that assists in remembering somethingmemory aid기억을 돕는 장치
parenthesesa pair of round brackets () used to mark off a parenthetical word or expressionbrackets괄호
negationthe contradiction or denial of somethingdenial부정, 반대
antecedenta thing or event that existed before or logically precedes anotherpredecessor선행사, 앞서는 것
precedencethe condition of being considered more important than someone or something else; priority in importance, order, or rankpriority우선, 우선권
disjunctsa word or phrase that is grammatically independent of the other parts of the sentence in which it occursseparate part분리된 부분
causationthe action of causing somethingcausing인과, 원인 제공
decidedlyin a manner that is clear and definiteclearly단호하게, 명확히
sufficebe enough or adequatebe sufficient충분하다
tautologya statement that is true by necessity or by virtue of its logical formredundancy동어 반복, 자명한 진리
converselyintroducing a statement or idea that reverses one that has just been made or referred toin contrast반대로
contrapositivelyin a way that involves the contrapositive of a statementby contrapositive대우적으로
refutationthe action of proving a statement or theory to be wrong or false; disproofdisproving반박, 논박
monotonicitythe property of a function to be either entirely non-increasing or non-decreasingconsistency단조성
resolventa clause obtained by resolving two clauses containing complementary literalsderived clause해석절
soundnessthe quality of being based on valid reasoning or good judgmentvalidity타당성
yieldproduce or provide (a natural, agricultural, or industrial product)produce산출하다, 양보하다
ontologicalrelating to the branch of metaphysics dealing with the nature of beingexistential존재론의
commitmentthe state or quality of being dedicated to a cause, activity, etc.dedication헌신, 약속
pedagogicalrelating to teachingeducational교육의, 교수법의
aritythe number of arguments or operands that a function or operation takesnumber of arguments(함수의) 인수 개수
surrogate motherswomen who carry and give birth to a child for another person or couplegestational carriers대리모
predicatea symbol or function that represents a property or relationproperty술어, 속성, 명제함수
kinshipblood relationshipfamily relationship친족 관계
theorema general proposition not self-evident but proved by a chain of reasoning; a truth established by means of accepted truthsproven statement정리, 명제
existentiallyrelating to existencerelating to existence존재에 관한
Universala type of quantification that states that a predicate holds for all members of a specified setfor all전체에 대한 한정
existentiala type of quantification that states that a predicate holds for at least one member of a specified setthere exists존재에 대한 한정
latentexisting but not yet developed or manifest; hidden or concealedhidden잠재적인, 숨어있는

Knowledge Base

  • TELL, ASKS, TELL
    • TELLs the knowledge base what it preceives
    • ASKs the knowledge base what action it should perform
      • reasoning may be done about the current state of the world
      • about the outcomes of possible action sequences and so on
    • TELLs the knowledge base which action was chosen, and returns the action so that it can be executed
  • MAKE-PERCEPT-SENTENCE
    • constructs a sentence asserting that the agent preceived the given percept at the given time.
  • MAKE-ACTION-QUERY
    • constructs a sentence that asks what action should be done at the current time.
  • MAKE-ACTION-SENTENCE
    • constructs a sentence asserting that the chosen action was executed.

Logical connectives

BNF (Backus–Naur Form) grammar of sentences Symbols from Logic and Set Theory

  • ¬\neg : negation (NOT), ¬W1,3\neg W_{1,3}
    • A literal is either an atomic sentence (a positive literal) or a negated atomic sentence (a negative literal).
  • \land : conjunction (AND), W1,3P3,1W_{1,3} \land P_{3, 1}
    • its parts are the conjuncts.
  • \lor : disjunction (OR), (W1,3P3,1)W2,2(W_{1,3} \land P_{3,1}) \lor W_{2,2}
    • its parts are the disjuncts.
  •     \implies : implication (IMPLIES), (W1,3P3,1)    ¬W2,2(W_{1,3} \land P_{3,1}) \implies \neg W_{2,2}
    • its premise or antecedent, and its conclusion or consequent is the part that follows the     \implies.
    • Implications are also called rules or if-then statements.
    • Sometimes written as \rightarrow or \supset.
  •     \iff : biconditional (IF AND ONLY IF), W1,3    ¬W2,2W_{1,3} \iff \neg W_{2,2}

Truth tables

PPQQ¬P\lnot PPQP \land QPQP \lor QP    QP \implies QP    QP \iff Q
falsefalsetruefalsefalsetruetrue
falsetruetruefalsetruetruefalse
truefalsefalsefalsetruefalsefalse
truetruefalsetruetruetruetrue
  • Logical equivalence: PQP \equiv Q:
  • Validity: a sentence is valid if it is true in all models.
    • Deduction Theorem: For any sentences α\alpha and β\beta, αβ\alpha \models \beta if and only if (α    β)(\alpha \implies \beta) is valid.
  • Satisfiability: a sentence is satisfiable if it is true in, or satisfied by, some model.
  • Modus Ponens: α    β,αβ\frac{\alpha \implies \beta, \alpha}{\therefore \beta}
    • whenever any sentences of the form α    β\alpha \implies \beta and α\alpha are given, then the sentence β\beta can be inferred.
  • And-Elimination: αβα\frac{\alpha \land \beta}{\therefore \alpha}
    • from a conjunction, one of the conjuncts can be inferred.
  • monotonicity: the set of entailed sentences can only increase as information is added to the knowledge base.
    • inference rules can be applied whenever suitable premises are found in the knowledge base, regardless of what other sentences are present.

IAI +008

· 13 min read

NLP

Tokenization

The process of dividing a text into a sequence of words.

  • Different models uses different tokenization methods.
BERT TOKENBERT IDGPT TOKENGPT ID
my2026My3666
grandson7631Ġgrandson31845
loved3866Ġloved10140
it2009Ġit340
!999Ġ!0
so2061Ġso1406
much2172Ġmuch881
fun4569Ġfun1257
!999Ġ!0

Corpus

a large and structured collection of text

  • a corpus typically consists of at least a million words of text
  • at least tens of thousands of distinct vocabulary words.

Text classification

  • the process of categorizing text into organized groups.
  • text classifiers can automatically analyze text and then assign a set of predefined tags or categories based on its content.
  • machine learning approach
    • Features
      • BoW
      • TF-IDF
    • Features + classifier
      • Logistic regression
      • SVM
      • Naive Bayes
  • Deep learning approach
    • Neural models: CNNs (capture local n-grams)
    • RNNs, LSTMs (sequence-aware)
    • Transformers (e.g. BERT)
      • Contextual embedding
  • Modern enhancements
    • Embedding + classifier: Pretrained embeddings (Word2Vec) + classifier
    • Fine-tuned transformers: BERT fine-tuned

Bag of Words, BoW

  • it represents a text as a bag of its words
  • we can understand the meaning of a document from its content (words) their multiplicity (frequency, number of occurrences)
  • mainly used as a tool of feature extraction.
  • limitations
    • ignores syntax and the context
    • disregarding grammar
    • discards word order - words are independent of each other
    • considers only the meanings of the words in the sentence
# examples

Example1 = "He likes to watch movies. Mary likes movies too."
Example2 = "Mary also likes to watch football games."

# Vocabulary
Vocab = {"He", "likes", "to", "watch", "movies", "Mary", "also", "football", "games"}

# BoW representation
BoW1 = {He: 1, likes: 2, to: 1, watch: 1, movies: 2, Mary: 1, also: 0, football: 0, games: 0}
BoW2 = {He: 0, likes: 1, to: 1, watch: 1, movies: 0, Mary: 1, also: 1, football: 1, games: 1}

[[1,2,1,1,2,1,0,0,0], [0,1,1,1,0,1,1,1,1]]

TF-IDF

Term Frequency - Inverse Document Frequency

  • Model based on the statistics of word counts.
  • idea is that key terms and important ideas are likely to repeat.
  • includes a scoring function that measure the relevance of a document to a query.
    • the function takes a document with a corpus and a query as input and returns a numeric score.
    • the doucments that have the highest scores are considered as the most relevant documents.
  • Term Frequency
    • TF(qi,dj,D)TF(q_i, d_j, D)
  • Inverse Document Frequency
    • IDF(qi,D)=logNDF(qi,D)IDF(q_i, D) = \log\frac{N}{DF(q_i, D)}
      • DF(qi,D)DF(q_i, D): number of documents in the corpus DD that contain the term qiq_i
  • N=DN = |D|: total number of documents in the corpus DD
  • TF-IDF score
    • TFIDF(qi,dj,D)=TF(qi,dj)IDF(qi,D)TFIDF(q_i, d_j, D) = TF(q_i, d_j) \cdot IDF(q_i, D)

Examples of TF-IDF

  • Document 1: "John likes to watch movies."
  • Document 2: "Mary likes movies too."
  • Document 3: "John also likes football."
StepTermDocumentNumber of times term t
appears in document d
Total number of terms
in document d
TF(t, d)Total number of documentsNumber of documents
containing the term t
IDF(t)IDF(t) (base 10)TF-IDF(t,d)TF-IDF(t,d) (base 10)
1t=likesd1150.2330000
t=likesd2140.2500
t=likesd3140.2500
2t=watchd1150.2311.0986122890.4771212550.2197224580.095424251
t=watchd204000
t=watchd304000
3t=maryd1050311.0986122890.47712125500
t=maryd2140.250.2746530720.119280314
t=maryd304000
4t=footballd1050311.0986122890.47712125500
t=footballd204000
t=footballd3140.250.2746530720.119280314

Naive Bayes

  • naive refers to a very strong simplifying assumption about the features
  • Conditional independence assumption
    • Given class YY, all the features X=X1,X2,...,XnX = {X_1, X_2, ..., X_n} are assumed mutually independent.
  • P(XY)=P(X1,...,XnY)=i=1nP(XiY)P(X | Y) = P(X_1, ..., X_n | Y) = \prod_{i=1}^{n} P(X_i | Y)
  • Bayes rule
    • P(YX)=P(XY)P(Y)P(X)P(Y)P(XY)P(Y | X) = \frac{P(X | Y) P(Y)}{P(X)} \propto P(Y) P(X | Y)
    • P(YX1,...,Xn)P(Y)i=1nP(XiY)P(Y | X_1, ..., X_n) \propto P(Y) \prod_{i=1}^{n} P(X_i | Y)
  • Sentiment Analysis
    • p(Ckx1,...,xn)=1Zp(Ck)i=1np(xiCk)p(C_k | x_1, ..., x_n) = \frac{1}{Z} p(C_k) \prod_{i=1}^{n} p(x_i | C_k)
      • Z=p(x)=kp(Ck)p(xCk)Z = p(x) = \sum_{k} p(C_k) p(x | C_k)
        • scaling factor for normalization of p(Ckx)p(C_k | x)
    • maximum a posteriori (MAP) decision rule
      • y^=arg maxk1,...,Kp(Ck)i=1np(xiCk)\hat{y} = \argmax\limits_{k \in 1, ..., K}p(C_k) \prod_{i=1}^{n} p(x_i | C_k)

Examples of Naive Bayes

P(Classw1:N)=αP(Class)jP(wjClass)P(Class | w_{1:N}) = \alpha \cdot P(Class) \cdot \prod_{j} P(w_j | Class)

  • Analyze the sentiment
    • my grandson loved it
    • x1=myx_1 = \text{my}, x2=grandsonx_2 = \text{grandson}, x3=lovedx_3 = \text{loved}, x4=itx_4 = \text{it}
    • C=positive,negativeC = {positive, negative}
    • y^=arg maxk{positive,negative}p(Ck)p(x1Ck)p(x2Ck)p(x3Ck)p(x4Ck)\hat{y} = \argmax\limits_{k \in \{positive, negative\}} p(C_k) \cdot p(x_1 | C_k) \cdot p(x_2 | C_k) \cdot p(x_3 | C_k) \cdot p(x_4 | C_k)
      • positive case
        • p(positive)=0.49p(positive) = 0.49
        • p(mypositive)=0.30p(my | positive) = 0.30
        • p(grandsonpositive)=0.01p(grandson | positive) = 0.01
        • p(lovedpositive)=0.32p(loved | positive) = 0.32
        • p(itpositive)=0.30p(it | positive) = 0.30
        • p(positivex)p(positive)p(mypositive)p(grandsonpositive)p(lovedpositive)p(itpositive)=0.49×0.30×0.01×0.32×0.30=0.00014256p(positive | x) \propto p(positive) \cdot p(my | positive) \cdot p(grandson | positive) \cdot p(loved | positive) \cdot p(it | positive) = 0.49 \times 0.30 \times 0.01 \times 0.32 \times 0.30 = 0.00014256
      • nagative case
        • p(negative)=0.51p(negative) = 0.51
        • p(mynegative)=0.20p(my | negative) = 0.20
        • p(grandsonnegative)=0.02p(grandson | negative) = 0.02
        • p(lovednegative)=0.08p(loved | negative) = 0.08
        • p(itnegative)=0.4p(it | negative) = 0.4
        • p(negativex)p(negative)p(mynegative)p(grandsonnegative)p(lovednegative)p(itnegative)=0.51×0.20×0.02×0.08×0.4=0.00006528p(negative | x) \propto p(negative) \cdot p(my | negative) \cdot p(grandson | negative) \cdot p(loved | negative) \cdot p(it | negative) = 0.51 \times 0.20 \times 0.02 \times 0.08 \times 0.4 = 0.00006528
      • Z=p(x)=kp(Ck)p(xCk)Z = p(x) = \sum_{k} p(C_k) p(x | C_k)
        • =p(positive)p(my,grandson,loved,itpositive)+p(negative)p(my,grandson,loved,itnegative)= p(positive) \cdot p(my, grandson, loved, it | positive) + p(negative) \cdot p(my, grandson, loved, it | negative)
        • =0.00014256+0.00006528=0.00020784= 0.00014256 + 0.00006528 = 0.00020784
        • the probability of xx, obtained by adding up its probabilities under each class.
      • p(positivex)=p(positive)p(my,grandson,loved,itpositive)Z=0.000142560.000207840.6867p(positive | x) = \frac{p(positive) \cdot p(my, grandson, loved, it | positive)}{Z} = \frac{0.00014256}{0.00020784} \approx 0.6867
      • p(negativex)=p(negative)p(my,grandson,loved,itnegative)Z=0.000065280.000207840.3133p(negative | x) = \frac{p(negative) \cdot p(my, grandson, loved, it | negative)}{Z} = \frac{0.00006528}{0.00020784} \approx 0.3133
    • Decision
      • y^=arg maxk{positive,negative}{k=positive:0.6867,k=negative:0.3133}\hat{y} = \argmax\limits_{k \in \{positive, negative\}} \{k = positive : 0.6867, k = negative : 0.3133\}
      • The sentiment is positive.
  • Spam detection
    • Probabilities learned from data:
      • P(Spam)=0.4P(\text{Spam}) = 0.4, P(Ham)=0.6P(\text{Ham}) = 0.6
      • P(freeSpam)=0.8P(\text{free}|\text{Spam}) = 0.8, P(freeHam)=0.1P(\text{free}|\text{Ham}) = 0.1
      • P(winSpam)=0.7P(\text{win}|\text{Spam}) = 0.7, P(winHam)=0.05P(\text{win}|\text{Ham}) = 0.05
    • New document: "free win"
      • Spam score: 0.4×0.8×0.7=0.2240.4 \times 0.8 \times 0.7 = 0.224
      • Ham score: 0.6×0.1×0.05=0.0030.6 \times 0.1 \times 0.05 = 0.003
        → Classified as Spam.

N-gram model

  • N-gram: a sequence of written symbols of length n
    • unigram, bigram, trigram
  • the probability of each symbol is dependent only on the n-1 previous symbols.
  • P(wjw1:j1)=P(wjwjn+1:j1)P(w_j|w_{1:j-1}) = P(w_j|w_{j-n+1:j-1})
  • P(w1:N)=j=1NP(wjw1:j1)j=1NP(wjwjn+1:j1)P(w_1:N) = \prod_{j=1}^{N} P(w_j|w_{1:j-1}) \approx \prod_{j=1}^{N} P(w_j|w_{j-n+1:j-1})

Examples of N-gram

  • W1:NW_{1:N} is "This article is on NLP"
    • N=5
    • Bigram (n-gram with n=2)
P("This article is on NLP")
/* full chain rule, */
= P("This") // j = 1
* P("article" | "This") // j = 2
* P("is" | "This article") // j = 3
* P("on" | "This article is") // j = 4
* P("NLP" | "This article is on") // j = 5
/* bigram approximation */
= P("This") // j =1
* P("article" | "This") // j = 2
* P("is" | "article") // j = 3
* P("on" | "is") // j = 4
* P("NLP" | "on") // j = 5
Step (j)Word (W_j)BigramTrigram
1This(P(This))(P(\text{This}))(P(This))(P(\text{This}))
2article(P(articleThis))(P(\text{article} \mid \text{This}))(P(articleThis))(P(\text{article} \mid \text{This}))
3is(P(isarticle))(P(\text{is} \mid \text{article}))(P(isThis, article))(P(\text{is} \mid \text{This, article}))
4on(P(onis))(P(\text{on} \mid \text{is}))(P(onarticle, is))(P(\text{on} \mid \text{article, is}))
5NLP(P(NLPon))(P(\text{NLP} \mid \text{on}))(P(NLPis, on))(P(\text{NLP} \mid \text{is, on}))

Transformer

  • given a set of input vectors (tokens), attention lets each token look at the others and form a weighted average of them.
  • The weights are data-dependent.
  • The model learns the weights representing which tokens are relevant to which other tokens.

X=Input Embeddings,Q=XWQ,K=XWK,V=XWVX = \text{Input Embeddings},\qquad Q = X W_Q,\quad K = X W_K,\quad V = X W_V

  • Scores: S=QKTdS = \frac{QK^T}{\sqrt{d}}
    • dot products between every query and every key
    • the scale d\sqrt{d} keeps gradients stable
  • Weights: A=Softmax(S)A = Softmax(S)
    • row-wise softmax
    • each row sums to 1
  • Output: Attention(Q,K,V)=AVAttention(Q, K, V) = A V
    • each output token is a weighted sum of the value vectors, with weights determined by the attention scores.(how much to pay attention to each position)
  • Query (Q): What am I looking for?
  • Key (K): What is the label/address of the information I have?
  • Value (V): What is the actual information I want to convey?

Cross-Attention

  • look up relevant information in another sequence.
    • e.g. decoder attending to encoder outputs in translation
  • QQ from the current sequence, KK and VV from the other sequence.
    • Q=XtargetWQ,K=XsourceWK,V=XsourceWVQ = X_{\text{target}} W_Q, \quad K = X_{\text{source}} W_K, \quad V = X_{\text{source}} W_V
  • Cross-attention = Which source tokens are relevant to this target token?
  • Self-attention = Which other tokens in this sequence are relevant to this token?
  • headi=Attention(QWiQ,KWiK,VWiV)head_i = Attention(Q W_i^Q, K W_i^K, V W_i^V)
  • MultiHead(Q,K,V)=Concat(head1,...,headh)WOMultiHead(Q, K, V) = Concat(head_1, ..., head_h) W_O

Word representation

One-hot representation

  • represents each word as a vector of length N.
  • where N is the size of the vocabulary.
vocab = {he, is, singing, she, dancing, stage}

she = [0, 0, 0, 1, 0, 0]
is = [0, 1, 0, 0, 0, 0]
singing = [0, 0, 1, 0, 0, 0]
  • limitations
    • incredibly inefficient for large vocabularies
    • not embed any intrinsic meaning of words
    • unable to represent similarity between likely words
    • the representation of documents is sparse vectors
      • can cause challenges in computation

Word Embedding

  • represents individual words as vectors in a low-dimensional continuous space.
  • a distributed representation of a word.
  • generate a unique value for each word while using smaller vectors compared with one-hot encoding.
  • common vector dictionaries
    • word2vec
    • Glove (Global Vectors)

Contextual embedding

  • generates different vectors for the same word based on its context.
  • the word "bank" would have different embeddings in the sentences:
    • "He went to the bank to deposit money."
    • "She sat by the river bank and enjoyed the view."
  • BERT or GPT use deep neural networks to process a sequence of tokens.
  • Each token's embedding is computed by considering the token itself, its position in the sequence and the surrounding tokens, context.
  • captures both semantic and syntactic role in that specific context.

Part of Speech (POS) tagging

  • lexical category or tag that indicates the grammatical role of a word in a sentence.
  • parts of speech allow language models to capture generalizations such as "adjectives often modify nouns" or "verbs often follow subjects".
From the start , it took a person
IN DT NN , PRP VBD DT NN

with great qualities to succeed
IN JJ NNS TO VB
TagDescriptionExample
CCCoordinating conjunctionand, but
CDCardinal numberone, two
DTDeterminerthe, a
EXExistential therethere
FWForeign worddoppelgänger
INPreposition or subordinating conjunctionin, of
JJAdjectivebig, old
JJRAdjective, comparativebigger, older
JJSAdjective, superlativebiggest, oldest
LSList item marker1, 2, One
MDModalcan, will
NNNoun, singular or masscat, tree
NNSNoun, pluralcats, trees
NNPProper noun, singularJohn, London
NNPSProper noun, pluralSmiths, Londons
PDTPredeterminerall, both
POSPossessive ending's, s'
PRPPersonal pronounI, you, he
PRP$Possessive pronounmy, your, his
RBAdverbquickly, very
RBRAdverb, comparativefaster, better
RBSAdverb, superlativefastest, best
RPParticleup, off
SYMSymbol$, %, &
TOtoto
UHInterjectionoh, wow
VBVerb, base formbe, have
VBDVerb, past tensewas, had
VBGVerb, gerund or present participlebeing, having
VBNVerb, past participlebeen, had
VBPVerb, non-3rd person singular presenttalk, have
VBZVerb, 3rd person singular presenttalks, has
WDTWh-determinerwhich, that
WPWh-pronounwho, what
WP$Possessive wh-pronounwhose
WRBWh-adverbwhere, when
#Pound sign#
$Dollar sign$
,Comma,
.Sentence-final punctuation. ! ?

Example of POS tagging

  • Hidden Markov Model (HMM)
    • takes in a temproral sequence of evidence observations
    • predicts the lexical categories
  • Logistic regression
    • build 45 different logistics regression models, one for each part of speech
    • ask each model how probable it is that the example word is a member of that category, given the feature values for that word in its particular context.

Machine translation

  • translate a sentence from a source lnaguae to a trget language.
  • train an MT model: a large corpus of source/target sentence paris and hope that the trained MT model can accurately translate new sentences.
  • want to generate a target language sentence that corresponds to the source language sentence
  • the geneartion of each target word is conditional on the entire source sentence and on all previously generated target words.

Example of machine translation

  • a sequance-to-sequence model
    • use two RNNs (LSTM)
  • attentional sequence-to-sequence model
    • use attentino to create a context-based summarization of the source sentence into a fixed-dimension representation
  • transformer-based model
    • encoder: reads the source sentence and turns it into a rich, contextual set of vectors.
    • decoder: generates the target sentence one token at a time, using what it has generated so far and the encoder's representations.

Text generation

  • a subfield of NLP
  • leverages knowledge in computational linguistics and AI to automatically generate natural language texts
  • can satisfy certain communicativa requirements

Example of text generation

  • Classifier based on word embeddings, e.g. RNN and LSTM
    • RNN: each input word is encoded as a word embedding vector xix_i, a hidden layer ztz_t, the classes are the words of the vocabulary
      • the output yty_t will be a softmax probability distribution over the possible values of the next word in the sentence.
    • LSTM: can choose to remember som parts of the input, copying it over to the next time step, and to forget toher parts.
  • Pre-trained languaeg model using deep learning
    • BERT
    • GPT-X, Generativ ePre-trained Transformer

Transfer learning

  • experience with one learning task helps an agent learn better on another task.
  • pretraining: a form of transfer learning in which we use a large amount of shared general-domain language data to train an initial version of an NLP model.
    • we can use a smaller amount of domain-specific data to refine the model
    • the refined model can learn the vocabulary, idioms, syntactic structure, and other linguistic phenomena that are specific to the new domain.
  • For NN, learning consist of adjusting weight, so the most plausible approach for transfer learning is to copy over the weights learned for task A to a network that will be trained for task B.
    • The weights are then updated by gradient descent in the usual way using data for task B.
  • the popularity of transfer learning is the availability of high-quality pretrained models.
  • will want to freeze the first few layers of the pretrained model
    • these layers serve as feature detectors that will be useful for new model.
    • new data set will be allowed to modify the parameters of the higher levels only
      • these are the layers that identify problem-specific features and do classification.

FDA +009

· 2 min read

Linear Separability

  • the data is linearly separable if
    • it can be separated by a point on a single dimension line of data points
    • by a line on a two-dimensional representation of data points
    • by a plane (a two-dimensional surface) in a three-dimensional representation of the data points
  • If it is non-linearly separable, look at other options for classification.

Hyperplane

  • the conceptual divide between data
  • Weight vector: represented and generated in weight space.
  • Choosing the hyperplane
    • Minimum distance between samples
    • Least-squares method
    • Gradient Descent

Artificial Neural Networks, ANN

  • Strength: for high dimensionality problems, the complex relations between variables
  • Weaknesses: theoretically complex, computationally intensive, needs large data sets, complicated to implement
  • Kinds of ANN
    • Perceptrons, Multilayer Perceptrons
    • Deep learning neural networks
    • Kohonen networks
    • Convolutional neural networks
    • Radial Basis Functions
    • Recurrent neural networks
    • Support Vector Machines
    • Competitive learning
    • Boltzmann machines

Multilayer Perceptrons, MLP

  • Challenges
    • Decide on the network topology.
      • how many hidden layers are needed
      • how many neurons in each of the hidden layers
    • Find values for the weights which make the network produce the correct output values for the given input values.
  • Neural networks only accept numeric data.
    • need to convert the categorical into numeric.
    • One-Hot encoding, Thermometer encoding.
  • high values may need to be scaled into a similar range as neural networks
    • need to do a log transform to pull the values into a target range.
    • [-1, +1] or [0, 1]
  • input neurons should be as small as possible.
    • adding neurons -> more parameters and weights -> amplify any bias. (overtrain the network)
  • one categorical attribute may have many attribute values
    • each adding a parameter -> adding risk of overtraining

Resilient Propagation, RProp

  • directly adjust the weight step based on the local gradient information
  • introduces a weight update value uiju_{ij} for each weight wijw_{ij}
  • updates it based on the sign of the partial derivative of the error with respect to the weight
  • update value uiju_{ij}
    • if sign changes (i.e. jumped over local minima) -> uiju_{ij} slightly decreased.
    • if sign remains the same -> uiju_{ij} slightly increased.
  • weight wijw_{ij}
    • if derivative is +ve+ve (i.e. error increasing) -> wijw_{ij} decreased by uiju_{ij}
    • if the derivative is negative (i.e. error decreasing) -> wijw_{ij} increased by uiju_{ij}
    • if the derivative changes sign, the last weight update is reverted. (backtracks the last weight update)

KNIME

  • RProp MLP Learner + MultiLayerPerceptron Predictor
  • MultilayerPerceptron + Weka Predictor (back propagation with momentum)