kaggle 房价预测 得分0.53492

server/2024/10/21 5:47:33/

流程

  1. 导入需要的包
  2. 引入文件,查看内容
  3. 数据处理
  4. 调用模型准备训练
  5. 输出结果

导入需要的包

python">import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error

引入文件,查看内容

python">train = pd.read_csv('train.csv')
print('The shape of training data:', train.shape)
train.head()

在这里插入图片描述

python">test = pd.read_csv('test.csv')
print('The shape of testing data:', test.shape)
test.head()

在这里插入图片描述

数据处理

删除没有用的列
python">train.drop('LotFrontage', axis=1, inplace=True)
test.drop('LotFrontage', axis=1, inplace=True)
区分数字特征和字符特征
python">#分离数字特征和类别特征
num_features = []
cate_features = []
for col in test.columns:if test[col].dtype == 'object':cate_features.append(col)else:num_features.append(col)
print('number of numeric features:', len(num_features))
print('number of categorical features:', len(cate_features))
去除特殊的值
python">#处理掉右下的明显异常值
train = train.drop(train[(train['TotalBsmtSF']>6000) & (train['SalePrice']<200000)].index)
train = train.drop(train[(train['GrLivArea']>4000) & (train['SalePrice']<200000)].index)
查看训练集中各特征的数据缺失个数
python">print('The shape of training data:', train.shape)
train_missing = train.isnull().sum()
train_missing = train_missing.drop(train_missing[train_missing==0].index).sort_values(ascending=False)
train_missing
查看测试集中各特征的数据缺失个数
python">#查看测试集中各特征的数据缺失个数
print('The shape of testing data:', test.shape)
test_missing = test.isnull().sum()
test_missing = test_missing.drop(test_missing[test_missing==0].index).sort_values(ascending=False)
test_missing
根据特征说明文档,以下特征缺失代表没有,所以直接补充为’None’就可以了:
python">none_lists = ['PoolQC', 'MiscFeature', 'Alley', 'Fence', 'FireplaceQu', 'GarageType', 'GarageFinish', 'GarageQual', 'GarageCond', 'BsmtFinType1','BsmtFinType2', 'BsmtCond', 'BsmtExposure', 'BsmtQual', 'MasVnrType']
for col in none_lists:train[col] = train[col].fillna('None')test[col] = test[col].fillna('None')
补充出现频率最高的一类
python">most_lists = ['MSZoning', 'Exterior1st', 'Exterior2nd', 'SaleType', 'KitchenQual', 'Electrical']
for col in most_lists:train[col] = train[col].fillna(train[col].mode()[0])test[col] = test[col].fillna(train[col].mode()[0])    #注意这里补充的是训练集中出现最多的类别
删除掉多余的特征
python">train['Functional'] = train['Functional'].fillna('Typ')
test['Functional'] = test['Functional'].fillna('Typ')train.drop('Utilities', axis=1, inplace=True)
test.drop('Utilities', axis=1, inplace=True)
数字特征处理
补零,对可能为零的特征,缺失值全部补零
python">zero_lists = ['GarageYrBlt', 'MasVnrArea', 'BsmtFullBath', 'BsmtHalfBath', 'BsmtFinSF1', 'BsmtFinSF2', 'BsmtUnfSF', 'GarageCars', 'GarageArea','TotalBsmtSF']
for col in zero_lists:train[col] = train[col].fillna(0)test[col] = test[col].fillna(0)
最后检查下是否还存在缺失值:

查看训练集是否有空

python">train.isnull().sum().any()

查看测试集是否有空

python">test.isnull().sum().any()
从存放类别特征的列表去掉
python">#从存放类别特征的列表去掉'Utilities'
cate_features.remove('Utilities')
print('The number of categorical features:', len(cate_features))
python">for col in cate_features:train[col] = train[col].astype(str)test[col] = test[col].astype(str)
le_features = ['Street', 'Alley', 'LotShape', 'LandContour', 'LandSlope', 'HouseStyle', 'RoofMatl', 'Exterior1st', 'Exterior2nd', 'ExterQual', 'ExterCond', 'Foundation', 'BsmtQual', 'BsmtCond', 'BsmtExposure', 'BsmtFinType1', 'BsmtFinType2', 'HeatingQC', 'CentralAir','KitchenQual', 'Functional', 'FireplaceQu', 'GarageFinish', 'GarageQual', 'GarageCond', 'PavedDrive', 'PoolQC', 'Fence']
for col in le_features:encoder = LabelEncoder()value_train = set(train[col].unique())value_test = set(test[col].unique())value_list = list(value_train | value_test)encoder.fit(value_list)train[col] = encoder.transform(train[col])test[col] = encoder.transform(test[col])
把数据放一块处理
python">all_data = pd.concat((train.drop('SalePrice', axis=1), test)).reset_index(drop=True)
all_data = pd.get_dummies(all_data, drop_first=True)  #注意独热编码生成的时候要去掉一个维度,保证剩下的变量都是相互独立的
all_data.shape
划分数据集
python">trainset = all_data[:1460]
y=train['SalePrice']
testset = all_data[1458:]
print('The shape of training data:', trainset.shape)
print('The shape of testing data:', testset.shape)

调用模型

python">linear_model = LinearRegression()
linear_model.fit(trainset, y)
预测数据
python">line_pre = linear_model.predict(testset)

输出结果

python">test = pd.read_csv('test.csv')
# print(test.shape,line_pre.shape)
we = pd.DataFrame({'Id': test['Id'], 'SalePrice': line_pre})
we.to_csv('House_Price_submissionMyself.csv', index=False)

http://www.ppmy.cn/server/5004.html

相关文章

CentOS 7上MySQL数据库主从配置与主从切换技术详解

摘要:本文主要介绍了在CentOS7操作系统上搭建MySQL数据库,并进行主从配置以及主从切换的详细步骤。文章首先阐述了主从配置的架构和原理,然后提供了具体的配置案例,包括安装MySQL、配置主服务器、配置从服务器、测试主从同步等步骤。接着,文章详细介绍了如何进行主从切换,…

【新版HI3559AV100开发注意事项(四)】

新版HI3559AV100开发注意事项&#xff08;四&#xff09; 三十、HI3559A参数中对输入分辨率限制的原因是&#xff1f; 答&#xff1a;分辨率限制有两个来源&#xff1a; 一个是时钟频率最高为600M&#xff0c;开启一拍两像素之后相当于1200M。你这个数据量太大了&#xff0c;6…

【论文阅读】RS-Mamba for Large Remote Sensing Image Dense Prediction(附Code)

论文作者提出了RS-Mamba(RSM)用于高分辨率遥感图像遥感的密集预测任务。RSM设计用于模拟具有线性复杂性的遥感图像的全局特征&#xff0c;使其能够有效地处理大型VHR图像。它采用全向选择性扫描模块&#xff0c;从多个方向对图像进行全局建模&#xff0c;从多个方向捕捉大的空间…

排序算法之快速排序

目录 一、简介二、代码实现三、应用场景 一、简介 算法平均时间复杂度最好时间复杂度最坏时间复杂度空间复杂度排序方式稳定性快速排序O( N N N log ⁡ 2 N \log_{2}N log2​N)O( N N N log ⁡ 2 N \log_{2}N log2​N)O(n^2)O( log ⁡ 2 N \log_{2}N log2​N)In-place不稳定 稳…

LCR 023. 相交链表

给定两个单链表的头节点 headA 和 headB &#xff0c;请找出并返回两个单链表相交的起始节点。如果两个链表没有交点&#xff0c;返回 null 。 图示两个链表在节点 c1 开始相交&#xff1a; 题目数据 保证 整个链式结构中不存在环。 注意&#xff0c;函数返回结果后&#xf…

实体类List重复校验

如果实体类有多个属性&#xff0c;并且你希望根据所有属性的组合来进行重复校验&#xff0c;你可以考虑以下几种方法&#xff1a; 使用集合存储已经出现过的实体对象&#xff1a; 将每个实体对象放入一个 Set 中进行重复校验。在 Set 中元素的比较可以使用自定义的 equals 方法…

蓝桥杯刷题-计算系数

本文自用&#xff0c;用作记录。 211. 计算系数 - AcWing题库 #include <bits/stdc.h>using namespace std;int a, b, k ,n ,m; const int mod 10007; int qmi(int a, int k) {a % mod;int res 1;while (k){if (k & 1) res res * a % mod;a a * a % mod;k >…

【机器学习300问】72、神经网络的隐藏层数量和各层神经元节点数如何影响模型的表现?

评估深度学习的模型的性能依旧可以用偏差和方差来衡量。它们反映了模型在预测过程中与理想情况的偏离程度&#xff0c;以及模型对数据扰动的敏感性。我们简单回顾一下什么是模型的偏差和方差&#xff1f; 一、深度学习模型的偏差和方差 偏差&#xff1a;衡量模型预测结果的期望…