machine learning自定义数据集使用框架的线性回归方法对其进行拟合
使用框架(如Scikit-learn)对自定义数据集进行线性回归拟合是一个常见的任务。以下是一个详细的步骤指南,展示如何使用Scikit-learn库在Python中完成这一任务
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score
import matplotlib.pyplot as plt
# 示例数据
X = np.array([[1], [2], [3], [4], [5]]) # 特征,形状为 (n_samples, n_features)
y = np.array([1, 3, 2, 3, 5]) # 目标
# 拆分数据集
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)
r2 = r2_score(y_test, y_pred)
print(f"Mean Squared Error: {mse}")
print(f"R^2 Score: {r2}")
# 可视化结果
plt.scatter(X, y, color='blue', label='Data')
plt.plot(X_test, y_pred, color='red', linewidth=2, label='Regression Line')
plt.xlabel('X')
plt.ylabel('y')
plt.legend()
plt.show()