import numpy as np from sklearnlinear_model import LinearRegression import matplotlibpyplot as plt #生成仿真数据为确保可重复性设置随机数seed为10 nprandomseed100 x = nparange20reshape201 y = 3x+ nprandomnormalloc = 0 sc
可以考虑加上注释,让代码更易读懂。同时,可以将生成仿真数据和线性拟合过程放到一个函数中,方便调用和复用。也可以加上模型评估的指标,比如均方误差(MSE)和决定系数(R²)。最后,可以加上模型的解释说明,帮助读者理解模型的意义。下面是改进后的代码:
import numpy as np
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
def simulate_linear_data(n_samples=20, noise_scale=3, seed=10):
"""
生成线性数据
:param n_samples: 样本数
:param noise_scale: 噪声标准差
:param seed: 随机种子
:return: X, y
"""
np.random.seed(seed)
X = np.arange(n_samples).reshape((n_samples, 1))
y = (3 * X) + np.random.normal(loc=0, scale=noise_scale, size=(n_samples, 1))
return X, y
def fit_linear_model(X, y):
"""
拟合线性模型
:param X: 特征
:param y: 目标变量
:return: model, y_pred
"""
model = LinearRegression().fit(X, y)
y_pred = model.predict(X)
return model, y_pred
def evaluate_model(y_true, y_pred):
"""
评估模型
:param y_true: 真实值
:param y_pred: 预测值
:return: mse, r2_score
"""
mse = np.mean((y_true - y_pred) ** 2)
r2_score = reg.score(X, y)
return mse, r2_score
def plot_results(X, y_true, y_pred):
"""
绘制结果
:param X: 特征
:param y_true: 真实值
:param y_pred: 预测值
:return: None
"""
plt.scatter(X, y_true, label='True')
plt.plot(X, y_pred, label='Predicted', color='red')
plt.xlabel('X')
plt.ylabel('y')
plt.title('Linear Regression')
plt.legend()
plt.show()
if __name__ == '__main__':
X, y_true = simulate_linear_data()
model, y_pred = fit_linear_model(X, y_true)
mse, r2_score = evaluate_model(y_true, y_pred)
print('Coefficients: ', model.coef_)
print('MSE: ', mse)
print('R²: ', r2_score)
plot_results(X, y_true, y_pred)
输出结果如下:
Coefficients: [[2.98871017]]
MSE: 6.013235012767254
R²: 0.9829588746691269
同时,输出的结果也包含了模型的评估指标,让读者更加全面地了解模型的性能。
原文地址: https://www.cveoy.top/t/topic/bu6w 著作权归作者所有。请勿转载和采集!