【Python】使用 Scikit-Learn 库(机器学习)

加载数据集

与您的机器学习实验数据集一起工作

from sklearn import datasets
iris = datasets.load_iris()
X, y = iris.data, iris.target

2. 将数据分为训练集和测试集

将您的数据划分,分配部分用于训练和评估:

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)

3. 训练模型

使用 randomForestClassifier 训练 ML 模型:

from sklearn.ensemble import randomForestClassifier
model = RandomForestClassifier()
model.fit(X_train, y_train)

4. 进行预测

访问模型预测:

predictions = model.predict(X_test)

5. 评估模型性能

为了评估您的模型,测量其在预测中的准确性:

from sklearn.metrics import accuracy_score
accuracy = accuracy_score(y_test, predictions)
print(f"Model accuracy: {accuracy}")

6. 使用交叉验证

使用交叉验证:

from sklearn.model_selection import cross_val_score
scores = cross_val_score(model, X, y, cv=5)
print(f"Cross-validation scores: {scores}")

7. 特征缩放

创建您特征的适当比例,使模型能够更有效地学习:

from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)

8. 网格搜索参数调整

为了优化您模型的参数,寻求最佳组合:

from sklearn.model_selection import GridSearchCV
param_grid = {'n_estimators': [10, 50, 100], 'max_depth': [None, 10, 20]}
grid_search = GridSearchCV(model, param_grid, cv=5)
grid_search.fit(X_train, y_train)

9. 管道创建

为了简化您的数据处理和建模步骤,打造一个无缝的流程:

from sklearn.pipeline import Pipeline
pipeline = Pipeline([
    ('scaler', StandardScaler()),
    ('classifier', RandomForestClassifier())
])
pipeline.fit(X_train, y_train)

10. 保存和加载模型

为了保护您的模型:

import joblib
# Saving the model
joblib.dump(model, 'model.joblib')
# Loading the model
loaded_model = joblib.load('model.joblib')

使用 Plotly 库(交互式数据可视化

创建基本折线图

创建折线图:

import plotly.graph_objs as go
import plotly.io as pio
x = [1, 2, 3, 4, 5]
y = [1, 4, 9, 16, 25]
fig = go.Figure(data=go.Scatter(x=x, y=y, mode='lines'))
pio.show(fig)

创建散点图

创建散点图:

fig = go.Figure(data=go.Scatter(x=x, y=y, mode='markers'))
pio.show(fig)

3. 创建柱状图

创建柱状图:

categories = ['A', 'B', 'C', 'D', 'E']
values = [10, 20, 15, 30, 25]
fig = go.Figure(data=go.Bar(x=categories, y=values))
pio.show(fig)

4. 创建饼图

创建饼图:

labels = ['Earth', 'Water', 'Fire', 'Air']
sizes = [25, 35, 20, 20]
fig = go.Figure(data=go.Pie(labels=labels, values=sizes))
pio.show(fig)

5. 创建直方图

创建直方图:

data = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
fig = go.Figure(data=go.Histogram(x=data))
pio.show(fig)

6. 创建箱线图

创建箱线图:

data = [1, 2, 2, 3, 4, 4, 4, 5, 5, 6]
fig = go.Figure(data=go.Box(y=data))
pio.show(fig)

7. 创建热图

创建热图:

import numpy as np
z = np.random.rand(10, 10)  # Generate random data
fig = go.Figure(data=go.Heatmap(z=z))
pio.show(fig)

8. 创建 3D 曲面图

创建 3D 曲面图:

z = np.random.rand(20, 20)  # Generate random data
fig = go.Figure(data=go.Surface(z=z))
pio.show(fig)

9. 创建子图

创建子图:

from plotly.subplots import make_subplots
fig = make_subplots(rows=1, cols=2)
fig.add_trace(go.Scatter(x=x, y=y, mode='lines'), row=1, col=1)
fig.add_trace(go.Bar(x=categories, y=values), row=1, col=2)
pio.show(fig)

10. 创建交互式时间序列

与时间序列一起工作:

import pandas as pd
dates = pd.date_range('20230101', periods=5)
values = [10, 11, 12, 13, 14]
fig = go.Figure(data=go.Scatter(x=dates, y=values, mode='lines+markers'))
pio.show(fig)