如何使用 Python 的 Scikitlearn 库进行机器学习算法评估?
步骤:
- 导入必要的库
import sklearn.model_selection as train_test_split
- 加载数据
X_train, X_test, y_train, y_test = train_test_split.train_test_split(X_train, y_train, test_size=0.2)
- 创建评估指标
from sklearn.metrics import accuracy_score
accuracy = accuracy_score(y_test, y_pred)
- 训练模型
from sklearn.linear_model import LinearRegression
model = LinearRegression()
model.fit(X_train, y_train)
- 评估模型
y_pred = model.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print(f"Accuracy: {accuracy}")
示例代码:
import sklearn.model_selection as train_test_split
import numpy as np
# 加载数据
X_train = np.load('train_data.npy')
y_train = np.load('train_labels.npy')
# 创建评估指标
accuracy = train_test_split.accuracy_score
# 训练模型
model = LinearRegression()
model.fit(X_train, y_train)
# 评估模型
y_pred = model.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
# 打印结果
print(f"Accuracy: {accuracy}")
注意:
-
train_size
参数控制测试集的大小。 -
accuracy_score
函数返回模型在测试集上的准确率。 - 可以使用其他评估指标,例如
precision
、recall
和F1-score
。