import matplotlib as mpl import matplotlib.pyplot as plt import pandas as pd from sklearn.linear_model import LinearRegression import numpy as np from sklearn.metrics import mean_absolute_error from sklearn.metrics import mean_squared_error from sklearn.metrics import r2_score mpl.rcParams['font.sans-serif']=['KaiTi'] mpl.rcParams['axes.unicode_minus']= False data=pd.read_csv('data.csv') #print(data.head) data.dropna(axis=0,how='any',inplace=True) data['单价']=data['单价'].map(lambda d:d.replace('元/平米','')) data['单价']=data['单价'].astype(float) data['总价']=data['总价'].map(lambda e:e.replace('万','')) data['总价']=data['总价'].astype(float) data['建筑面积']=data['建筑面积'].map(lambda p:p.replace('平米','')) data['建筑面积']=data['建筑面积'].astype(float) copy_d=data.copy() copy_d[['室','厅','卫']]=copy_d['户型'].str.extract('(\d+)室(\d+)厅(\d+)卫') copy_d['室']=copy_d['室'].astype(float) new_data=data[['总价','建筑面积']] new_data['室']=copy_d['室'] new_data.dropna(axis=0,how='any',inplace=True) print(new_data) new_data.loc[2583]=[None,180.00,4] data_train=new_data.loc[0:2582] x_list=['建筑面积','室'] ndata_mean=data_train.mean() ndata_std=data_train.std() data_train=(data_train-ndata_mean)/ndata_std x_train=data_train[x_list].values y_train=data_train['总价'].values svr=LinearRegression() svr.fit(x_train,y_train) x_test=((new_data[x_list]-ndata_mean[x_list])/ndata_std[x_list]).values y_test=((new_data['总价']-ndata_mean['总价'])/ndata_std).values print(y_test) y_pred=svr.predict(x_test) new_data['y_pred']=y_test*ndata_std['总价']+ndata_mean['总价'] print(new_data[['总价','y_pred']]) svr_acc=svr.score(x_test,y_test)*100 svr_mae=mean_absolute_error(x_test,y_pred) print(svr_mae)
时间: 2024-01-19 15:02:35 浏览: 125
import numpy as np import matplotlib.pyplot as plt import math
这段代码主要是使用线性回归模型对房价进行预测,其中使用了 pandas 和 sklearn 进行数据的处理和模型的建立。具体来说,代码首先读取了一个 csv 文件,并进行了一些数据清洗,然后对数据进行了特征工程,提取出了室、厅、卫等特征,并将其转化为数值类型。接着将数据集分为训练集和测试集,使用训练集对线性回归模型进行训练,最后对测试集进行预测,并计算了模型的精度和误差等指标。
阅读全文