数据准备
数据为安居客二手房信息
![](https://i-blog.csdnimg.cn/blog_migrate/2eb8d2c5d267410204b0ed10a39e2461.png)
代码预测
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction import DictVectorizer
from sklearn.linear_model import LinearRegression,SGDRegressor
from sklearn.preprocessing import StandardScaler
#导入均方误差,评价回归
from sklearn.metrics import mean_squared_error,r2_score
df = pd.read_excel('housedata.xlsx')
#使用pandas对数据进行前处理
df['面积'] = df['面积'].str.replace('㎡','')
#print(len(np.unique(df['楼层'])))
df['楼层'] = df['楼层'].apply(lambda x: np.where('(' in x,x[0:2],x))
df['建筑年份'] = df['建筑年份'].str.replace('年建造','')
df['单价'] = df['单价'].str.replace('元/㎡','')
df['单价'] = df['单价'].apply(lambda x:int(x))
df['建筑年份'] = df['建筑年份'].apply(lambda x:int(x))
df['面积'] = df['面积'].apply(lambda x:float(x))
#去重
df1 = df.drop_duplicates()
#机器学习
y = pd.DataFrame(df1['单价'])
x = df1.drop('单价',axis=1)
#1、进行分为测试集和训练集
x_train,x_test,y_train,y_test = train_test_split(x,y,test_size=0.25)
#2、进行one-hot编码
dict = DictVectorizer(sparse=False)
x_train = dict.fit_transform(x_train.to_dict(orient='records'))
print(dict.get_feature_names())
x_test = dict.transform(x_test.to_dict(orient='records'))
#3.进行标准化,特征值和目标值都需要进行标准化
#特征值标准化
#print('标准化前:',x_test)
stand_x = StandardScaler()
x_train = stand_x.fit_transform(x_train)
x_test = stand_x.transform(x_test)
#目标值标准化,要将目标值变为二维的,reshape(-1, 1)是将数据变成n行,1列,n是根据原始数据计算的
stand_y = StandardScaler()
y_train = stand_y.fit_transform(y_train)
y_test = stand_y.transform(y_test)
#4.estimator预测
#正规方程求解方式预约结果
lr = LinearRegression()
lr.fit(x_train,y_train)
#回归系数w
print('正规方程计算回归系数:',lr.coef_)
print('正规方程计算常数项:',lr.intercept_)
#预测标准化之后的房屋价格
y_predict_after_zg = lr.predict(x_test)
print('正规方程预测标准化之后的房屋价格:',y_predict_after_zg)
#预测标准化之前的房屋价格,inverse_transform是将数据转换为标准化之前的数据
y_predict_before_zg = stand_y.inverse_transform(lr.predict(x_test))
print('正规方程预测标准化之前的房屋价格:',y_predict_before_zg)
print('正规方程的均方误差是:',mean_squared_error(stand_y.inverse_transform(y_test),y_predict_before_zg))
#梯度下降法预测房价,ravel()方法将数组维度拉成一维数组,将目标值转换,负责梯度下降法计算时会发出警告信息
sgd = SGDRegressor()
sgd.fit(x_train,y_train.ravel())
#回归系数w
print('梯度下降法计算回归系数:',sgd.coef_)
print('梯度下降法计算常数项:',sgd.intercept_)
#预测标准化之后的房屋价格
y_predict_after_sgd = sgd.predict(x_test)
print('梯度下降法预测标准化之后的房屋价格:',y_predict_after_sgd)
#预测标准化之前的房屋价格,inverse_transform是将数据转换为标准化之前的数据
y_predict_before_sgd = stand_y.inverse_transform(sgd.predict(x_test))
print('特征是:',dict.inverse_transform(stand_x.inverse_transform(x_test)))
print('梯度下降法预测标准化之前的房屋价格:',y_predict_before_sgd)
print('梯度下降法的均方误差是:',mean_squared_error(stand_y.inverse_transform(y_test),y_predict_before_sgd))
print(r2_score(stand_y.inverse_transform(y_test),y_predict_before_sgd))
print(lr.score(x_test,y_test))
print(sgd.score(x_test,y_test))
print('影响房价特征排序:',np.argsort(lr.coef_))
#特征值名字
print('特征值名字:',dict.get_feature_names())
print('影响房价特征排序:',np.array(dict.get_feature_names())[np.argsort(lr.coef_)])
#5.预测房价
x1 = pd.DataFrame([['古井上善名郡',126,'南','中层','3室2厅1卫','亳州万达广场',2019],['建投世纪城',114,'南','高层','3室2厅1卫','缤纷城',2014]])
x1.columns = ['小区名','面积','朝向','楼层','布局','位置','建筑年份']
print(type(x1.iloc[0,0]))
#one-hot编码
x_te = dict.transform(x1.to_dict(orient='records'))
print(x_te)
#标准化
x_st = stand_x.transform(x_te)
#预测,转换为标准化之前的价格
y_predict= stand_y.inverse_transform(lr.predict(x_st))
print('预测标准化之前的房屋价格:',y_predict)
#print(np.unique(res['address']))
![](https://i-blog.csdnimg.cn/blog_migrate/6be95440dade042d5376f7dc501a14c0.png)