波士顿房价预测
波士顿房价预测
本篇使用经典波士顿房价数据进行sklearn学习。
输出重定向
重定向标准输出到out,重定向标准错误到err
import sys
f1 = open("out", "w")
f2 = open("err", "w")
sys.stdout = f1
sys.stderr = f2
数据引入
-
从https://archive.ics.uci.edu/ml/machine-learning-databases/housing/ 下载数据
-
使用sklearn的简单玩具数据集(*根据提示,将来可能换为加利福尼亚数据)
# load data
boston = np.loadtxt('housing.data')
# 13 features
features = boston[:, :13]
print("*************************************features***********************************")
print(features)
# 1 mark
print("*************************************mark**************************************")
mark = boston[:, 13]
print(mark)
数据清洗
- 是否有异常数据(这里暂时跳过,实际可以尝试通过画图找出异常点删除)
- 将不可解析的数据编码转化为可加减乘除的数据(此数据集不需要)
简单数据分析和处理
- 相关系数,找出13个特征和房价的相关系数,并绘制相关图片(折线图,散点图)
# correlation coefficient
coffs = np.corrcoef(boston, rowvar=False)
im_coff = coffs[:13, 13]
plt.plot(im_coff, marker='*', color='red')
im_coff = abs(im_coff)
plt.plot(im_coff, marker='*', color='blue')
plt.show()
for i in range(13):
plt.subplot(7, 2, i+1)
plt.scatter(boston[:, i], boston[:, 13])
plt.show()
- 分割测试集和训练集
print("*********************************split dataset**********************************")
X_train, X_test, y_train, y_test = train_test_split(
boston[:, :13],
boston[:, 13],
test_size=0.2,
random_state=1
)
print(X_train.shape, X_test.shape, y_train.shape, y_test.shape)
- 标准化
print("*********************************standard scaler********************************")
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.fit(X_test)
模型建立、训练、结果输出
print("*********************************model******************************************")
model = LinearRegression()
model.fit(X_train, y_train)
print(model.coef_)
print(model.intercept_)
模型的效果评估
print("*****************************prediction and value*******************************")
y_pred = model.predict(X_test)
plt.plot(y_pred, color='red')
plt.plot(y_test, color='blue')
plt.show()
# MSE 均方差
print("MSE:", mean_squared_error(y_test, y_pred))
# R2
print("R2:", r2_score(y_test, y_pred))
本文来自博客园,作者:OceanCT,转载请注明原文链接:https://www.cnblogs.com/OceanCT/p/16458222.html

浙公网安备 33010602011771号