【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)