- 导入需要的库文件
import numpy as np
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
- 自己产生随机数字
array_size = 300
np.random.seed(0)
X = np.random.randn(array_size).reshape(-1, 1)
np.random.seed(12)
y = np.dot(X, 5) + np.random.randn(array_size).reshape(-1, 1)
- 训练模型以及查看模型参数
Linear = LinearRegression()
reg = Linear.fit(X, y)
reg_Score = reg.score(X, y)
reg_Coef = reg.coef_
reg_intercept_ = reg.intercept_
reg_Predict = reg.predict([[8]])
print(reg_Score, reg_Coef, reg_intercept_, reg_Predict)
- 绘制图形
line_X = np.arange(X.min(), X.max())[:, np.newaxis]
line_y = reg.predict(line_X)
plt.scatter(X, y, c='black', s=50)
plt.plot(line_X, line_y, c='cornflowerblue', linewidth=10)
plt.show()