波士顿住房数据: 该数据集取自StatLib图书馆,由卡内基梅隆大学维护。该数据集涉及住房城市波士顿的房价。提供的数据集有506个实例,包含13个特征。 数据集的描述取自
null
让我们建立线性回归模型,预测房价 输入库和数据集。
Python3
# Importing Libraries import numpy as np import pandas as pd import matplotlib.pyplot as plt # Importing Data from sklearn.datasets import load_boston boston = load_boston() |
输入波士顿数据的形状和获取特征名称
Python3
boston.data.shape |
Python3
boston.feature_names |
将数据从nd阵列转换为数据帧,并向数据中添加要素名称
Python3
data = pd.DataFrame(boston.data) data.columns = boston.feature_names data.head( 10 ) |
将“价格”列添加到数据集
Python3
# Adding 'Price' (target) column to the data boston.target.shape |
Python3
data[ 'Price' ] = boston.target data.head() |
波士顿数据集描述
Python3
data.describe() |
波士顿数据集信息
Python3
data.info() |
获取输入和输出数据,并进一步将数据拆分为训练和测试数据集。
Python3
# Input Data x = boston.data # Output Data y = boston.target # splitting data to training and testing dataset. #from sklearn.cross_validation import train_test_split #the submodule cross_validation is renamed and reprecated to model_selection from sklearn.model_selection import train_test_split xtrain, xtest, ytrain, ytest = train_test_split(x, y, test_size = 0.2 , random_state = 0 ) print ( "xtrain shape : " , xtrain.shape) print ( "xtest shape : " , xtest.shape) print ( "ytrain shape : " , ytrain.shape) print ( "ytest shape : " , ytest.shape) |
将线性回归模型应用于数据集并预测价格。
Python3
# Fitting Multi Linear regression model to training model from sklearn.linear_model import LinearRegression regressor = LinearRegression() regressor.fit(xtrain, ytrain) # predicting the test set results y_pred = regressor.predict(xtest) |
绘制散点图以显示预测结果——“ytrue”值与“y_pred”值
Python3
# Plotting Scatter graph to show the prediction # results - 'ytrue' value vs 'y_pred' value plt.scatter(ytest, y_pred, c = 'green' ) plt.xlabel( "Price: in $1000's" ) plt.ylabel( "Predicted value" ) plt.title( "True value vs predicted value : Linear Regression" ) plt.show() |
线性回归的结果,即均方误差。
Python3
# Results of Linear Regression. from sklearn.metrics import mean_squared_error mse = mean_squared_error(ytest, y_pred) print ( "Mean Square Error : " , mse) |
根据结果,我们的模型的准确率仅为66.55%。因此,准备好的模型不太适合预测房价。可以使用许多其他可能的机器学习算法和技术来改进预测结果。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END