Introduction to Artificial Intelligence

1. บทนำและนิยาม (Introduction & Definition)

1.1 AI คืออะไร?

Artificial Intelligence (AI) หรือ ปัญญาประดิษฐ์ คือ สาขาวิชาทางวิทยาการคอมพิวเตอร์ที่มุ่งเน้นการสร้างระบบหรือเครื่องจักรที่สามารถแสดงพฤติกรรมที่เรียกได้ว่า "ฉลาด" เหมือนมนุษย์ โดยระบบเหล่านี้สามารถเรียนรู้ เข้าใจ คิดวิเคราะห์ และตัดสินใจได้เอง

นิยามของ AI สามารถแบ่งออกได้เป็น 4 มุมมองหลัก:

%%{init: {'theme':'base', 'themeVariables': { 'primaryColor':'#282828','primaryTextColor':'#ebdbb2','primaryBorderColor':'#fabd2f','lineColor':'#fe8019','secondaryColor':'#3c3836','tertiaryColor':'#504945','background':'#282828','mainBkg':'#3c3836','secondBkg':'#504945','textColor':'#ebdbb2','fontSize':'16px'}}}%%
graph TD
    A[AI Definitions] --> B[Thinking Humanly]
    A --> C[Acting Humanly]
    A --> D[Thinking Rationally]
    A --> E[Acting Rationally]
    
    B --> B1["การคิดเหมือนมนุษย์
Cognitive Modeling"] C --> C1["การกระทำเหมือนมนุษย์
Turing Test Approach"] D --> D1["การคิดอย่างมีเหตุผล
Laws of Thought"] E --> E1["การกระทำอย่างมีเหตุผล
Rational Agent"] style A fill:#458588,stroke:#83a598,color:#ebdbb2 style B fill:#689d6a,stroke:#8ec07c,color:#282828 style C fill:#689d6a,stroke:#8ec07c,color:#282828 style D fill:#d79921,stroke:#fabd2f,color:#282828 style E fill:#d79921,stroke:#fabd2f,color:#282828

1.2 เป้าหมายของ AI

เป้าหมายหลักของ AI คือการสร้าง Rational Agent หรือตัวแทนที่มีเหตุผล ซึ่งหมายถึงระบบที่สามารถ:

ฟังก์ชันของ Rational Agent สามารถแสดงได้ดังนี้:

f : P * A

โดยที่:

ตัวอย่างการทำงานของ Rational Agent

class RationalAgent:
    """ตัวอย่างพื้นฐานของ Rational Agent"""
    
    def __init__(self, goal):
        self.goal = goal
        self.percept_history = []
        self.knowledge_base = {}
    
    def perceive(self, environment):
        """รับรู้สภาพแวดล้อม"""
        percept = environment.get_state()
        self.percept_history.append(percept)
        return percept
    
    def think(self, percept):
        """ประมวลผลและตัดสินใจ"""
        # อัปเดตความรู้
        self.update_knowledge(percept)
        
        # วิเคราะห์สถานการณ์
        analysis = self.analyze_situation()
        
        # เลือกการกระทำที่ดีที่สุด
        best_action = self.choose_best_action(analysis)
        return best_action
    
    def act(self, action, environment):
        """ดำเนินการ"""
        result = environment.execute(action)
        return result
    
    def update_knowledge(self, percept):
        """อัปเดต knowledge base"""
        self.knowledge_base['current_state'] = percept
        self.knowledge_base['time'] = len(self.percept_history)
    
    def analyze_situation(self):
        """วิเคราะห์สถานการณ์ปัจจุบัน"""
        return {
            'state': self.knowledge_base.get('current_state'),
            'goal_distance': self.calculate_goal_distance()
        }
    
    def choose_best_action(self, analysis):
        """เลือกการกระทำที่เหมาะสมที่สุด"""
        # ตรรกะในการเลือกการกระทำ
        possible_actions = ['move_forward', 'turn_left', 'turn_right', 'stop']
        # เลือกการกระทำที่ทำให้เข้าใกล้เป้าหมายมากที่สุด
        return possible_actions[0]  # Simplified
    
    def calculate_goal_distance(self):
        """คำนวณระยะห่างจากเป้าหมาย"""
        # Simplified calculation
        return 0

# ตัวอย่างการใช้งาน
class SimpleEnvironment:
    def __init__(self):
        self.state = {'position': (0, 0), 'obstacles': []}
    
    def get_state(self):
        return self.state
    
    def execute(self, action):
        print(f"Executing action: {action}")
        return True

# สร้าง agent และ environment
env = SimpleEnvironment()
agent = RationalAgent(goal={'position': (10, 10)})

# Agent ทำงาน
percept = agent.perceive(env)
action = agent.think(percept)
agent.act(action, env)

2. รากฐานของปัญญาประดิษฐ์ (Parent Disciplines of AI)

AI เป็นสาขาวิชาที่เกิดจากการบูรณาการความรู้จากหลายสาขาวิชา แต่ละสาขามีส่วนสำคัญในการสร้างพื้นฐานให้กับ AI:

%%{init: {'theme':'base', 'themeVariables': { 'primaryColor':'#282828','primaryTextColor':'#ebdbb2','primaryBorderColor':'#fabd2f','lineColor':'#fe8019','secondaryColor':'#3c3836','tertiaryColor':'#504945','background':'#282828','mainBkg':'#3c3836','secondBkg':'#504945','textColor':'#ebdbb2','fontSize':'14px'}}}%%
graph LR
    AI[Artificial
Intelligence] AI --> Phil[Philosophy
ปรัชญา] AI --> Math[Mathematics
คณิตศาสตร์] AI --> Psy[Psychology
จิตวิทยา] AI --> Neuro[Neuroscience
ประสาทวิทยา] AI --> CS[Computer Science
วิทยาการคอมพิวเตอร์] AI --> Ling[Linguistics
ภาษาศาสตร์] Phil --> Phil1[Knowledge &
Reasoning] Math --> Math1[Logic &
Probability] Psy --> Psy1[Cognitive
Processes] Neuro --> Neuro1[Brain
Structure] CS --> CS1[Algorithms &
Computation] Ling --> Ling1[Language
Structure] style AI fill:#cc241d,stroke:#fb4934,color:#ebdbb2 style Phil fill:#458588,stroke:#83a598,color:#ebdbb2 style Math fill:#b16286,stroke:#d3869b,color:#ebdbb2 style Psy fill:#689d6a,stroke:#8ec07c,color:#282828 style Neuro fill:#d79921,stroke:#fabd2f,color:#282828 style CS fill:#98971a,stroke:#b8bb26,color:#282828 style Ling fill:#d65d0e,stroke:#fe8019,color:#ebdbb2

2.1 ปรัชญา (Philosophy)

ปรัชญาเป็นรากฐานสำคัญที่ทำให้เกิดคำถามพื้นฐาน:

ผลงานสำคัญ:

2.2 คณิตศาสตร์ (Mathematics)

คณิตศาสตร์ให้เครื่องมือในการคำนวณและแสดงความรู้:

ตรรกศาสตร์ (Logic):

P Q R

โดยที่:

ความน่าจะเป็น (Probability):

ทฤษฎีความน่าจะเป็นของ Bayes:

P ( A | B ) = P ( B | A ) P ( A ) P ( B )

โดยที่:

import numpy as np

class BayesianInference:
    """ตัวอย่างการใช้ Bayes' Theorem ใน AI"""
    
    def __init__(self):
        self.prior = {}
        self.likelihood = {}
        self.evidence = {}
    
    def calculate_posterior(self, hypothesis, evidence_data):
        """
        คำนวณ Posterior Probability
        P(H|E) = P(E|H) * P(H) / P(E)
        """
        prior = self.prior.get(hypothesis, 0.5)
        likelihood = self.likelihood.get((hypothesis, evidence_data), 0.5)
        evidence = self.evidence.get(evidence_data, 1.0)
        
        posterior = (likelihood * prior) / evidence
        return posterior
    
    def update_belief(self, hypothesis, evidence_data, prior_prob, likelihood_prob):
        """อัปเดตความเชื่อตาม Bayesian Update"""
        self.prior[hypothesis] = prior_prob
        self.likelihood[(hypothesis, evidence_data)] = likelihood_prob
        
        return self.calculate_posterior(hypothesis, evidence_data)

# ตัวอย่างการใช้งาน: การวินิจฉัยโรค
bayes = BayesianInference()

# ตั้งค่าความน่าจะเป็นเบื้องต้น
# P(มีโรค) = 0.01 (1%)
bayes.prior['disease'] = 0.01
bayes.prior['no_disease'] = 0.99

# ถ้ามีโรค โอกาสที่ผลตรวจเป็นบวก = 0.95
bayes.likelihood[('disease', 'positive_test')] = 0.95
# ถ้าไม่มีโรค โอกาสที่ผลตรวจเป็นบวก = 0.05 (False positive)
bayes.likelihood[('no_disease', 'positive_test')] = 0.05

# คำนวณ P(มีโรค | ผลตรวจเป็นบวก)
bayes.evidence['positive_test'] = (
    bayes.likelihood[('disease', 'positive_test')] * bayes.prior['disease'] +
    bayes.likelihood[('no_disease', 'positive_test')] * bayes.prior['no_disease']
)

prob_disease_given_positive = bayes.calculate_posterior('disease', 'positive_test')
print(f"ความน่าจะเป็นที่มีโรคเมื่อผลตรวจเป็นบวก: {prob_disease_given_positive:.4f}")

2.3 จิตวิทยา (Psychology)

จิตวิทยาช่วยให้เข้าใจกระบวนการคิดและการเรียนรู้ของมนุษย์:

แนวคิดสำคัญ:

ผลงานสำคัญ:

2.4 ประสาทวิทยา (Neuroscience)

ประสาทวิทยาให้ความเข้าใจเกี่ยวกับโครงสร้างและการทำงานของสมอง:

แนวคิดสำคัญที่นำมาใช้ใน AI:

โครงสร้างของ Artificial Neuron:

%%{init: {'theme':'base', 'themeVariables': { 'primaryColor':'#282828','primaryTextColor':'#ebdbb2','primaryBorderColor':'#fabd2f','lineColor':'#fe8019','secondaryColor':'#3c3836','tertiaryColor':'#504945','background':'#282828','mainBkg':'#3c3836','secondBkg':'#504945','textColor':'#ebdbb2','fontSize':'14px'}}}%%
graph LR
    X1[x₁] -->|w₁| Sum((Σ))
    X2[x₂] -->|w₂| Sum
    X3[x₃] -->|w₃| Sum
    Xn[xₙ] -->|wₙ| Sum
    B[bias b] --> Sum
    Sum --> Act[Activation
Function] Act --> Y[output y] style Sum fill:#458588,stroke:#83a598,color:#ebdbb2 style Act fill:#d79921,stroke:#fabd2f,color:#282828 style Y fill:#689d6a,stroke:#8ec07c,color:#282828

สมการของ Artificial Neuron:

y = f ( i=1 n w i x i + b )

โดยที่:

2.5 วิทยาการคอมพิวเตอร์ (Computer Science)

วิทยาการคอมพิวเตอร์ให้เครื่องมือในการนำ AI ไปใช้งานจริง:

แนวคิดสำคัญ:

ตัวอย่าง: Binary Search Tree สำหรับ Decision Making

class DecisionNode:
    """โหนดสำหรับ Decision Tree"""
    
    def __init__(self, feature=None, threshold=None, left=None, right=None, value=None):
        self.feature = feature      # คุณสมบัติที่ใช้ตัดสินใจ
        self.threshold = threshold  # ค่าเกณฑ์
        self.left = left           # โหนดซ้าย (ถ้าเงื่อนไขเป็นเท็จ)
        self.right = right         # โหนดขวา (ถ้าเงื่อนไขเป็นจริง)
        self.value = value         # ค่าผลลัพธ์ (ถ้าเป็น leaf node)
    
    def is_leaf(self):
        """ตรวจสอบว่าเป็น leaf node หรือไม่"""
        return self.value is not None
    
    def predict(self, sample):
        """ทำนายผลลัพธ์สำหรับ sample"""
        if self.is_leaf():
            return self.value
        
        # เลือก branch ตามเงื่อนไข
        if sample[self.feature] <= self.threshold:
            return self.left.predict(sample)
        else:
            return self.right.predict(sample)

# ตัวอย่าง Decision Tree สำหรับการตัดสินใจซื้อคอมพิวเตอร์
# คุณสมบัติ: [RAM (GB), Storage (GB), Price (บาท)]

# สร้าง tree
root = DecisionNode(
    feature=2,  # ดูที่ Price ก่อน
    threshold=30000,
    left=DecisionNode(value="ซื้อ"),  # ถ้าราคา <= 30000 บาท
    right=DecisionNode(
        feature=0,  # ดูที่ RAM
        threshold=16,
        left=DecisionNode(value="ไม่ซื้อ"),  # RAM <= 16 GB และราคา > 30000
        right=DecisionNode(value="ซื้อ")     # RAM > 16 GB
    )
)

# ทดสอบ
sample1 = {'RAM': 8, 'Storage': 512, 'Price': 25000}
sample2 = {'RAM': 32, 'Storage': 1024, 'Price': 50000}

print(f"Sample 1: {root.predict([8, 512, 25000])}")    # ซื้อ
print(f"Sample 2: {root.predict([32, 1024, 50000])}")  # ซื้อ

2.6 ภาษาศาสตร์ (Linguistics)

ภาษาศาสตร์ช่วยในการเข้าใจและประมวลผลภาษาธรรมชาติ:

แนวคิดสำคัญ:

การประยุกต์ใช้ใน AI:


3. สาขาย่อยของ AI (AI Subfields)

AI แบ่งออกเป็นสาขาย่อยหลายสาขาตามประเภทของปัญหาและวิธีการแก้ไข:

%%{init: {'theme':'base', 'themeVariables': { 'primaryColor':'#282828','primaryTextColor':'#ebdbb2','primaryBorderColor':'#fabd2f','lineColor':'#fe8019','secondaryColor':'#3c3836','tertiaryColor':'#504945','background':'#282828','mainBkg':'#3c3836','secondBkg':'#504945','textColor':'#ebdbb2','fontSize':'13px'}}}%%
mindmap
  root((AI
Subfields)) Machine Learning Supervised Learning Unsupervised Learning Reinforcement Learning Deep Learning Natural Language Processing Text Classification Machine Translation Sentiment Analysis Question Answering Computer Vision Image Classification Object Detection Image Segmentation Face Recognition Robotics Motion Planning Manipulation Perception Human-Robot Interaction Expert Systems Knowledge Base Inference Engine Rule-Based Systems Planning & Optimization Path Planning Scheduling Resource Allocation

3.1 Machine Learning (ML)

Machine Learning คือ การเรียนรู้จากข้อมูลโดยไม่ต้องเขียนโปรแกรมอย่างละเอียด

ประเภทของ Machine Learning:

3.1.1 Supervised Learning

เรียนรู้จากข้อมูลที่มีป้ายกำกับ (labeled data):

ตัวอย่างโค้ด Simple Linear Regression:

import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error, r2_score

class SimpleLinearRegression:
    """ตัวอย่าง Linear Regression สำหรับทำนายราคาบ้าน"""
    
    def __init__(self):
        self.model = LinearRegression()
    
    def prepare_data(self, X, y):
        """แบ่งข้อมูลเป็น training และ testing set"""
        return train_test_split(X, y, test_size=0.2, random_state=42)
    
    def train(self, X_train, y_train):
        """ฝึกโมเดล"""
        self.model.fit(X_train, y_train)
        print(f"Coefficient: {self.model.coef_[0]:.2f}")
        print(f"Intercept: {self.model.intercept_:.2f}")
    
    def predict(self, X):
        """ทำนายค่า"""
        return self.model.predict(X)
    
    def evaluate(self, X_test, y_test):
        """ประเมินผล"""
        y_pred = self.predict(X_test)
        mse = mean_squared_error(y_test, y_pred)
        r2 = r2_score(y_test, y_pred)
        
        print(f"Mean Squared Error: {mse:.2f}")
        print(f"R² Score: {r2:.4f}")
        
        return y_pred

# ตัวอย่างการใช้งาน
# สร้างข้อมูลตัวอย่าง: ความสัมพันธ์ระหว่างขนาดบ้าน (ตร.ม.) กับราคา (ล้านบาท)
np.random.seed(42)
house_size = np.random.randint(30, 200, 100).reshape(-1, 1)  # ขนาดบ้าน 30-200 ตร.ม.
house_price = 0.1 * house_size + 2 + np.random.randn(100, 1) * 0.5  # ราคา = 0.1*ขนาด + 2 + noise

# สร้างและฝึกโมเดล
regressor = SimpleLinearRegression()
X_train, X_test, y_train, y_test = regressor.prepare_data(house_size, house_price)
regressor.train(X_train, y_train)
y_pred = regressor.evaluate(X_test, y_test)

สมการ Linear Regression:

y = w 0 + w 1 x 1 + w 2 x 2 + + w n x n

3.1.2 Unsupervised Learning

เรียนรู้จากข้อมูลที่ไม่มีป้ายกำกับ:

3.1.3 Reinforcement Learning (RL)

เรียนรู้จากการทดลองและรับ reward/penalty:

%%{init: {'theme':'base', 'themeVariables': { 'primaryColor':'#282828','primaryTextColor':'#ebdbb2','primaryBorderColor':'#fabd2f','lineColor':'#fe8019','secondaryColor':'#3c3836','tertiaryColor':'#504945','background':'#282828','mainBkg':'#3c3836','secondBkg':'#504945','textColor':'#ebdbb2','fontSize':'14px'}}}%%
graph LR
    Agent[Agent] -->|Action| Env[Environment]
    Env -->|State, Reward| Agent
    
    Agent -->|learns| Policy[Policy π]
    Policy -->|selects| Action[Action aₜ]
    
    Env -->|provides| State[State sₜ]
    Env -->|gives| Reward[Reward rₜ]
    
    style Agent fill:#458588,stroke:#83a598,color:#ebdbb2
    style Env fill:#689d6a,stroke:#8ec07c,color:#282828
    style Policy fill:#d79921,stroke:#fabd2f,color:#282828

Q-Learning Algorithm:

Q ( s , a ) Q ( s , a ) + α [ r + γ max a' Q ( s' , a' ) Q ( s , a ) ]

โดยที่:

3.1.4 Deep Learning

การเรียนรู้ด้วย Neural Networks ที่มีหลาย layer:

3.2 Natural Language Processing (NLP)

การประมวลผลภาษาธรรมชาติ:

งานหลักของ NLP:

Pipeline ของ NLP:

%%{init: {'theme':'base', 'themeVariables': { 'primaryColor':'#282828','primaryTextColor':'#ebdbb2','primaryBorderColor':'#fabd2f','lineColor':'#fe8019','secondaryColor':'#3c3836','tertiaryColor':'#504945','background':'#282828','mainBkg':'#3c3836','secondBkg':'#504945','textColor':'#ebdbb2','fontSize':'13px'}}}%%
graph LR
    A[Raw Text] --> B[Tokenization]
    B --> C[Text Cleaning]
    C --> D[Feature
Extraction] D --> E[Model
Processing] E --> F[Output] style A fill:#458588,stroke:#83a598,color:#ebdbb2 style B fill:#689d6a,stroke:#8ec07c,color:#282828 style C fill:#d79921,stroke:#fabd2f,color:#282828 style D fill:#b16286,stroke:#d3869b,color:#ebdbb2 style E fill:#98971a,stroke:#b8bb26,color:#282828 style F fill:#d65d0e,stroke:#fe8019,color:#ebdbb2
import re
from collections import Counter

class SimpleNLPProcessor:
    """ตัวอย่างพื้นฐานของ NLP Processing"""
    
    def __init__(self):
        # Stop words ภาษาไทยพื้นฐาน
        self.thai_stop_words = set([
            'และ', 'หรือ', 'ที่', 'ใน', 'ของ', 'เป็น', 'การ', 'ได้', 
            'มี', 'จาก', 'ให้', 'กับ', 'นี้', 'นั้น', 'เพื่อ', 'ไว้'
        ])
    
    def tokenize(self, text):
        """แบ่งข้อความเป็น tokens (คำ)"""
        # สำหรับภาษาอังกฤษ
        tokens = re.findall(r'\b\w+\b', text.lower())
        return tokens
    
    def remove_stopwords(self, tokens):
        """ลบ stop words"""
        return [token for token in tokens if token not in self.thai_stop_words]
    
    def get_word_frequency(self, tokens):
        """นับความถี่ของคำ"""
        return Counter(tokens)
    
    def simple_sentiment_analysis(self, text):
        """วิเคราะห์ความรู้สึกเบื้องต้น"""
        positive_words = {'ดี', 'สวย', 'เยี่ยม', 'ชอบ', 'รัก', 'มีความสุข', 'good', 'great', 'excellent', 'love', 'happy'}
        negative_words = {'แย่', 'เลว', 'ไม่ดี', 'เกลียด', 'เศร้า', 'bad', 'terrible', 'hate', 'sad', 'awful'}
        
        tokens = self.tokenize(text)
        
        positive_count = sum(1 for token in tokens if token in positive_words)
        negative_count = sum(1 for token in tokens if token in negative_words)
        
        if positive_count > negative_count:
            return "Positive"
        elif negative_count > positive_count:
            return "Negative"
        else:
            return "Neutral"
    
    def extract_keywords(self, text, top_n=5):
        """ดึงคำสำคัญจากข้อความ"""
        tokens = self.tokenize(text)
        tokens = self.remove_stopwords(tokens)
        word_freq = self.get_word_frequency(tokens)
        
        return word_freq.most_common(top_n)

# ตัวอย่างการใช้งาน
nlp = SimpleNLPProcessor()

text_en = "Artificial Intelligence is great and machine learning is excellent for solving complex problems"
text_th = "ปัญญาประดิษฐ์เป็นเทคโนโลยีที่ดีมากและมีประโยชน์ในการแก้ปัญหาที่ซับซ้อน"

print("Sentiment (EN):", nlp.simple_sentiment_analysis(text_en))
print("Keywords (EN):", nlp.extract_keywords(text_en))

3.3 Computer Vision

การประมวลผลและเข้าใจภาพ:

งานหลักของ Computer Vision:

CNN Architecture:

%%{init: {'theme':'base', 'themeVariables': { 'primaryColor':'#282828','primaryTextColor':'#ebdbb2','primaryBorderColor':'#fabd2f','lineColor':'#fe8019','secondaryColor':'#3c3836','tertiaryColor':'#504945','background':'#282828','mainBkg':'#3c3836','secondBkg':'#504945','textColor':'#ebdbb2','fontSize':'12px'}}}%%
graph LR
    Input[Input
Image] --> Conv1[Convolution
Layer 1] Conv1 --> Pool1[Pooling
Layer 1] Pool1 --> Conv2[Convolution
Layer 2] Conv2 --> Pool2[Pooling
Layer 2] Pool2 --> FC[Fully
Connected
Layer] FC --> Output[Output
Classification] style Input fill:#458588,stroke:#83a598,color:#ebdbb2 style Conv1 fill:#689d6a,stroke:#8ec07c,color:#282828 style Pool1 fill:#d79921,stroke:#fabd2f,color:#282828 style Conv2 fill:#689d6a,stroke:#8ec07c,color:#282828 style Pool2 fill:#d79921,stroke:#fabd2f,color:#282828 style FC fill:#b16286,stroke:#d3869b,color:#ebdbb2 style Output fill:#d65d0e,stroke:#fe8019,color:#ebdbb2

3.4 Robotics

การสร้างหุ่นยนต์อัจฉริยะ:

ส่วนประกอบสำคัญ:

Applications:

3.5 Expert Systems

ระบบผู้เชี่ยวชาญที่เก็บความรู้และกฎเกณฑ์:

ส่วนประกอบ:

ตัวอย่าง Expert System:

class MedicalExpertSystem:
    """ระบบผู้เชี่ยวชาญทางการแพทย์อย่างง่าย"""
    
    def __init__(self):
        # Knowledge Base: กฎการวินิจฉัย
        self.rules = {
            'flu': {
                'symptoms': ['fever', 'cough', 'fatigue', 'body_ache'],
                'min_match': 3,
                'recommendation': 'พักผ่อน ดื่มน้ำเยอะๆ และรับประทานยาลดไข้'
            },
            'cold': {
                'symptoms': ['runny_nose', 'sneezing', 'sore_throat', 'cough'],
                'min_match': 2,
                'recommendation': 'พักผ่อน ดื่มน้ำอุ่น และรับประทานวิตามินซี'
            },
            'allergy': {
                'symptoms': ['sneezing', 'itchy_eyes', 'runny_nose'],
                'min_match': 2,
                'recommendation': 'หลีกเลี่ยงสารก่อภูมิแพ้ และรับประทานยาแก้แพ้'
            }
        }
    
    def diagnose(self, symptoms):
        """
        วินิจฉัยโรคตามอาการ
        symptoms: list of symptom strings
        """
        results = []
        
        for disease, rule in self.rules.items():
            # นับจำนวนอาการที่ตรงกัน
            matched_symptoms = set(symptoms) & set(rule['symptoms'])
            match_count = len(matched_symptoms)
            
            # ถ้าตรงตามเกณฑ์ขั้นต่ำ
            if match_count >= rule['min_match']:
                confidence = (match_count / len(rule['symptoms'])) * 100
                results.append({
                    'disease': disease,
                    'confidence': confidence,
                    'matched_symptoms': list(matched_symptoms),
                    'recommendation': rule['recommendation']
                })
        
        # เรียงตามความมั่นใจ
        results.sort(key=lambda x: x['confidence'], reverse=True)
        return results
    
    def explain_diagnosis(self, diagnosis_results):
        """อธิบายผลการวินิจฉัย"""
        if not diagnosis_results:
            return "ไม่พบโรคที่ตรงกับอาการ กรุณาปรึกษาแพทย์"
        
        explanation = []
        for result in diagnosis_results:
            explanation.append(
                f"\nโรค: {result['disease'].upper()}\n"
                f"ความมั่นใจ: {result['confidence']:.1f}%\n"
                f"อาการที่ตรงกัน: {', '.join(result['matched_symptoms'])}\n"
                f"คำแนะนำ: {result['recommendation']}"
            )
        
        return "\n".join(explanation)

# ตัวอย่างการใช้งาน
expert_system = MedicalExpertSystem()

# ผู้ป่วยมีอาการ
patient_symptoms = ['fever', 'cough', 'fatigue', 'body_ache']

# วินิจฉัย
diagnosis = expert_system.diagnose(patient_symptoms)
explanation = expert_system.explain_diagnosis(diagnosis)

print("=== ผลการวินิจฉัย ===")
print(explanation)
print("\n⚠️ คำเตือน: ระบบนี้เป็นเพียงตัวอย่าง กรุณาปรึกษาแพทย์เพื่อการวินิจฉัยที่แม่นยำ")

4. เทคนิคและอัลกอริทึมพื้นฐานใน AI

4.1 การค้นหา (Search Algorithms)

การค้นหาเป็นเทคนิคพื้นฐานในการแก้ปัญหา AI:

การค้นหาแบบไม่มีข้อมูล:

การค้นหาที่ใช้ข้อมูล heuristic:

A* Search Algorithm:

ฟังก์ชันการประเมิน:

f ( n ) = g ( n ) + h ( n )

โดยที่:

import heapq
from typing import List, Tuple, Dict, Set

class AStarPathfinder:
    """A* Algorithm สำหรับหาเส้นทางที่สั้นที่สุด"""
    
    def __init__(self, grid: List[List[int]]):
        """
        grid: 0 = ทางเดิน, 1 = กำแพง
        """
        self.grid = grid
        self.rows = len(grid)
        self.cols = len(grid[0]) if grid else 0
    
    def heuristic(self, pos1: Tuple[int, int], pos2: Tuple[int, int]) -> float:
        """
        Manhattan Distance Heuristic
        h(n) = |x1 - x2| + |y1 - y2|
        """
        return abs(pos1[0] - pos2[0]) + abs(pos1[1] - pos2[1])
    
    def get_neighbors(self, pos: Tuple[int, int]) -> List[Tuple[int, int]]:
        """หาตำแหน่งข้างเคียง (4 ทิศทาง)"""
        row, col = pos
        neighbors = []
        
        # ขึ้น, ลง, ซ้าย, ขวา
        directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
        
        for dr, dc in directions:
            new_row, new_col = row + dr, col + dc
            
            # ตรวจสอบว่าอยู่ในขอบเขตและไม่ใช่กำแพง
            if (0 <= new_row < self.rows and 
                0 <= new_col < self.cols and 
                self.grid[new_row][new_col] == 0):
                neighbors.append((new_row, new_col))
        
        return neighbors
    
    def find_path(self, start: Tuple[int, int], goal: Tuple[int, int]) -> List[Tuple[int, int]]:
        """
        หาเส้นทางจาก start ไป goal ด้วย A*
        Returns: list of positions หรือ [] ถ้าหาเส้นทางไม่ได้
        """
        # Priority queue: (f_score, position)
        open_set = [(0, start)]
        
        # เก็บ g_score สำหรับแต่ละตำแหน่ง
        g_score: Dict[Tuple[int, int], float] = {start: 0}
        
        # เก็บเส้นทาง
        came_from: Dict[Tuple[int, int], Tuple[int, int]] = {}
        
        # เก็บตำแหน่งที่เคยเยี่ยม
        visited: Set[Tuple[int, int]] = set()
        
        while open_set:
            # ดึงตำแหน่งที่มี f_score ต่ำที่สุด
            current_f, current = heapq.heappop(open_set)
            
            # ถ้าถึงเป้าหมายแล้ว
            if current == goal:
                return self.reconstruct_path(came_from, current)
            
            if current in visited:
                continue
            
            visited.add(current)
            
            # สำรวจข้างเคียง
            for neighbor in self.get_neighbors(current):
                # คำนวณ g_score ใหม่
                tentative_g = g_score[current] + 1  # ระยะทางระหว่างช่อง = 1
                
                # ถ้าพบเส้นทางที่ดีกว่า
                if neighbor not in g_score or tentative_g < g_score[neighbor]:
                    came_from[neighbor] = current
                    g_score[neighbor] = tentative_g
                    f_score = tentative_g + self.heuristic(neighbor, goal)
                    heapq.heappush(open_set, (f_score, neighbor))
        
        # ไม่พบเส้นทาง
        return []
    
    def reconstruct_path(self, came_from: Dict, current: Tuple[int, int]) -> List[Tuple[int, int]]:
        """สร้างเส้นทางจาก came_from dictionary"""
        path = [current]
        while current in came_from:
            current = came_from[current]
            path.append(current)
        path.reverse()
        return path
    
    def visualize_path(self, path: List[Tuple[int, int]]) -> None:
        """แสดงผลเส้นทางบน grid"""
        if not path:
            print("ไม่พบเส้นทาง!")
            return
        
        # สร้าง grid สำหรับแสดงผล
        display = [row[:] for row in self.grid]
        
        # ทำเครื่องหมายเส้นทาง
        for i, (row, col) in enumerate(path):
            if i == 0:
                display[row][col] = 'S'  # Start
            elif i == len(path) - 1:
                display[row][col] = 'G'  # Goal
            else:
                display[row][col] = '*'  # Path
        
        # แสดงผล
        for row in display:
            print(' '.join(str(cell) if cell in [0, 1] else cell for cell in row))
        
        print(f"\nความยาวของเส้นทาง: {len(path)} ช่อง")

# ตัวอย่างการใช้งาน
# 0 = ทางเดิน, 1 = กำแพง
grid = [
    [0, 0, 0, 0, 1, 0, 0],
    [0, 1, 1, 0, 1, 0, 0],
    [0, 0, 0, 0, 0, 0, 0],
    [0, 1, 1, 1, 1, 1, 0],
    [0, 0, 0, 0, 0, 0, 0],
]

pathfinder = AStarPathfinder(grid)
start = (0, 0)
goal = (4, 6)

print("=== A* Pathfinding Demo ===\n")
print("Grid (0=ทางเดิน, 1=กำแพง):")
for row in grid:
    print(' '.join(str(cell) for cell in row))

print(f"\nStart: {start}, Goal: {goal}\n")
path = pathfinder.find_path(start, goal)

print("เส้นทางที่พบ (S=Start, G=Goal, *=Path):")
pathfinder.visualize_path(path)

4.2 Constraint Satisfaction Problems (CSP)

ปัญหาที่มีข้อจำกัด:

องค์ประกอบของ CSP:

ตัวอย่างปัญหา CSP:

อัลกอริทึมสำหรับ CSP:

4.3 Game Playing

การเล่นเกมด้วย AI:

4.3.1 Minimax Algorithm

อัลกอริทึมสำหรับเกม 2 ผู้เล่น:

minimax ( node ) = { utility(node) if node is terminal maxsuccessorminimax(successor) if MAX's turn minsuccessorminimax(successor) if MIN's turn

4.3.2 Alpha-Beta Pruning

การตัดกิ่งใน Minimax เพื่อเพิ่มประสิทธิภาพ:

4.4 Optimization

การหาค่าที่เหมาะสมที่สุด:

เทคนิคการ Optimize:


5. การประยุกต์ใช้ AI (AI Applications)

5.1 Healthcare (การแพทย์)

การประยุกต์ใช้:

ตัวอย่าง: Image Classification สำหรับ X-Ray

# Pseudo-code สำหรับ CNN สำหรับวิเคราะห์ภาพ X-Ray
"""
from tensorflow import keras
from tensorflow.keras import layers

class ChestXRayClassifier:
    def __init__(self):
        self.model = self.build_model()
    
    def build_model(self):
        model = keras.Sequential([
            # Convolutional layers
            layers.Conv2D(32, (3, 3), activation='relu', input_shape=(224, 224, 3)),
            layers.MaxPooling2D((2, 2)),
            
            layers.Conv2D(64, (3, 3), activation='relu'),
            layers.MaxPooling2D((2, 2)),
            
            layers.Conv2D(128, (3, 3), activation='relu'),
            layers.MaxPooling2D((2, 2)),
            
            # Dense layers
            layers.Flatten(),
            layers.Dense(128, activation='relu'),
            layers.Dropout(0.5),
            layers.Dense(2, activation='softmax')  # Normal vs Pneumonia
        ])
        
        model.compile(
            optimizer='adam',
            loss='categorical_crossentropy',
            metrics=['accuracy']
        )
        
        return model
    
    def train(self, train_data, val_data, epochs=20):
        history = self.model.fit(
            train_data,
            validation_data=val_data,
            epochs=epochs
        )
        return history
    
    def predict(self, xray_image):
        prediction = self.model.predict(xray_image)
        return prediction
"""

5.2 Finance (การเงิน)

การประยุกต์ใช้:

5.3 Transportation (การขนส่ง)

การประยุกต์ใช้:

5.4 E-commerce (พาณิชย์อิเล็กทรอนิกส์)

การประยุกต์ใช้:

5.5 Education (การศึกษา)

การประยุกต์ใช้:

5.6 Entertainment (บันเทิง)

การประยุกต์ใช้:

5.7 Manufacturing (การผลิต)

การประยุกต์ใช้:


6. จริยธรรมและความท้าทายของ AI (AI Ethics and Challenges)

6.1 ประเด็นจริยธรรม (Ethical Issues)

6.1.1 Bias และความเป็นธรรม (Bias and Fairness)

AI อาจมี bias จากข้อมูลที่ใช้ฝึก:

ตัวอย่างปัญหา:

แนวทางแก้ไข:

6.1.2 ความเป็นส่วนตัว (Privacy)

การใช้ข้อมูลส่วนบุคคล:

ความท้าทาย:

มาตรการป้องกัน:

6.1.3 ความโปร่งใส (Transparency)

ความสามารถในการอธิบายการตัดสินใจ:

ความสำคัญ:

6.1.4 ความรับผิดชอบ (Accountability)

ใครควรรับผิดชอบเมื่อ AI ทำผิดพลาด:

6.2 ความท้าทายทางเทคนิค (Technical Challenges)

6.2.1 Adversarial Attacks

การโจมตีโมเดล AI:

ตัวอย่าง:

6.2.2 Robustness

ความทนทานของโมเดล:

6.2.3 Scalability

การขยายขนาด:

6.2.4 Data Quality

คุณภาพของข้อมูล:

6.3 ผลกระทบทางสังคม (Social Impact)

6.3.1 Job Displacement

การแทนที่งานของมนุษย์:

แนวทางรับมือ:

6.3.2 Digital Divide

ความเหลื่อมล้ำทางดิจิทัล:

6.3.3 Misinformation

ข้อมูลเท็จและ Deepfake:

มาตรการป้องกัน:

6.4 กรอบการทำงานด้านจริยธรรม (Ethical Frameworks)

6.4.1 หลักการพื้นฐาน

6.4.2 Responsible AI Principles

6.4.3 AI Governance


7. ประวัติและวิวัฒนาการของ AI (History and Evolution of AI)

7.1 ก่อนยุค AI (Pre-AI Era)

1943: McCulloch-Pitts Neuron

Warren McCulloch และ Walter Pitts สร้างแบบจำลองทางคณิตศาสตร์ของเซลล์ประสาท

1950: Turing Test

Alan Turing เสนอ Turing Test เป็นวิธีทดสอบว่าเครื่องจักรมี "สติปัญญา" หรือไม่

คำถามของ Turing:

"Can machines think?" → "Can machines exhibit intelligent behavior indistinguishable from humans?"

1956: Dartmouth Conference

การประชุมที่ Dartmouth College โดย John McCarthy, Marvin Minsky, Claude Shannon, และ Nathaniel Rochester ถือเป็นจุดเริ่มต้นอย่างเป็นทางการของ AI

1957: Perceptron

Frank Rosenblatt พัฒนา Perceptron ซึ่งเป็นรูปแบบแรกของ Neural Network

การทำงานของ Perceptron:

output = { 1 if i=1nwixi+b>0 0 otherwise

7.2 ยุคทอง (1960s-1970s)

ความก้าวหน้า:

7.3 ยุค AI Winter ครั้งที่ 1 (1970s-1980s)

สาเหตุของความถดถอย:

1969: Perceptron Book

Minsky และ Papert เขียนหนังสือชี้ให้เห็นข้อจำกัดของ Perceptron

7.4 ยุคฟื้นฟู (1980s)

Backpropagation Algorithm (1986)

Rumelhart, Hinton, และ Williams นำเสนออัลกอริทึม Backpropagation ซึ่งทำให้สามารถฝึก Multi-layer Neural Networks ได้

Backpropagation:

E w ij = E o j o j net j net j w ij

Expert Systems

ระบบผู้เชี่ยวชาญเริ่มได้รับความนิยมในอุตสาหกรรม

7.5 ยุค AI Winter ครั้งที่ 2 (1990s)

อีกครั้งที่ AI เข้าสู่ช่วงถดถอยเนื่องจาก:

7.6 ยุคฟื้นคืนชีพ (2000s-2010s)

2006: Deep Learning Renaissance

Geoffrey Hinton และทีมแสดงให้เห็นว่าสามารถฝึก Deep Neural Networks ได้อย่างมีประสิทธิภาพ

ปัจจัยสำคัญ:

2012: AlexNet

AlexNet ชนะการแข่งขัน ImageNet ด้วยความแม่นยำที่สูงกว่าวิธีแบบเดิมมาก

2016: AlphaGo

DeepMind's AlphaGo เอาชนะ Lee Sedol ผู้เชี่ยวชาญเกมโกะระดับโลก

7.7 ยุคปัจจุบัน (2020s)

Generative AI

การพัฒนา AI ที่สามารถสร้างเนื้อหาใหม่:

Large Language Models (LLMs)

โมเดลภาษาขนาดใหญ่ที่มีความสามารถหลากหลาย:

Timeline วิวัฒนาการ AI:

%%{init: {'theme':'base', 'themeVariables': { 'primaryColor':'#3c3836','primaryTextColor':'#ebdbb2','primaryBorderColor':'#fabd2f','lineColor':'#fe8019','secondaryColor':'#504945','tertiaryColor':'#665c54','background':'#282828','fontSize':'13px'}}}%%
graph TD
    subgraph Era1[" ยุคเริ่มต้น (1950-1960s)"]
        A["1950: Turing Test
AI เริ่มต้น"] B["1956: Dartmouth Conference
คำว่า AI เกิดขึ้น"] C["1957: Perceptron
Neural Network แรก"] end subgraph Era2[" ยุคทองและความถดถอย (1960s-1990s)"] D["1960s-70s: Expert Systems
ยุคทอง AI"] E["1970s-80s: AI Winter 1
ความถดถอยครั้งแรก"] F["1986: Backpropagation
ฝึก Multi-layer NN ได้"] G["1990s: AI Winter 2
ความถดถอยครั้งที่สอง"] end subgraph Era3[" ยุคฟื้นฟู (1997-2016)"] H["1997: Deep Blue
IBM เอาชนะ Kasparov"] I["2006: Deep Learning
ฟื้นคืนชีพ"] J["2012: AlexNet
CNN ชนะ ImageNet"] K["2016: AlphaGo
AI เอาชนะมนุษย์ในเกมโกะ"] end subgraph Era4[" ยุคใหม่ (2017-ปัจจุบัน)"] L["2017: Transformer
สถาปัตยกรรมใหม่"] M["2020: GPT-3
LLM ขนาดใหญ่"] N["2022: ChatGPT
AI สู่สาธารณะ"] O["2024: Generative AI
AI สร้างสรรค์"] end A --> B --> C --> D --> E --> F --> G --> H --> I --> J --> K --> L --> M --> N --> O

7.8 อนาคตของ AI

แนวโน้มและความท้าทาย:

Artificial General Intelligence (AGI)

Explainable AI (XAI)

AI Ethics

Edge AI

Quantum AI

ความท้าทายที่ต้องเผชิญ:

  1. Data Bias: ข้อมูลที่มี bias นำไปสู่ AI ที่มี bias
  2. Privacy: การปกป้องข้อมูลส่วนบุคคล
  3. Security: การป้องกัน adversarial attacks
  4. Energy Consumption: การใช้พลังงานสูงของโมเดลขนาดใหญ่
  5. Job Displacement: ผลกระทบต่อตลาดแรงงาน
  6. Regulation: การกำกับดูแลที่เหมาะสม

สรุป

Artificial Intelligence เป็นสาขาวิชาที่กว้างขวางและซับซ้อน ครอบคลุมตั้งแต่รากฐานทางปรัชญาและคณิตศาสตร์ ไปจนถึงการประยุกต์ใช้ในชีวิตประจำวัน AI ได้พัฒนามาอย่างต่อเนื่องตั้งแต่ทศวรรษ 1950 ผ่านช่วงเวลาที่รุ่งเรืองและถดถอยสลับกันไป จนมาถึงยุคปัจจุบันที่ AI กลายเป็นส่วนสำคัญของเทคโนโลยีและสังคม

จุดสำคัญของ AI:

อนาคตของ AI มีทั้งโอกาสและความท้าทาย การพัฒนา AI ที่มีความรับผิดชอบ (Responsible AI) จะเป็นกุญแจสำคัญในการสร้างเทคโนโลยีที่เป็นประโยชน์ต่อมนุษยชาติอย่างแท้จริง


เอกสารอ้างอิง:

  1. Russell, S., & Norvig, P. (2020). Artificial Intelligence: A Modern Approach (4th ed.). Pearson.
  2. Goodfellow, I., Bengio, Y., & Courville, A. (2016). Deep Learning. MIT Press.
  3. Mitchell, T. M. (1997). Machine Learning. McGraw-Hill.
  4. Bishop, C. M. (2006). Pattern Recognition and Machine Learning. Springer.
  5. Sutton, R. S., & Barto, A. G. (2018). Reinforcement Learning: An Introduction (2nd ed.). MIT Press.