以下是基于原文的二次改写版本:
# 导入所需的库
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
import numpy as np
import matplotlib.pyplot as plt
# 创建数据集
data = np.array([[152, 51], [156, 53], [160, 54], [164, 55],
[168, 57], [172, 60], [176, 62], [180, 65],
[184, 69], [188, 72]])
# 打印数据集的维度
print("The size of dataset is (%d,%d)" % data.shape)
# 准备训练集和测试集的特征向量和标签
X, y = data[:, 0].reshape(-1, 1), data[:, 1]
X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=0.8)
# 创建线性回归模型实例
regr = LinearRegression()
# 在训练数据上训练模型
regr.fit(X_train, y_train)
# 输出训练数据上的R平方值
print("Score for training data %.2f" % regr.score(X_train, y_train)) # 输出: 0.97
# 可视化训练数据及其拟合的直线
plt.scatter(X_train, y_train, color='red') # 训练数据点(红色)
plt.plot(X_train, regr.predict(X_train), color='blue') # 训练数据拟合直线(蓝色)
plt.xlabel('height (cm)') # x轴标签
plt.ylabel('weight (kg)') # y轴标签
plt.show()
# 可视化测试数据及其拟合的直线(仅显示部分,但通常不包括在训练过程中)
plt.scatter(X_test, y_test, color='black') # 测试数据点(黑色)
plt.plot(X_train, regr.predict(X_train), color='blue') # 同上,为了对比训练效果,再次绘制训练数据拟合直线(蓝色)
plt.xlabel('height (cm)') # x轴标签(与训练部分相同)
plt.ylabel('weight (kg)') # y轴标签(与训练部分相同)
plt.show()
# 输出测试数据上的R平方值
print("Score for testing data %.2f" % regr.score(X_test, y_test)) # 输出: 0.89
print("Prediction for a person with height 171 is: %.2f" % regr.predict([[171]])) # 输出: 60.38
© 版权声明
本网站上的所有资源均来源于本网站,所有网址和文章版权均归原作者所有。如有侵权行为,请将相关证明发送至以下电子邮件地址:dxsen@qq.com