波士顿房价估计

news/2024/10/25 3:27:12/

一、导入模块

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
plt.rcParams['font.sans-serif'] = ['SimHei']

二、载入数据

from sklearn import datasets
# 加载波士顿房价的数据集
boston = datasets.load_boston()
print(boston)

打印结果:
在这里插入图片描述
在这里插入图片描述

# 先要查看数据的类型,是否有空值,数据的描述信息等等。
boston_df = pd.DataFrame(boston.data, columns=boston.feature_names)
boston_df['PRICE'] = boston.target
# 先要查看数据的类型,是否有空值,数据的描述信息等等。
boston_df = pd.DataFrame(boston.data, columns=boston.feature_names)
boston_df['PRICE'] = boston.target
# 先要查看数据的类型,是否有空值,数据的描述信息等等。
boston_df = pd.DataFrame(boston.data, columns=boston.feature_names)
boston_df['PRICE'] = boston.target
# 查看数据的描述信息,在描述信息里可以看到每个特征的均值,最大值,最小值等信息。
boston_df.describe()
# 清洗'PRICE' = 50.0 的数据
boston_df = boston_df.loc[boston_df['PRICE'] != 50.0]

三、数据可视化

# 计算每一个特征和房价的相关系数
boston_df.corr()['PRICE']
# 可以看出LSTAT、PTRATIO、RM三个特征的相关系数大于0.5,这三个特征和价格都有明显的线性关系。
plt.figure(facecolor='gray')
corr = boston_df.corr()
corr = corr['PRICE']
corr[abs(corr) > 0.5].sort_values().plot.bar()

结果:
在这里插入图片描述

# LSTAT 和房价的散点图
plt.figure(facecolor='gray')
plt.scatter(boston_df['LSTAT'], boston_df['PRICE'], s=30, edgecolor='white')
plt.title('LSTAT')
plt.show()

结果:
在这里插入图片描述

# PTRATIO 和房价的散点图
plt.figure(facecolor='gray')
plt.scatter(boston_df['PTRATIO'], boston_df['PRICE'], s=30, edgecolor='white')
plt.title('PTRATIO')
plt.show()

结果:
在这里插入图片描述

# RM 和房价的散点图
plt.figure(facecolor='gray')
plt.scatter(boston_df['RM'], boston_df['PRICE'], s=30, edgecolor='white')
plt.title('RM')
plt.show()

结果:
在这里插入图片描述

四、数据预处理

#异常数据处理
boston_df = boston_df[['LSTAT', 'PTRATIO', 'RM', 'PRICE']]
# 目标值
y = np.array(boston_df['PRICE'])
boston_df = boston_df.drop(['PRICE'], axis=1)
# 特征值
X = np.array(boston_df)
#划分训练集与测试集
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.2,random_state=0)
print(X_train.shape, X_test.shape, y_train.shape, y_test.shape)

结果:
在这里插入图片描述

#数据统一化
from sklearn import preprocessing
# 初始化标准化器
min_max_scaler = preprocessing.MinMaxScaler()
# 分别对训练和测试数据的特征以及目标值进行标准化处理
X_train = min_max_scaler.fit_transform(X_train)
y_train = min_max_scaler.fit_transform(y_train.reshape(-1,1)) # reshape(-1,1)指将它转化为1列,行自动确定
X_test = min_max_scaler.fit_transform(X_test)
y_test = min_max_scaler.fit_transform(y_test.reshape(-1,1))

五、模型训练

from sklearn.linear_model import LinearRegression
lr = LinearRegression()
# 使用训练数据进行参数估计
lr.fit(X_train, y_train)
# 使用测试数据进行回归预测
y_test_pred = lr.predict(X_test)

六、模型评估

# 使用r2_score对模型评估
from sklearn.metrics import mean_squared_error, r2_score
# 绘图函数
def figure(title, *datalist):plt.figure(facecolor='gray', figsize=[16, 8])for v in datalist:plt.plot(v[0], '-', label=v[1], linewidth=2)plt.plot(v[0], 'o')plt.grid()plt.title(title, fontsize=20)plt.legend(fontsize=16)plt.show()
# 训练数据的预测值
y_train_pred = lr.predict(X_train)# 计算均方差
train_error = [mean_squared_error(y_train, [np.mean(y_train)] * len(y_train)),mean_squared_error(y_train, y_train_pred)]
# 绘制误差图
figure('误差图 最终的MSE = %.4f' % (train_error[-1]), [train_error, 'Error'])

结果:
在这里插入图片描述

# 绘制预测值与真实值图
figure('预测值与真实值图 模型的' + r'$R^2=%.4f$' % (r2_score(y_train_pred, y_train)), [y_test_pred, '预测值'],[y_test, '真实值'])

结果:
在这里插入图片描述

# 线性回归的系数
print('线性回归的系数为:\n w = %s \n b = %s' % (lr.coef_, lr.intercept_))

结果:
在这里插入图片描述


http://www.ppmy.cn/news/315306.html

相关文章

伦敦备受青睐的标志性建筑——皇家阿尔伯特音乐厅

说到伦敦重要的演出场所,当然不能不提皇家阿尔伯特音乐厅(Royal Albert Hall)。披头士乐队、滚石乐队、阿黛尔、萨顶顶、谭晶、郎朗等著名歌手和音乐人都曾在这里举办演唱会或音乐会,一年一度的逍遥音乐节更是让这座音乐厅备受瞩目…

芬兰雅威联手金茂府 打响“城市空气革命”第一仗

随着中国经济飞速发展,中国高端豪宅地产项目也越来越多,房地产业内人士直言:“高端城市豪宅必须把好空气质量这一关,否则就难以获得高端群体的认同。”不得不说,人们对呼吸健康的重视继雾霾之后,在经历过此…

波士顿房价预测(一)

波士顿房价预测(一) 导语: 开始学习机器学习相关知识。波士顿房价预测,也是很经典的一个案例,我会陆续把自己完成整个项目的过程记录下来,还有就是可能会出现一定的差错,或者数据分析库使用的不是很熟练的情况&#xf…

波斯顿房价 (1)

#房价预测 import torch #data import numpy as np import re ff open(r"C:\Users\22383\Desktop\备份pytorch\000、课程配套资料\Pytorch_code-master\pytorch_code\04\cls_reg\housing.data").readlines() data [] for item in ff:out re.sub(r"\s{2,}&quo…

波士顿房价预测

波士顿房价预测 在这节课中,我们使用波士顿房价数据集来实现一个更加完整的例子,关于波士顿房价数据集,我们在第6讲中进行了详细的介绍,这是对它可视化的结果 其中的每一个子图是数据集中的一个属性,和房价之间的关系…

大教堂和市集(The Cathedral and the Bazaar)

<<The Cathedral and the Bazaar>>中文 Copy to clipboard 在自由软件启蒙阶段&#xff0c;埃里克.雷蒙德以如椽之笔呼啸而出&#xff0c;其核心著作被业界成为"五部曲"&#xff1a;《黑客道简史》(A Brief History of Hackerdom)、《大教堂和市集》(T…

自然环保美家 莫斯科165平温情公寓

该公寓位于俄罗斯莫斯科的一个绿色社区&#xff0c;共165平方米&#xff0c;高水准的装饰和搭配尽显大气和温馨&#xff0c;主人发挥空间的潜能&#xff0c;现代风格的装饰&#xff0c;极具设计感&#xff0c;诱人的氛围让人流连忘返。接下来就跟随小编一起欣赏吧。 装饰Tips&a…

scotland yard

CW-MODEL 有需要的朋友qq 1703105484 In this first task we will ask you to implement Java classes, which model the game mechanics of "Scotland Yard" within a given software framework. Note that you will implement the full version of the game (n…