sklearn回归分析实战

sklearn回归分析实战

数据集下载链接:

链接:https://pan.baidu.com/s/1UCWFTDrrurYPOJnIHP0uJA
提取码:6666

实战--基于面积的单因子房价预测

基于课程中的房价预测案例与task1 data.csv数据,建立单因子线性回归模型,预测面积100平方米的房子售价100万是否值得投资。

 

1、完成数据加载与可视化 2、进行数据预处理: X、y赋值、格式转化、维度确认 3、建立单因子线性回归模型,训练模型 4、评估模型表现,可视化线性回归预测结果

# 数据加载
import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.metrics import r2_score

data = pd.read_csv('task1_data.csv')
# X,y赋值
X = data.loc[:, '面积']  # 提取名为“面积”的列。
y = data.loc[:, '房价']
# 转换为numpy下的np_array类
X = np.array(X)
y = np.array(y)
# 维度转化,目前计算机只知道有11行 现在告诉计算机有一列
X = X.reshape(-1, 1)  # -1表示原来有多少现在就有多少,1表示有一列
y = y.reshape(-1, 1)
# 建立线性回归模型
model = LinearRegression()
model.fit(X, y)
# #获取线性回归核心参数
# a = model.coef_
# b = model.intercept_
# 结果预测
y_predict = model.predict(X)
# #100平方米房价预测
# X_test = np.array([[100]])
# y_test_predict = model.predict(X_test)
# print(y_test_predict)
# 模型评估
R2 = r2_score(y, y_predict)
print(R2)

 

实战--多因子房价预测

基于task2data.csv数据,建立线性回归模型,预测合理房价:

1、以面积为输入变量,建立单因子模型评估模型表现,可视化线性回归预测结果 2、以面积、人均收入、房龄为输入变量建立多因子模型,评估模型表现 3、预测预测面积=150,人均收入=60000 房龄=5的合理房价

#使用单子因子模型预测
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.metrics import r2_score
data = pd.read_csv('task2_data.csv')
X = data.loc[:,'面积']
y = data.loc[:,'房价']
X = np.array(X)
y = np.array(y)
X = X.reshape(-1,1)
y = y.reshape(-1,1)
model = LinearRegression()
model.fit(X,y)
y_predict = model.predict(X)
X_test = np.array([[150]])
y_test_predict = model.predict(X_test)
R2 = r2_score(y,y_predict)
print(R2)


#使用多音字模型预测
#数据更新
X = data.drop(['房价'],axis=1) #axis=1 按列剔除数据
fig3 = plt.figure(figsize=(20,5))
fig3_1 = plt.subplot(131)
plt.scatter(X.loc[:,'面积'],y)
plt.title('Price Vs Size')
fig3_2 = plt.subplot(132)
plt.scatter(X.loc[:,'人均收入'],y)
plt.title('Price Vs income')

fig3_3 = plt.subplot(133)
plt.scatter(X.loc[:,'房龄'],y)
plt.title('Price Vs HouseAge')
# plt.show()
#建立多因子回归模型
model_multi = LinearRegression()
model_multi.fit(X,y)
y_predict_multi = model_multi.predict(X)
R2_multi = r2_score(y,y_predict_multi)
print(R2_multi)
#预测
# X_test_multi = np.array([[150,60000,5]])
# y_test_predict_multi = model_multi.predict(X_test_multi)
# print(y_test_predict_multi)

加利福尼亚房屋价值数据集预测

from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.model_selection import cross_val_score
import pandas as pd
from sklearn.datasets import fetch_california_housing as fch
from sklearn.metrics import r2_score
#导入数据集
housevalue = fch()
X = pd.DataFrame(housevalue.data)
y = housevalue.target
X.columns = housevalue.feature_names
#分训练集和测试集
Xtrain, Xtest, Ytrain, Ytest = train_test_split(X, y, test_size=0.3, random_state=420)
#恢复索引,看不懂,记得这个步骤就行,必须有
for i in [Xtrain, Xtest]:
   i.index = range(i.shape[0])

model = LinearRegression()
model.fit(Xtrain,Ytrain)
y_predict = model.predict(Xtest)

R2 = r2_score(Ytest,y_predict)
print(R2)
 

核心代码

数据加载及展示

#数据加载
import pandas as pd
import numpy as np
data =pd.read_csv('task1_data.csv)
data.head()
#xy赋值
x= data.loc[:,'面积']
y=data.loc[:,'房价']
#数据可视化
from matplotlib import pyplot as plt
fig1=plt.figure()
plt.scatter(x,y)
plt.xlabel('size(x)')
plt.ylabel('price(y)')
plt.show()

数据预处理

#数据格式转化
x=np.array(x)
y =np.array(y)
print(type(x),type(y))
print(x.shape,y.shape)

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

模型建立及训练

#创建模型实例
from sklearn.linear_model import LinearRegression
model= LinearRegression()
#模型训练
model.fit(x,y)

模型预测

#获取线性回归模型系数
a = model.coef
b = model.intercept
print(a,b,"y=f(x)=*x+f".format(a[0][0],b[0]))
#结果预测
y_predict = a[0][0]*x+ b[0]
print(y_predict)
#第二种预测的方法
y_predict2 = model.predict(x)
print(y_predict2)
#预测面积为100时,对应的价格
X_test = np.array([[100]])
y_test_p = model.predict(X test)
print(y_test_p)

结果展示及表现评估

#模型评估
from sklearn.metrics import r2_score
R2 =r2_score(yy_predict)
print(R2)
#预测结果可视化
from matplotlib import pyplot as plt
fig1=plt.figure()
plt.scatter(x,y,label='y_real')
plt.plot(x,y_predict,label='y_predict')
plt.xlabel('size(x)')
plt.ylabel('price(y)')
plt.legend()
plt.show()

图形展示

画散点图

import matplotlib.pyplot as plt
plt.scatter(x,y)

多张图同时展示

subplot子图

fig1 = plt.subplot(121) #第一个模块
plt.scatter(x1,y1)
fig2 = plt.subplot(122) #第二个模块
plt.scatter(x2,y2)

 

posted @ 2023-05-09 21:49  qfzwy  阅读(245)  评论(0)    收藏  举报