Skip to main content

线性回归

简单的模型预测

import pandas as pd
from matplotlib import pyplot as plt
from sklearn.linear_model import LinearRegression
import numpy as np

data = pd.read_csv('generated_data.csv')
lr_model = LinearRegression()

# 转成 1维的数组

x = np.array(x)
x = x.reshape(-1,1)
y = np.array(y)
y = y.reshape(-1,1)
print(type(x),x.shape,type(y),y.shape)

# 创建模型
lr_model.fit(x,y)

# 预测结果
y_predict = lr_model.predict(x)
print(y_predict)

# 预测单个值 注意[[]]
y_3 = lr_model.predict([[3.5]])
print(y_3)

#a\b 打印
a = lr_model.coef_
b = lr_model.intercept_
print(a,b)

# 模型评估 均方误差(MSE)越小越好, R2分数越接近1越好
from sklearn.metrics import mean_squared_error,r2_score
MSE = mean_squared_error(y,y_predict)
R2 = r2_score(y,y_predict)
print(MSE,R2)

# 图形化 y’vs y集中度越高越好(越接近直线分布)
plt.figure()
plt.plot(y,y_predict)
plt.show()

线性回归预测房价 - (涉及 单因子 和 多因子预测)

import pandas as pd
import numpy as np
data = pd.read_csv('usa_housing_price.csv')


# 图形
%matplotlib inline
from matplotlib import pyplot as plt
fig = plt.figure(figsize=(10,10))
fig1 =plt.subplot(231)
plt.scatter(data.loc[:,'Avg. Area Income'],data.loc[:,'Price'])
plt.title('Price VS Income')

fig2 =plt.subplot(232)
plt.scatter(data.loc[:,'Avg. Area House Age'],data.loc[:,'Price'])
plt.title('Price VS House Age')

fig3 =plt.subplot(233)
plt.scatter(data.loc[:,'Avg. Area Number of Rooms'],data.loc[:,'Price'])
plt.title('Price VS Number of Rooms')

fig4 =plt.subplot(234)
plt.scatter(data.loc[:,'Area Population'],data.loc[:,'Price'])
plt.title('Price VS Area Population')

fig5 =plt.subplot(235)
plt.scatter(data.loc[:,'size'],data.loc[:,'Price'])
plt.title('Price VS size')
plt.show()

# 单因子预测
X = data.loc[:,'size']
y = data.loc[:,'Price']
X = np.array(X).reshape(-1,1)
# 建立线性回归模型
from sklearn.linear_model import LinearRegression
LR1 = LinearRegression()
#train the model
LR1.fit(X,y)

#计算价格和大小
y_predict_1 = LR1.predict(X)
print(y_predict_1)

# 模型评估
from sklearn.metrics import mean_squared_error,r2_score
mean_squared_error_1 = mean_squared_error(y,y_predict_1)
r2_score_1 = r2_score(y,y_predict_1)
print(mean_squared_error_1,r2_score_1)

# 图形化结果
fig6 = plt.figure(figsize=(8,5))
plt.scatter(X,y)
plt.plot(X,y_predict_1,'r')
plt.show()

# 多因子预测
# 设置因子,去掉价格
X_multi = data.drop(['Price'],axis=1)
# 建立第二线性模型
LR_multi = LinearRegression()
# 创建模型
LR_multi.fit(X_multi,y)

#进行预测
y_predict_multi = LR_multi.predict(X_multi)
print(y_predict_multi)

# 模型评估
mean_squared_error_multi = mean_squared_error(y,y_predict_multi)
r2_score_multi = r2_score(y,y_predict_multi)
print(mean_squared_error_multi,r2_score_multi)

# 图形化
fig7 = plt.figure(figsize=(8,5))
plt.scatter(y,y_predict_multi)
plt.show()

# 根据模型进行预测
X_test = [65000,5,5,30000,200]
X_test = np.array(X_test).reshape(1,-1)
y_test_predict = LR_multi.predict(X_test)
print(y_test_predict)