房价预测1--Regression--Ridge

1.数据集
train.csv
test.csv

2.数据读取

import numpy as np
import pandas as pd

train_data = pd.read_csv('E:/机器学习/my_code_kaggle/lesson2/input/train.csv',index_col = 0)
test_data = pd.read_csv('E:/机器学习/my_code_kaggle/lesson2/input/test.csv',index_col = 0)

y_train = train_data['SalePrice']

3.判断平滑性

#判断平滑性
#y_train.hist()
#发现平滑性不怎么样,最好分布图类似于一个正态分布就比较好
y_train_log = np.log1p(y_train)
#y_train_log.hist()

不平滑:
在这里插入图片描述
log1p之后:
在这里插入图片描述
4.属性变化
有的属性使用不同分类表示的,Category类型的,有的属性(MSSubClass)是用数字表示,但是不能作为数值大小进行比较,还是应该作为类别分类,先要str化,然后One-Hot方法,把Category类变成Numerical类:

#MSSubClass属性的数值无意义,作为类别标签看待,转为字符串
#MSSubClass是Categorical类型,用One-Hot的方法来表示
#pandas自带get_dummies方法,一键做到One-Hot
train_data['MSSubClass'] = train_data['MSSubClass'].astype(str)
#print(train_data['MSSubClass'].value_counts())

#把MSSubClass换成字符串标签了之后,就和其他的英文分类差不多了,直接dummy
dummy_train = pd.get_dummies(train_data)#属性由79个变成了302个,1460*303

5.空缺值处理

#查看各个属性缺失值的个数,用平均值填补缺失值
print(dummy_train.isnull().sum().sort_values(ascending = False).head(10))
mean_cols = dummy_train.mean()
dummy_train = dummy_train.fillna(mean_cols)#用mean_cols来填满空缺值
#print(dummy_train.isnull().sum().sum())#确定没有空缺值了

6.标准化numerical数据
这里,我们当然不需要把One-Hot的那些0/1数据给标准化。我们的目标应该是那些本来就是numerical的数据:

#做regression的时候最好先标准化一下
#标准化numerical类型数据,不是One-Hot变成的numerical
numeric_cols = train_data.columns[train_data.dtypes != 'object']
print(numeric_cols)#len(numeric_cols) = 36

numeric_col_means = dummy_train.loc[:,numeric_cols].mean()
numeric_col_std = dummy_train.loc[:,numeric_cols].std()
dummy_train.loc[:,numeric_cols] = (dummy_train.loc[:,numeric_cols]-numeric_col_means)/numeric_col_std

7.训练模型

#调参数过程
#通过交叉验证,看模型选用哪一套算法比较好
from sklearn.linear_model import Ridge
from sklearn.model_selection import cross_val_score

y_train = dummy_train['SalePrice']
X_train = dummy_train.drop(['SalePrice'],axis = 1) #丢掉这一列作为训练集的训练数据

alphas = np.logspace(-3,2,50)#开始和结束是10**-3和10**2,中间一共取50个点
test_scores = []
for alpha in alphas:
    clf = Ridge(alpha)#使用的是岭回归模型
    #交叉验证
    test_score = np.sqrt(-cross_val_score(clf,X_train,y_train,cv = 10,scoring = 'neg_mean_squared_error'))
    test_scores.append(np.mean(test_score))
    
#结果可视化
import matplotlib.pyplot as plt
plt.plot(alphas,test_scores)
plt.title('Alpha vs CV Error')#alpha = 20左右比较好

在这里插入图片描述
我们可以看到这里直接拿不平滑的y_train,即没有做log1p变化的SalePrice来做训练,均方误差在0.37左右

这里我们再来拿平滑后的数据来训练:
只需要把交叉验证的那一行代码改成

 test_score = np.sqrt(-cross_val_score(clf,X_train,y_train_log,cv = 10,scoring = 'neg_mean_squared_error'))   

在这里插入图片描述
alpha = 15比较好
均方误差被进一步减小了,说明平滑处理的重要性

另外,我这里只对训练数据进行了One-Hot处理,实际上用测试集去测试的时候也是要同样处理数据的,所以有些文章建议,把训练集的标签拿出来之后,与测试数据拼接,然后统一处理,再分出新的训练集和测试集

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值