知识代码
# 一元线性回归代码实现
# 【1】导入资源包
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
# 【2】加载样本数据,核心是给x,y赋值
x = [[1], [2], [4], [5]]
y = [2,6,8,15]
#【3】模型搭建
lr = LinearRegression()
#【4】模型训练
lr.fit(x,y)
#【5】模型预测
res = lr.predict([[10]])
print(res)
#拓展
#【6】显示模型参数
print('回归系数a:',str(lr.coef_))
print('截距b:',str(lr.intercept_))
print('模型函数: y = ',str(lr.coef_[0]),'*x +',str(lr.intercept_))
#【7】样本及模型可视化
plt.scatter(x,y)
plt.plot(x,lr.predict(x))
plt.show()
案例一:
需求
分析AI专业学生学习时长和最终成绩的关系
数据
学习时长 | 最终成绩 |
120 | 100 |
1 | 0 |
2 | 0 |
10 | 20 |
50 | 70 |
90 | 80 |
70 | 63 |
100 | 90 |
代码:
# 【1】导入资源包
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
import pandas as pd
# 【2】加载样本数据,核心是给x,y赋值
df = pd.read_excel('data.xlsx')
print(df.head())
x = df[['学习时长']]
y = df['最终成绩']
#【3】模型搭建
lr = LinearRegression()
#【4】模型训练
lr.fit(x,y)
#【5】模型预测
res = lr.predict([[73]])
print(res)
#拓展
#【6】显示模型参数
print('回归系数a:',str(lr.coef_))
print('截距b:',str(lr.intercept_))
print('模型函数: y = ',str(lr.coef_[0]),'*x +',str(lr.intercept_))
#【7】样本及模型可视化
plt.scatter(x,y)
plt.plot(x,lr.predict(x))
plt.show()