终于进入机器学习了!

alt text

机器学习的主要方法:

  • 监督式机器学习
  • 无监督式机器学习
  • 强化学习

学习方法

  • 基于模型——通过对训练数据进行学习和分析,构建一个明确的模型来描述数据的内在规律和模式。然后,利用这个模型对新的数据进行预测和分类。
  • 基于实例——并不显式地构建一个模型,而是直接将训练数据存储起来。在预测时,根据新数据与训练数据的相似性,从训练数据中找到与之最相似的实例,并根据这些实例的标签或属性来进行预测。

监督学习的常用方法:

  • 贝叶斯分类器
  • 逻辑回归(分类)
  • 决策树
  • 支撑向量机
  • 神经网络

无监督学习的常用方法:

  • K-均值聚类(K-means)
  • 高斯混合模型(GMM)

alt text
alt text

机器学习软件scikit-learn的学习

相关阅读:https://arxiv.org/abs/1309.0238

scikit-learn是基于python的开源机器学习库
正由于scikit-learn有标准的api(应用程序接口)设计,故其使用流程都是固定的
alt text
scikit-learn的数据表示:

  • Numpy的多维数组表示密集数据
  • Scipy的稀疏矩阵表示稀疏数据

scikit-learn的api设计:

  • 估算器接口estimator是核心库,fit()方法作为统一的训练数据输入
  • 预测器接口predictor是扩展估算器,predict()方法输入X_test来产生预测
  • 转换器transformer定义了transform()方法

alt text

有监督学习

form sklearn.机器学习大类方法 import 具体方法

基础操作

数据准备
1
2
3
4
5
6
7
8
9
10
11
12
13
14
from sklearn.datasets import make_classification

# 创建一组带标签的数据
n_samples = 100
X, y = make_classification(n_samples=n_samples, n_features=2, n_informative=2,
n_redundant=0, n_repeated=0, random_state=250)

# X是100个2维变量
X[:5]
X.shape

# y是100个0/1标签
y[:5]
y.shape
对创建的数据集进行数据可视化
1
2
3
plt.figure(figsize=(10, 10))
plt.scatter(X[:, 0], X[:, 1], c=y, cmap = 'coolwarm')
#cmap = 'coolwarm' 通常是用于设置绘图时的颜色映射(colormap)。'coolwarm' 是 matplotlib 库中一种常用的颜色映射,它从冷色调(蓝色)过渡到暖色调(红色),常被用于突出数据中的正负值或高低值对比。
贝叶斯公式进行分类(高斯朴素贝叶斯分类器)

用后验信息更新先验概率以获得后验概率
[
P(A|B)=\frac{P(B|A)P(A)}{P(B)}
]
alt text

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#从GaussianNB引入GNB模型,用于拟合
from sklearn.naive_bayes import GaussianNB
#accuracy_score模块,评估拟合的准确度
from sklearn.metrics import accuracy_score

#建立模型并拟合
gnb = GaussianNB()
gnb.fit(X, y)

#查看对不同标签预测的概率
gnb.predict_proba(X).round(4)[:5]
#输出预测标签
pred=gnb.predict(X)

#查看拟合结果
pred == y
#输出准确率
acc=accuracy_score(pred, y)

#绘制带预测标记的散点图(设Xc为正确的分类)
Xc=X[y == pred]
Xf=X[y != pred]

plt.figure(figsize=(10, 10))
plt.scatter(Xc[:, 0], Xc[:, 1], c=y[y == pred], marker = 'o', cmap = 'coolwarm')
plt.scatter(Xf[:, 0], Xf[:, 1], c=y[y != pred], marker = 'x', cmap = 'coolwarm')
逻辑回归

用logistic函数(Sigmoid函数),将single trial的可能结果输出为概率
[
y = \frac{1}{1 + e^{-x}}
]

逻辑回归单元
alt text

1
2
3
4
5
6
7
from sklearn.linear_model import LogisticRegression

model = LogisticRegression(C=1)
model.fit(X, y)
model.predict_proba(X).round(4)[:5]
pred=model.predict(X)
accuracy_score(pred, y)
决策树Decision Tree

基于特征的分类方法
alt text
alt text
决策树的生成算法:ID3算法
alt text

1
2
3
4
5
6
7
8
9
10
11
12
13
14
from sklearn.tree import DecisionTreeClassifier
#采用决策树分类预测
dt = DecisionTreeClassifier(max_depth=1)
dt.fit(X, y)
dt.predict_proba(X).round(4)
pred=dt.predict(X)
#查看不同深度决策树的准确率
print('{:>8s} | {:8s}'.format('depth', 'accuracy'))
print(20 * '-')
for depth in range(1, 6):#深度值的循环
model = DecisionTreeClassifier(max_depth=depth)#创建决策树进行计算,看每个节点的准确度
model.fit(X, y)
acc=accuracy_score(model.predict(X), y)
print('{:>8s} | {:8s}'.format(depth, acc))
支撑向量机SVM

alt text
alt text

数据预处理

特征变换

缩放:
alt text

连续值变换:

  • 标准差归一化alt text
  • 最小最大归一化
  • L1正则化
  • L2正则化alt text
    离散值变换
    alt text
数据集的拆分——训练集与测试集

alt text

1
2
3
4
5
6
7
8
9
10
11
from sklearn.svm import SVC
from sklearn.model_selection import train_test_split

train_x, test_x, train_y, test_y = train_test_split(X, y, test_size=0.33, random_state=0)

#采用支撑向量机模型进行测试划分后的数据集
model = SVC(C=1, kernel='linear')
model.fit(train_x, train_y)
pred_test = model.predict(test_x)
test_y==pred_test
accuracy = model.score(test_x, test_y)

alt text
alt text

无监督学习

1
2
3
4
5
6
7
#新建数据集
from matplotlib import pyplot as plt
from sklearn.datasets import make_blobs

X, y = make_blobs(n_samples=250, random_state=500, centers=4, cluster_std=1.25)
plt.figure(figsize=(10, 10))
plt.scatter(X[:, 0], X[:, 1], s=50)

K均值聚类

alt text

高斯混合模型

alt text

练习

数据清洗与分析

题目:
使用 Scikit-learn 库中的鸢尾花数据集(datasets.load iris()),进行以下数据探索与分析任务(上传实验结果截屏):
数据加载与初步查看:
加载鸢尾花数据集
查看数据集的前几行,了解数据的基本结构。
数据描述:
生成数据集的描述性统计信息,包括均值、标准差、最小值、最大值等3.数据分布可视化:
绘制每个特征的直方图,查看数据的分布情况,
绘制箱线图,查看数据的离散程度和异常值。
答案:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris

# 1. 数据加载与初步查看
# 加载鸢尾花数据集
iris = load_iris()
# 将数据转换为 DataFrame 格式,方便后续操作
iris_df = pd.DataFrame(data= np.c_[iris['data'], iris['target']],
columns= iris['feature_names'] + ['target'])
# 查看数据集的前几行
print("数据集前几行:")
print(iris_df.head())

# 2. 数据描述
# 生成数据集的描述性统计信息,包括均值、标准差、最小值、最大值等
description = iris_df.describe()
print("\n数据集描述性统计信息:")
print(description)

# 3. 数据分布可视化
# 设置图片清晰度
plt.rcParams['figure.dpi'] = 300

# 绘制每个特征的直方图,查看数据的分布情况
features = iris['feature_names']
fig, axes = plt.subplots(2, 2, figsize=(10, 8))
axes = axes.flatten()
for i, feature in enumerate(features):
axes[i].hist(iris_df[feature], bins=20, edgecolor='k')
axes[i].set_title(f'Histogram of {feature}')
axes[i].set_xlabel(feature)
axes[i].set_ylabel('Frequency')
plt.tight_layout()
plt.show()

# 绘制箱线图,查看数据的离散程度和异常值
iris_df.drop('target', axis=1).plot(kind='box', subplots=True, layout=(2, 2), figsize=(10, 8),
sharex=False, sharey=False)
plt.suptitle('Box plot of iris features')
plt.show()

线性回归模型

题目:对糖尿病数据集(datasets.oad diabetes0)进行回归分析,并输出模型的均方误差(MSE),决定系数(R?)和可视化预测值与直实值的对比,
回答:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import matplotlib.pyplot as plt

# 设置支持中文的字体,例如 SimHei(黑体)
plt.rcParams['font.family'] = 'SimHei'
# 解决负号显示问题
plt.rcParams['axes.unicode_minus'] = False

# 后续的绘图代码保持不变
import numpy as np
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score

# 加载糖尿病数据集
diabetes = datasets.load_diabetes()
X = diabetes.data
y = diabetes.target

# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 创建线性回归模型并训练
model = LinearRegression()
model.fit(X_train, y_train)

# 进行预测
y_pred = model.predict(X_test)

# 计算均方误差(MSE)和决定系数(R^2)
mse = mean_squared_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)

print(f"均方误差 (MSE): {mse}")
print(f"决定系数 (R^2): {r2}")

# 可视化预测值与真实值的对比
plt.figure(figsize=(10, 6))
plt.scatter(y_test, y_pred, color='blue', alpha=0.5)
plt.plot([y_test.min(), y_test.max()], [y_test.min(), y_test.max()], 'k--', lw=2)
plt.xlabel('真实值')
plt.ylabel('预测值')
plt.title('线性回归模型:真实值 vs 预测值')
plt.show()

决策树分类器

题目:使用 Scikit-learn 库中的决策树分类器
对鸢尾花数据集(datasets.load iis())进行分类分析,并输出模型的准确率、混淆矩阵和可视化决策树结构、可视化决策树分类结果。
回答:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier, plot_tree
from sklearn.metrics import accuracy_score, confusion_matrix
import seaborn as sns

# 1. 加载鸢尾花数据集
iris = load_iris()
X = iris.data
y = iris.target

# 2. 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

# 3. 创建决策树分类器并训练
clf = DecisionTreeClassifier(random_state=42)
clf.fit(X_train, y_train)

# 4. 模型预测
y_pred = clf.predict(X_test)

# 5. 模型评估
# 计算准确率
accuracy = accuracy_score(y_test, y_pred)
print(f"模型准确率: {accuracy}")

# 生成混淆矩阵
cm = confusion_matrix(y_test, y_pred)
print("混淆矩阵:")
print(cm)

# 可视化混淆矩阵
plt.figure(figsize=(8, 6))
sns.heatmap(cm, annot=True, fmt='d', cmap='Blues',
xticklabels=iris.target_names, yticklabels=iris.target_names)
plt.xlabel('预测类别')
plt.ylabel('真实类别')
plt.title('混淆矩阵')
plt.show()

# 6. 可视化决策树结构
plt.figure(figsize=(15, 10))
plot_tree(clf, feature_names=iris.feature_names, class_names=iris.target_names, filled=True)
plt.title('决策树结构')
plt.show()

# 7. 可视化决策树分类结果(选取前两个特征进行二维可视化)
X_2d = X[:, :2]
clf_2d = DecisionTreeClassifier(random_state=42)
clf_2d.fit(X_2d, y)

# 创建网格点
x_min, x_max = X_2d[:, 0].min() - 1, X_2d[:, 0].max() + 1
y_min, y_max = X_2d[:, 1].min() - 1, X_2d[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.02),
np.arange(y_min, y_max, 0.02))
Z = clf_2d.predict(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)

# 绘制分类边界和数据点
plt.figure(figsize=(10, 8))
plt.contourf(xx, yy, Z, alpha=0.4)
plt.scatter(X_2d[:, 0], X_2d[:, 1], c=y, edgecolors='k', alpha=0.8)
plt.xlabel(iris.feature_names[0])
plt.ylabel(iris.feature_names[1])
plt.title('决策树分类结果可视化')
plt.show()

聚类算法

问题:
对鸢尾花数据集(datasets.oad iris())进行数据预处理(如标准化),然后利用KMeans聚类算法进行无监督学习,并可视化聚类结果
回答:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import numpy as np
import matplotlib
matplotlib.use('TkAgg') # 更换为 TkAgg 后端
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import KMeans

# 设置支持中文的字体
plt.rcParams['font.family'] = 'SimHei'
# 解决负号显示问题
plt.rcParams['axes.unicode_minus'] = False

# 1. 加载鸢尾花数据集
iris = load_iris()
# 提取特征数据
X = iris.data
# 提取特征名称,用于后续绘图标注
feature_names = iris.feature_names

# 2. 数据预处理:标准化
scaler = StandardScaler()
# 对特征数据进行标准化处理
X_scaled = scaler.fit_transform(X)

# 3. KMeans 聚类
# 已知鸢尾花数据集有 3 个类别,设置聚类数为 3
kmeans = KMeans(n_clusters=3, random_state=42)
# 对标准化后的数据进行聚类
kmeans.fit(X_scaled)
# 获取聚类标签
labels = kmeans.labels_

# 4. 可视化聚类结果(选取前两个特征进行二维可视化)
plt.figure(figsize=(10, 8))

# 绘制数据点,根据聚类标签进行颜色区分
plt.scatter(X[:, 0], X[:, 1], c=labels, cmap='viridis', edgecolor='k', s=50)

# 绘制聚类中心,注意要将聚类中心的坐标转换回原始数据的尺度
centers = scaler.inverse_transform(kmeans.cluster_centers_)[:, :2]
plt.scatter(centers[:, 0], centers[:, 1], c='red', marker='X', s=200, label='聚类中心')

# 设置坐标轴标签
plt.xlabel(feature_names[0])
plt.ylabel(feature_names[1])
# 设置图形标题
plt.title('KMeans 聚类结果(鸢尾花数据集)')
# 显示图例
plt.legend()
# 显示图形
plt.show()