#使用sklearn提供的接口实现线性回归
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# 加载数据集
data = pd.read_csv('../data_test/Salary_Data.csv')
x = data['YearsExperience']
y = data['Salary']
#整理数据
train_x = pd.DataFrame(x)
train_y = y
plt.scatter(x,y)
import sklearn.linear_model as lm #线性模型
model = lm.LinearRegression() #y = w1*x + w0
model.fit(train_x,train_y) #执行梯度下降,寻找最优超参数
pred_y = model.predict(train_x)
print('权重w1:',model.coef_)
print('偏置w0:',model.intercept_)
# 绘制回归线
plt.scatter(x,y,color='dodgerblue',s=60)
plt.plot(x,pred_y,color='orangered')
要点:
训练数据,用于模型训练,不能参加测试
测试数据,用于模型的评估,不能参加训练
从样本数据中,拿到一部分数据,用于模型的测试(假设测试数据没有参加过训练)¶
#测试集数据(没有参加过训练)
test_x = train_x.iloc[::4]
test_y = train_y[::4] #真实值
pred_test_y = model.predict(test_x) #预测值
import sklearn.metrics as sm #模型评估模块
#平均绝对误差
print(sm.mean_absolute_error(test_y,pred_test_y)) #先给真实值,再给预测值
#均方误差
print(sm.mean_squared_error(test_y,pred_test_y))
# 中位数绝对偏差
print(sm.median_absolute_error(test_y,pred_test_y))
# r2得分
print(sm.r2_score(test_y,pred_test_y))
#模型的保存
import pickle
with open('model.pickle','wb') as f:
pickle.dump(model,f)
print('模型保存成功')
#模型的加载
with open('./model.pickle','rb') as f:
new_model = pickle.load(f)
new_model.predict([[1.1],[15.1]])