寒假打卡27-2月14日

机器学习基础

在本篇文章中,我们将介绍机器学习的基础知识,包括常见的机器学习算法、数据预处理、模型训练与评估等内容。我们将使用 scikit-learn 库,它是一个功能强大且易于使用的机器学习库。

1. 安装 scikit-learn

首先,我们需要安装 scikit-learn。可以使用以下命令通过 pip 安装:

pip install scikit-learn

2. 数据预处理

在进行机器学习之前,我们需要对数据进行预处理,包括处理缺失值、编码分类变量、标准化数据等。

处理缺失值

使用 pandas 处理缺失值。

import pandas as pd

# 读取 CSV 文件
df = pd.read_csv('data.csv')

# 处理缺失值
df = df.dropna()  # 删除包含缺失值的行
# df = df.fillna(0)  # 用 0 填充缺失值

print(df.head())

编码分类变量

使用 scikit-learnLabelEncoder 编码分类变量。

from sklearn.preprocessing import LabelEncoder

# 示例数据
data = {'color': ['red', 'blue', 'green', 'blue', 'red']}
df = pd.DataFrame(data)

# 编码分类变量
encoder = LabelEncoder()
df['color_encoded'] = encoder.fit_transform(df['color'])

print(df)

标准化数据

使用 scikit-learnStandardScaler 标准化数据。

from sklearn.preprocessing import StandardScaler

# 示例数据
data = {'height': [1.80, 1.65, 1.75, 1.70, 1.60], 'weight': [80, 60, 75, 70, 55]}
df = pd.DataFrame(data)

# 标准化数据
scaler = StandardScaler()
df[['height', 'weight']] = scaler.fit_transform(df[['height', 'weight']])

print(df)

3. 常见机器学习算法

线性回归

使用 scikit-learn 进行线性回归。

from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error

# 示例数据
data = {'height': [1.80, 1.65, 1.75, 1.70, 1.60], 'weight': [80, 60, 75, 70, 55]}
df = pd.DataFrame(data)

# 拆分数据集
X = df[['height']]
y = df['weight']
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 = mean_squared_error(y_test, y_pred)
print(f'Mean Squared Error: {mse}')

逻辑回归

使用 scikit-learn 进行逻辑回归。

from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score

# 示例数据
data = {'feature1': [1, 2, 3, 4, 5], 'feature2': [5, 4, 3, 2, 1], 'label': [0, 0, 1, 1, 1]}
df = pd.DataFrame(data)

# 拆分数据集
X = df[['feature1', 'feature2']]
y = df['label']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 训练模型
model = LogisticRegression()
model.fit(X_train, y_train)

# 预测
y_pred = model.predict(X_test)

# 评估模型
accuracy = accuracy_score(y_test, y_pred)
print(f'Accuracy: {accuracy}')

K 近邻算法

使用 scikit-learn 进行 K 近邻算法分类。

from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score

# 示例数据
data = {'feature1': [1, 2, 3, 4, 5], 'feature2': [5, 4, 3, 2, 1], 'label': [0, 0, 1, 1, 1]}
df = pd.DataFrame(data)

# 拆分数据集
X = df[['feature1', 'feature2']]
y = df['label']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 训练模型
model = KNeighborsClassifier(n_neighbors=3)
model.fit(X_train, y_train)

# 预测
y_pred = model.predict(X_test)

# 评估模型
accuracy = accuracy_score(y_test, y_pred)
print(f'Accuracy: {accuracy}')

4. 模型训练与评估

交叉验证

使用 scikit-learn 进行交叉验证。

from sklearn.model_selection import cross_val_score
from sklearn.linear_model import LogisticRegression

# 示例数据
data = {'feature1': [1, 2, 3, 4, 5], 'feature2': [5, 4, 3, 2, 1], 'label': [0, 0, 1, 1, 1]}
df = pd.DataFrame(data)

# 特征和标签
X = df[['feature1', 'feature2']]
y = df['label']

# 训练模型并进行交叉验证
model = LogisticRegression()
scores = cross_val_score(model, X, y, cv=5)

print(f'Cross-Validation Scores: {scores}')
print(f'Mean Score: {scores.mean()}')

网格搜索

使用 scikit-learn 进行网格搜索以优化模型参数。

from sklearn.model_selection import GridSearchCV
from sklearn.svm import SVC

# 示例数据
data = {'feature1': [1, 2, 3, 4, 5], 'feature2': [5, 4, 3, 2, 1], 'label': [0, 0, 1, 1, 1]}
df = pd.DataFrame(data)

# 特征和标签
X = df[['feature1', 'feature2']]
y = df['label']

# 定义参数网格
param_grid = {'C': [0.1, 1, 10], 'kernel': ['linear', 'rbf']}

# 进行网格搜索
model = SVC()
grid_search = GridSearchCV(model, param_grid, cv=5)
grid_search.fit(X, y)

print(f'Best Parameters: {grid_search.best_params_}')
print(f'Best Score: {grid_search.best_score_}')

总结

在本篇文章中,我们介绍了机器学习的基础知识,包括数据预处理、常见的机器学习算法(线性回归、逻辑回归、K 近邻算法)以及模型训练与评估(交叉验证、网格搜索)。通过掌握这些知识,你能够构建和优化基本的机器学习模型,为实际应用中的数据分析和预测打下基础。接下来,我们将探讨深度学习基础的相关内容,敬请期待!

posted @ 2025-02-14 20:00  aallofitisst  阅读(24)  评论(0)    收藏  举报