目录
1.算法求解步骤
2.算法核心代码
3.算法效果展示
1.算法求解步骤
线性回归算法流程:
#1.数据导入与处理
#2.创建线性回归模型并拟合数据
#3.计算回归直线的斜率和截距
#4.预测 x=5 时的y值
#5.进行进一步预测
#5.进行进一步预测
2.算法核心代码
#机器学习算法基础第一节
#1.线性回归算法
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
#1.数据导入与处理
data = np.array([[1, 20.5], [2, 24.7], [3, 27.1], [4, 32.8], [6, 39.8]])
x = data[:, 0].reshape(-1, 1)
"""
reshape(-1,1)就是指定新数组列为1
即此时的x=[1,2,3,4,5,6]^T
"""
y = data[:, 1]
#此时的y=【20.5,24.7,27.1,32.8,39.8]
#2.创建线性回归模型并拟合数据
model = LinearRegression()
model.fit(x, y)
#3.计算回归直线的斜率和截距
slope = model.coef_[0]#model返回斜率
intercept = model.intercept_
print("回归方程的斜率是:",slope)
print("回归方程的截距是:",intercept)
#4.预测 x=5 时的y值
x_pred = np.array([[5]])
y_pred = model.predict(x_pred)
print("预测x=5的值是:",y_pred)
#5.进行进一步预测
x_pred = np.linspace(0, 7, 100).reshape(-1, 1)
y_pred = model.predict(x_pred)
#6.绘制可视化图片
plt.scatter(x, y, color='blue', label='Data points')
plt.plot(x_pred, y_pred, color='red', label='Regression line')
plt.legend(loc=3, borderaxespad=0., bbox_to_anchor=(0, 0.875))
plt.title('Linear regression prediction model',color='black')
plt.xlabel('x value range',color='r')
plt.ylabel('y value range',color='r')
plt.savefig('C:/Users/Zeng Zhong Yan/Desktop/Linear regression prediction model.png', dpi=500, bbox_inches='tight')
plt.show()