线性回归
1 一元线性回归
如下对y=2x+7的一次函数进行了模拟回归,其中coef_是斜率,intercept_是截距.
mport matplotlib.pyplot as plt import numpy as np from sklearn import linear_model from sklearn.metrics import mean_squared_error, r2_score y = [9,11,13,15,17] x_train= np.arange( 1, 6, 1).reshape([-1,1]) x_test = np.array([[6],[7]]) y_test = [18,22] # 建一个对象并使用训练集训练模型 regr = linear_model.LinearRegression() regr.fit(x_train, y) y_pred = regr.predict(x_test) # 查看系数 print('斜率是: ', regr.coef_) print('截距是: ', regr.intercept_) # # 查看均方误差 # print("Mean squared error: %.2f" % mean_squared_error(y_test, y_pred)) # # 解释方差分数:1是完美的预测 # print('Variance score: %.2f' % r2_score(y_test, y_pred)) plt.scatter(x_train, y, color='black') plt.scatter(x_test, y_test, color='green') # 回归直线用蓝色表示 plt.plot(x_train, regr.predict(x_train), color='blue', linewidth=3) # 预测直线用红色表示 plt.plot(x_test, regr.predict(x_test), color='red', linewidth=3) plt.xticks(()) plt.yticks(()) plt.show()
import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression #导入机器学习库中的线性回归模块 data=pd.DataFrame({'square_feet':[150,200,250,300,350,400,600], 'price':[5450,6850,8750,9650,10450,13450,16450]}) #创建一组7行2列的数据,square_feet为房屋面积,price为对应价格 data_train=np.array(data['square_feet']).reshape(data['square_feet'].shape[0],1)#这里是将数据转化为一个1维矩阵 print(type(data_train)) print(data_train) data_test=data['price'] #创建线性回归模型,拟合面积与价格并通过面积预测价格 regr=LinearRegression() #创建线性回归模型,参数默认 # 这里的fit()中的第一个参数必须是二维数组才行,否则报错 regr.fit(data_train,data_test)#拟合数据,square_feet将房屋面积作为x,price价格作为y;也可以理解用面积去预测价格 a=regr.predict([[268.5]]) print(a)#查看预测结果 print(regr.score(data_train,data_test))#查看拟合准确率情况,这里的检验是 R^2 ,趋近于1模型拟合越好 #预测的结果:268.5平的房子价格为8833.54, R^2 =0.967 #我们来画个图看一下数据最后是什么样的 plt.scatter(data['square_feet'],data['price']) #画散点图看实际面积和价格的分布情况 plt.plot(data['square_feet'],regr.predict(np.array(data['square_feet']).reshape(data['square_feet'].shape[0],1)),color='red') #画拟合面积与价格的线型图 plt.show()