通往 AI 之路:Python 机器学习入门-机器学习基本概念

机器学习基本概念

机器学习是人工智能的重要分支,它依赖数学和统计学方法来构建模型,处理和分析数据。本章介绍了机器学习的基本概念,包括监督学习与无监督学习的区别,数据集的划分方式,过拟合与欠拟合的问题,以及交叉验证的方法。这些基础知识对理解和应用机器学习至关重要。


1. 监督学习 vs 无监督学习

1.1 监督学习

监督学习(Supervised Learning)是一种学习方法,它使用带有标签的数据进行训练,使模型能够学习输入与输出之间的映射关系。

监督学习的常见算法:
  • 线性回归(Linear Regression)
  • 逻辑回归(Logistic Regression)
  • 支持向量机(SVM)
  • 决策树(Decision Tree)
  • 随机森林(Random Forest)
  • 神经网络(Neural Networks)
示例:使用 Scikit-learn 进行监督学习
python 复制代码
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
import numpy as np

# 生成数据
X = np.array([[1], [2], [3], [4], [5]])
y = np.array([2, 4, 6, 8, 10])

# 划分训练集和测试集
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)

# 预测
predictions = model.predict(X_test)
print("预测值:", predictions)

1.2 无监督学习

无监督学习(Unsupervised Learning)是指没有标签的数据,模型需要自己发现数据中的模式或结构。

无监督学习的常见算法:
  • 聚类(Clustering):K-Means、DBSCAN、层次聚类
  • 降维(Dimensionality Reduction):PCA、t-SNE、LDA
示例:使用 K-Means 进行聚类
python 复制代码
from sklearn.cluster import KMeans
import numpy as np

# 生成数据
X = np.array([[1, 2], [1, 4], [1, 0], [10, 2], [10, 4], [10, 0]])

# K-Means 聚类
kmeans = KMeans(n_clusters=2, random_state=42)
kmeans.fit(X)
labels = kmeans.labels_
print("聚类标签:", labels)

2. 训练集、测试集、验证集

在机器学习任务中,我们通常将数据集划分为:

  • 训练集(Training Set):用于训练模型
  • 验证集(Validation Set):用于调整超参数
  • 测试集(Test Set):用于评估最终模型性能
python 复制代码
from sklearn.model_selection import train_test_split
import numpy as np

# 生成数据
X = np.arange(1, 101).reshape(-1, 1)
y = np.arange(1, 101)

# 划分训练集(60%)、验证集(20%)、测试集(20%)
X_train, X_temp, y_train, y_temp = train_test_split(X, y, test_size=0.4, random_state=42)
X_val, X_test, y_val, y_test = train_test_split(X_temp, y_temp, test_size=0.5, random_state=42)

3. 过拟合与欠拟合

3.1 过拟合(Overfitting)

  • 训练集上的表现很好,但测试集上的表现很差。
  • 解决方案:使用正则化(L1/L2)、增加数据量、降低模型复杂度。

3.2 欠拟合(Underfitting)

  • 模型过于简单,无法捕捉数据中的模式。
  • 解决方案:增加模型复杂度、增加特征、使用更强的算法。
python 复制代码
from sklearn.linear_model import Ridge

# 使用 L2 正则化(Ridge 回归)
ridge = Ridge(alpha=1.0)
ridge.fit(X_train, y_train)

4. 交叉验证(Cross Validation)

交叉验证是一种评估模型性能的技术,可以减少模型对训练数据的依赖,提高泛化能力。

4.1 K 折交叉验证(K-Fold Cross Validation)

将数据集分成 K 份,轮流使用其中 K-1 份训练,1 份测试。

python 复制代码
from sklearn.model_selection import KFold, cross_val_score
from sklearn.linear_model import LinearRegression

kf = KFold(n_splits=5)
model = LinearRegression()
scores = cross_val_score(model, X, y, cv=kf)
print("K 折交叉验证得分:", scores)

4.2 分层 K 折交叉验证(Stratified K-Fold)

适用于类别不均衡数据。

python 复制代码
from sklearn.model_selection import StratifiedKFold
from sklearn.datasets import load_iris

X, y = load_iris(return_X_y=True)
skf = StratifiedKFold(n_splits=5)

4.3 留一法(LOO,Leave-One-Out)

每次使用 n-1 个样本训练,剩下 1 个样本测试。

python 复制代码
from sklearn.model_selection import LeaveOneOut
loo = LeaveOneOut()
scores = cross_val_score(model, X, y, cv=loo)
print("LOO 交叉验证得分:", scores.mean())

4.4 随机分割交叉验证(Shuffle Split)

适用于大数据集,减少计算量。

python 复制代码
from sklearn.model_selection import ShuffleSplit
ss = ShuffleSplit(n_splits=5, test_size=0.2, random_state=42)
scores = cross_val_score(model, X, y, cv=ss)

4.5 时间序列交叉验证

适用于时间序列数据,不能随机分割。

python 复制代码
from sklearn.model_selection import TimeSeriesSplit
tscv = TimeSeriesSplit(n_splits=3)
scores = cross_val_score(model, X, y, cv=tscv)

结论

本章介绍了机器学习的基本概念,包括监督学习与无监督学习、数据集划分、过拟合与欠拟合以及交叉验证方法。理解这些基础知识可以帮助我们更好地训练和优化机器学习模型。

相关推荐
闲人编程1 小时前
将你的旧手机变成监控摄像头(Python + OpenCV)
python·opencv·智能手机·监控·codecapsule·oasis
007php0071 小时前
大厂深度面试相关文章:深入探讨底层原理与高性能优化
java·开发语言·git·python·面试·职场和发展·性能优化
SunnyDays10112 小时前
Python 复制和移动 Excel 工作表并保留所有格式:详解
python·复制excel工作表·移动excel工作表·重新排列excel工作表
FreeCode2 小时前
LangChain1.0智能体开发:运行时(Runtime)
人工智能·langchain·agent
柳安忆2 小时前
【论文阅读与项目复现】Hypothesis Generation with Large Language Models
论文阅读·人工智能·语言模型
汉克老师2 小时前
CCF--LMCC大语言模型能力认证官方样题(第一赛(青少年组)第二部分 程序题 (26--30))
人工智能·语言模型·自然语言处理·lmcc
无名之辈J2 小时前
库存预扣减之后,用户订单超时之后补偿库存的方案
后端
Mr_Oak2 小时前
【multi-model】moco系列&SimCLR&BEiT
人工智能·深度学习·神经网络·算法·计算机视觉·transformer·对比学习
小白跃升坊2 小时前
信息检索类智能体构建范式
人工智能·ai·全文检索·智能体
不会编程的小寒2 小时前
C++初始继承,继承中构造、析构顺序
开发语言·python