零基础学机器学习 - 黄佳

本书给出了一个机器学习入门路线图,从一个零基础的初学者视角出发,让读者跟着她一步一步向前,循序渐进地学习知识。包括机器学习、深度学习和强化学习的基础内容。
关于作者
黄佳 是人工智能领域的技术作家 和教育者:
- AI 技术专家:专注于机器学习和深度学习领域
- 技术作家:著有多本 AI 和机器学习相关书籍
- 教育者:擅长用通俗易懂的方式讲解复杂的 AI 概念
黄佳以其"零基础学"系列的写作风格著称,通过大量图解和代码示例,帮助零基础的读者入门机器学习。
核心内容
1. 机器学习基础
# 机器学习三大类型
# 1. 监督学习 (Supervised Learning)
# 特点:有标签数据,学习输入到输出的映射
# 应用:分类、回归
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
# 分类示例
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
model = LogisticRegression()
model.fit(X_train, y_train)
predictions = model.predict(X_test)
# 2. 无监督学习 (Unsupervised Learning)
# 特点:无标签数据,发现数据内在结构
# 应用:聚类、降维、异常检测
from sklearn.cluster import KMeans
from sklearn.decomposition import PCA
# 聚类示例
kmeans = KMeans(n_clusters=3)
clusters = kmeans.fit_predict(X)
# 降维示例
pca = PCA(n_components=2)
X_reduced = pca.fit_transform(X)
# 3. 强化学习 (Reinforcement Learning)
# 特点:通过与环境交互学习,最大化累积奖励
# 应用:游戏 AI、机器人控制、自动驾驶
import gym
env = gym.make('CartPole-v1')
# Agent 通过试错学习最优策略
2. 线性回归
import numpy as np
from sklearn.linear_model import LinearRegression
# 简单线性回归
# y = w * x + b
X = np.array([[1], [2], [3], [4], [5]])
y = np.array([2, 4, 5, 4, 5])
model = LinearRegression()
model.fit(X, y)
print(f"权重:{model.coef_[0]:.2f}")
print(f"截距:{model.intercept_:.2f}")
print(f"R² 分数:{model.score(X, y):.2f}")
# 损失函数:均方误差 (MSE)
# L = (1/n) * Σ(y_pred - y_true)²
# 梯度下降优化
def gradient_descent(X, y, learning_rate=0.01, epochs=1000):
n_samples, n_features = X.shape
weights = np.zeros(n_features)
bias = 0
for _ in range(epochs):
# 前向传播
y_pred = np.dot(X, weights) + bias
# 计算梯度
dw = (1/n_samples) * np.dot(X.T, (y_pred - y))
db = (1/n_samples) * np.sum(y_pred - y)
# 更新参数
weights -= learning_rate * dw
bias -= learning_rate * db
return weights, bias
3. 逻辑回归与分类
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report, confusion_matrix
# 逻辑回归:Sigmoid 函数
# P(y=1|x) = 1 / (1 + exp(-w*x - b))
def sigmoid(z):
return 1 / (1 + np.exp(-z))
# 多分类策略
# 1. One-vs-Rest (OvR)
# 2. Softmax 回归
model = LogisticRegression(
multi_class='multinomial', # Softmax
solver='lbfgs',
max_iter=1000
)
model.fit(X_train, y_train)
# 评估
y_pred = model.predict(X_test)
print(confusion_matrix(y_test, y_pred))
print(classification_report(y_test, y_pred))
# 评估指标
# - 准确率 (Accuracy): 正确预测的比例
# - 精确率 (Precision): 预测为正的样本中有多少是真的正
# - 召回率 (Recall): 真的正样本中有多少被预测对了
# - F1 分数:精确率和召回率的调和平均