Examining your data

COMPREHENSIVE DATA EXPLORATION WITH PYTHON

参考资料: https://www.kaggle.com/pmarcelino/comprehensive-data-exploration-with-python

  1. 了解问题。我们将查看每个变量,并对其对此问题的意义和重要性进行达观的分析。
  2. 单变量研究。我们只关注因变量('SalePrice')并尝试更多地了解它。
  3. 多变量研究。我们将尝试理解因变量和自变量相关性。
  4. 基本数据清洗。我们将清理数据集并处理缺失的数据、异常值和分类变量。
  5. 测试假设。我们将检查我们的数据是否符合大多数多变量技术所需的假设。

引入相关包:

In [1]:
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
from scipy.stats import norm
from sklearn.preprocessing import StandardScaler
from scipy import stats
import warnings
warnings.filterwarnings('ignore')
%matplotlib inline

读取数据,input文件夹在和这个文件同级的目录中,train.csv在input文件夹下

In [2]:
df_train = pd.read_csv('input/train.csv')

查看所有的列

In [3]:
df_train.columns
Out[3]:
Index(['Id', 'MSSubClass', 'MSZoning', 'LotFrontage', 'LotArea', 'Street',
       'Alley', 'LotShape', 'LandContour', 'Utilities', 'LotConfig',
       'LandSlope', 'Neighborhood', 'Condition1', 'Condition2', 'BldgType',
       'HouseStyle', 'OverallQual', 'OverallCond', 'YearBuilt', 'YearRemodAdd',
       'RoofStyle', 'RoofMatl', 'Exterior1st', 'Exterior2nd', 'MasVnrType',
       'MasVnrArea', 'ExterQual', 'ExterCond', 'Foundation', 'BsmtQual',
       'BsmtCond', 'BsmtExposure', 'BsmtFinType1', 'BsmtFinSF1',
       'BsmtFinType2', 'BsmtFinSF2', 'BsmtUnfSF', 'TotalBsmtSF', 'Heating',
       'HeatingQC', 'CentralAir', 'Electrical', '1stFlrSF', '2ndFlrSF',
       'LowQualFinSF', 'GrLivArea', 'BsmtFullBath', 'BsmtHalfBath', 'FullBath',
       'HalfBath', 'BedroomAbvGr', 'KitchenAbvGr', 'KitchenQual',
       'TotRmsAbvGrd', 'Functional', 'Fireplaces', 'FireplaceQu', 'GarageType',
       'GarageYrBlt', 'GarageFinish', 'GarageCars', 'GarageArea', 'GarageQual',
       'GarageCond', 'PavedDrive', 'WoodDeckSF', 'OpenPorchSF',
       'EnclosedPorch', '3SsnPorch', 'ScreenPorch', 'PoolArea', 'PoolQC',
       'Fence', 'MiscFeature', 'MiscVal', 'MoSold', 'YrSold', 'SaleType',
       'SaleCondition', 'SalePrice'],
      dtype='object')

1. 我们能发现什么?

为了理解我们的数据,我们可以查看每个变量并尝试理解它们的含义以及与此问题的相关性。我知道这很费时,但它能让我们了解数据集。

为了在我们的分析中有一些规则,我们可以创建一个包含以下列的Excel电子表格:

  • Variable - 变量名称。
  • Type - 变量类型的类型。此字段有两个可能的值:“数字”或“分类”。 “数字”是指值为数字的变量,“分类”是指值为类别的变量。
  • Segment - 变量细分的识别。我们可以定义三个可能的部分:building,space 或location。当我们说'building'时,我们指的是与建筑物的物理特征相关的变量(例如'OverallQual',房屋质量,房屋的整体材料和装修)。当我们说'space'时,我们指的是一个房屋空间属性的变量(例如'TotalBsmtSF', Total square feet of basement area, 总基底或者地下室面积,单位是平方英尺)。最后,当我们说'location'时,我们指的是一个变量,它提供有关房屋所在位置的信息(例如'Neighborhood',地区)。
  • Expectation - 变量对'SalePrice'的影响程度。我们可以用“高”,“中”和“低”作为可能的分类值。
  • Conclusion - 在我们快速查看数据之后发现的变量的重要程度。也可用“高”、“中”和“低”作为可能的分类值。
  • Comments - 我们想到的任何一般性评论。

虽然“Type”和“Segment”仅供将来参考,但“Expectation”一栏很重要,因为它将启发我们的“第六感”。要填写此表格,我们应该阅读所有变量的描述,并逐一问自己:

  • 在我们买房时,我们是否考虑过这个变量? (例如,当我们构想我们未来的家的时候,我们是否关心它的'砌体墙面'?)。
  • 如果是这样,这个变量有多重要? (例如,在外部使用'优质'材料而不是'差'会产生什么影响?并且'优秀'而不是'好'会有什么影响?)。
  • 这些信息是否已在任何其他变量中描述过? (例如,如果'LandContour'给出了房产的平整度(例如是否在洼地、是否在山边、是否平坦、建筑物是否高于旁边的道路),我们真的需要知道'LandSlope'(土地坡度,如平缓、中等、陡峭)吗?)。

在这个艰巨的练习之后,我们可以过滤电子表格并仔细查看具有“高”'期望'的变量。然后,我们可以查看这些变量和'SalePrice'之间的一些散点图,填写'结论'栏,对我们的期望进行修正。

我通过这个过程并得出结论,以下变量可以在这个问题中发挥重要作用:

  • OverallQual(这是一个我不喜欢的变量,因为我不知道它是如何计算的;使用所有其他可用变量来预测'OverallQual'是一个有趣的练习)。
  • YearBuilt。Original construction date,原始施工日期,也就是房屋年代
  • TotalBsmtSF。
  • GrLivArea。Above grade (ground) living area square feet,地上生活区面积,单位是平方英尺,也就是计容面积。

我最终得到了两个“building”变量('OverallQual'和'YearBuilt')和两个'space'变量('TotalBsmtSF'和'GrLivArea')。这可能有点出乎意料,因为它违背了房地产的口头禅,房屋重要的是“位置,位置和位置”。对于分类变量,这种快速数据检查过程可能有点苛刻。例如,我预计“Neigborhood”变量更具相关性,但在数据检查后我最终将其排除在外。也许这与使用散点图而不是箱图有关,散点图更适合于分类变量可视化。数据展示的方式通常会影响我们的结论。

然而,这个练习的要点是想一想我们的数据和期望,所以我认为我们实现了目标。现在是时候“少谈一点,请多一点动作”。

2. 首先要做的事情:分析'SalePrice'

看一下SalePrice是否有空值:

In [4]:
df_train['SalePrice'].isnull()
Out[4]:
0       False
1       False
2       False
3       False
4       False
5       False
6       False
7       False
8       False
9       False
10      False
11      False
12      False
13      False
14      False
15      False
16      False
17      False
18      False
19      False
20      False
21      False
22      False
23      False
24      False
25      False
26      False
27      False
28      False
29      False
        ...  
1430    False
1431    False
1432    False
1433    False
1434    False
1435    False
1436    False
1437    False
1438    False
1439    False
1440    False
1441    False
1442    False
1443    False
1444    False
1445    False
1446    False
1447    False
1448    False
1449    False
1450    False
1451    False
1452    False
1453    False
1454    False
1455    False
1456    False
1457    False
1458    False
1459    False
Name: SalePrice, Length: 1460, dtype: bool

统计一下空值的个数:

In [5]:
df_train['SalePrice'].isnull().sum()
Out[5]:
0

看来是没有空值,之后我们看一下这一列是什么类型的:

In [6]:
df_train['SalePrice'].dtypes
Out[6]:
dtype('int64')

发现这一列都是数值型的。如果返回的结果是dtype('O'),那说明这一列是Object类型,那我们需要看看是否有脏数据,是否要对数据做其他处理。对SalePrice进行快速统计,会统计出各列的:计数,平均数,方差,最小值,最大值,以及四分位数

In [7]:
#descriptive statistics summary
df_train['SalePrice'].describe()
Out[7]:
count      1460.000000
mean     180921.195890
std       79442.502883
min       34900.000000
25%      129975.000000
50%      163000.000000
75%      214000.000000
max      755000.000000
Name: SalePrice, dtype: float64

我们把直方图画出来,看看数据的分布情况:

In [8]:
#histogram
sns.distplot(df_train['SalePrice']);

我们可以看到:

  • 偏离正态分布
  • 有明显的正偏态/正偏斜/右偏/肥尾现象
  • 可以看到尖峰。

峰度(peakedness;kurtosis)又称峰态系数。表征概率密度分布曲线在平均值处峰值高低的特征数。直观看来,峰度反映了峰部的尖度。样本的峰度是和正态分布相比较而言统计量,如果峰度大于三,峰的形状比较尖,比正态分布峰要陡峭。反之亦然。 偏度(skewness)也称为偏态、偏态系数,是统计数据分布偏斜方向和程度的度量,是统计数据分布非对称程度的数字特征。 看偏度和峰度的数值:

In [9]:
#skewness and kurtosis
print("Skewness: %f" % df_train['SalePrice'].skew())
print("Kurtosis: %f" % df_train['SalePrice'].kurt())
Skewness: 1.882876
Kurtosis: 6.536282

'SalePrice'与数值变量/连续型的关系

画出GrLivArea/SalePrice的散点图(GrLivArea是地上生活区面积)

In [10]:
#scatter plot grlivarea/saleprice
var = 'GrLivArea'
data = pd.concat([df_train['SalePrice'], df_train[var]], axis=1)
data.plot.scatter(x=var, y='SalePrice', ylim=(0,800000));

可以看出来房屋价格和房屋面积是线性关系。 我们再来看看TotalBsmtSF地下室总面积和房屋价格的关系:

In [11]:
#scatter plot totalbsmtsf/saleprice
var = 'TotalBsmtSF'
data = pd.concat([df_train['SalePrice'], df_train[var]], axis=1)
data.plot.scatter(x=var, y='SalePrice', ylim=(0,800000));

地下室总面积和房屋价格关系不那么明确,有点像线性关系,也有点像指数关系,在地下室面积为0的时候,价格和地下室总面积没什么关系。

'SalePrice'与离散变量的关系

房屋价格与房屋质量关系

In [12]:
#box plot overallqual/saleprice
var = 'OverallQual'
data = pd.concat([df_train['SalePrice'], df_train[var]], axis=1)
f, ax = plt.subplots(figsize=(8, 6))
fig = sns.boxplot(x=var, y="SalePrice", data=data)
fig.axis(ymin=0, ymax=800000);

房屋价格与房屋建造年代关系

In [13]:
var = 'YearBuilt'
data = pd.concat([df_train['SalePrice'], df_train[var]], axis=1)
f, ax = plt.subplots(figsize=(16, 8))
fig = sns.boxplot(x=var, y="SalePrice", data=data)
fig.axis(ymin=0, ymax=800000);
plt.xticks(rotation=90);

我们不知道train.csv表格中给出的价格是否是不变价。不变价:是指国家各级统计部门在计算不同时期工业总产值时,对同一产品采用同一时期或同一时点的工业产品出厂价格作为不变价,又称W定价格。 如果是不变价的话,我们就可以通过这个价格对房子真实价值进行分析。相对来说,大家喜欢买新房子而不是老文物

综上所述

  • 'GrLivArea'和'TotalBsmtSF'似乎与'SalePrice'线性相关。 两种关系都是正的,这意味着当一个变量增加时,另一个变量增加。而且,和'TotalBsmtSF'的线性关系曲线的斜率特别高
  • 'OverallQual'和'YearBuilt'似乎也与'SalePrice'有关。 'OverallQual'与房价的关系似乎更强,其中箱形图显示销售价格如何随着整体质量而增加。

我们刚刚分析了四个变量,但还有许多其他我们应该分析的变量。 在这一步,我们主要选择正确的特征(特征选择)而不是它们之间复杂关系的定义(特征工程)。

3. Keep calm and work smart

到现在为止,我们只是按照我们的直觉,分析了我们认为重要的变量。尽管我们努力为我们的分析提供客观的特征,但我们必须说我们的出发点是主观的。我们现在来做客观的分析。

The 'plasma soup'

我们通过下面的方式进行研究

  • 相关矩阵 (热力图样式)
  • 'SalePrice'相关矩阵(缩放热图样式)
  • 最相关变量之间的散点图

    #### 相关矩阵 (热力图样式)

In [14]:
#correlation matrix
corrmat = df_train.corr()
f, ax = plt.subplots(figsize=(12, 9))
sns.heatmap(corrmat, vmax=.8, square=True);

在我看来,热力图是快速了解数据及其关系的最佳方式。

乍一看,有两个红色方块引起我的注意。第一个是'TotalBsmtSF'和'1stFlrSF'变量,第二个是'GarageX'变量Garage相关变量。他们之间有很强的相关性。实际上,这种相关性非常强,可以表明多重共线性的情况。多重共线性是指线性回归模型中的解释变量之间由于存在精确相关关系或高度相关关系而使模型估计失真或难以估计准确。一般来说,由于经济数据的限制使得模型设计不当,导致设计矩阵中解释变量间存在普遍的相关关系。如果我们考虑这些变量,它们给出了几乎相同的信息,因此实际上发生了多重共线性。热图非常适合检测这种情况。

在'GrLivArea','TotalBsmtSF'和'OverallQual'与'SalePrice'相关性比较高,当然我们也可以看到许多其他变量应该被考虑。

'SalePrice'相关矩阵(缩放热图样式)

In [15]:
#saleprice correlation matrix
k = 10 #number of variables for heatmap
cols = corrmat.nlargest(k, 'SalePrice')['SalePrice'].index
cm = np.corrcoef(df_train[cols].values.T)
sns.set(font_scale=1.25)
hm = sns.heatmap(cm, cbar=True, annot=True, square=True, fmt='.2f', annot_kws={'size': 10}, yticklabels=cols.values, xticklabels=cols.values)
plt.show()

上图中是与'SalePrice'最相关的变量。我对此的看法:

  • 'OverallQual','GrLivArea'和'TotalBsmtSF'与'SalePrice'密切相关。
  • 'GarageCars'和'GarageArea'也是一些最相关的变量。我们在分析中只需要其中一个变量
  • 'TotalBsmtSF'和'1stFloor'似乎也是孪生兄弟。我们可以保留'TotalBsmtSF'
  • 'FullBath'?
  • 'TotRmsAbvGrd'和'GrLivArea',再次成为孪生兄弟。
  • 'YearBuilt'......似乎'YearBuilt'与'SalePrice'略有关联。老实说,让我想起'YearBuilt'让我感到害怕,因为我开始觉得我们应该做一些时间序列分析才能做到这一点。

最相关变量之间的散点图

我必须承认,当我第一次看到这些散点图时,我完全被吹走了!这么短的空间里有如此多的信息,真是太神奇了。

In [16]:
#scatterplot
sns.set()
cols = ['SalePrice', 'OverallQual', 'GrLivArea', 'GarageCars', 'TotalBsmtSF', 'FullBath', 'YearBuilt']
sns.pairplot(df_train[cols], size = 2.5)
plt.show();

虽然我们已经知道了一些主要数据,但这个巨大的散点图给出了变量关系的合理解释。

我们可能感兴趣的一个数字是'TotalBsmtSF'和'GrLiveArea'之间的数字。在这个图中,我们可以看到绘制一条直线的点,这几乎就像一个边界。大多数点都低于该线,这是完全有道理的。地下室面积可以等于地上生活区域,但预计地下室面积不会超过地上生活区域(除非您尝试购买地堡)。

关于'SalePrice'和'YearBuilt'的情节也可以让我们思考。在“点云”的底部,我们看到几乎看起来像一个害羞的指数函数(具有创造性)。我们也可以在“点云”的上限看到同样的趋势(更具创造性)。另外,请注意关于过去几年的点集如何保持高于此限制(我只是想说现在价格上涨得更快)。

4. Missing data

是时候考虑数据缺失的问题了

  • 数据缺失的程度
  • 是随机都是数据还是有模式

这些问题的答案很重要,因为缺少数据可能意味着样本量的减少。此外,从实质的角度来看,我们需要确保缺失的数据流程没有偏见或者隐藏事实。

In [17]:
#missing data
total = df_train.isnull().sum().sort_values(ascending=False)
percent = (df_train.isnull().sum()/df_train.isnull().count()).sort_values(ascending=False)
missing_data = pd.concat([total, percent], axis=1, keys=['Total', 'Percent'])
missing_data.head(20)
Out[17]:
Total Percent
PoolQC 1453 0.995205
MiscFeature 1406 0.963014
Alley 1369 0.937671
Fence 1179 0.807534
FireplaceQu 690 0.472603
LotFrontage 259 0.177397
GarageCond 81 0.055479
GarageType 81 0.055479
GarageYrBlt 81 0.055479
GarageFinish 81 0.055479
GarageQual 81 0.055479
BsmtExposure 38 0.026027
BsmtFinType2 38 0.026027
BsmtFinType1 37 0.025342
BsmtCond 37 0.025342
BsmtQual 37 0.025342
MasVnrArea 8 0.005479
MasVnrType 8 0.005479
Electrical 1 0.000685
Utilities 0 0.000000

让我们分析一下,了解如何处理丢失的数据。 当超过15%的数据丢失时,我们应该删除相应的变量并假装它从未存在过。总之,为了处理丢失的数据,我们将删除所有缺少数据的变量,但变量“Electrical”除外。在“Electrical”中,我们将删除缺少数据。

In [18]:
#dealing with missing data
df_train = df_train.drop((missing_data[missing_data['Total'] > 1]).index,1)
df_train = df_train.drop(df_train.loc[df_train['Electrical'].isnull()].index)
df_train.isnull().sum().max() #just checking that there's no missing data missing...
Out[18]:
0

异常值

异常值也是我们应该注意的事情。 为什么? 因为异常值可以显着影响我们的模型,并且可以成为有价值的信息来源,为我们提供有关特定行为的见解。

异常值是一个复杂的主题,值得更多关注。 在这里,我们将通过“SalePrice”的标准偏差和一组散点图进行快速分析。

单变量分析

我们定义一个阈值,通过这个阈值观察异常值。在这种情况下,数据标准化意味着将数据值转换为平均值为0且标准偏差为1。

In [19]:
#standardizing data
saleprice_scaled = StandardScaler().fit_transform(df_train['SalePrice'][:,np.newaxis]);
low_range = saleprice_scaled[saleprice_scaled[:,0].argsort()][:10]
high_range= saleprice_scaled[saleprice_scaled[:,0].argsort()][-10:]
print('outer range (low) of the distribution:')
print(low_range)
print('\nouter range (high) of the distribution:')
print(high_range)
outer range (low) of the distribution:
[[-1.83820775]
 [-1.83303414]
 [-1.80044422]
 [-1.78282123]
 [-1.77400974]
 [-1.62295562]
 [-1.6166617 ]
 [-1.58519209]
 [-1.58519209]
 [-1.57269236]]

outer range (high) of the distribution:
[[3.82758058]
 [4.0395221 ]
 [4.49473628]
 [4.70872962]
 [4.728631  ]
 [5.06034585]
 [5.42191907]
 [5.58987866]
 [7.10041987]
 [7.22629831]]
  • 低范围值与0相似且不太远。
  • 高范围值远离0,同时感觉7.X的值实际上超出范围。

    #### 双变量分析

我们已经知道了以下散点图。 然而,当我们从一个新的角度看待事物时,总会发现一些东西。

In [20]:
#bivariate analysis saleprice/grlivarea
var = 'GrLivArea'
data = pd.concat([df_train['SalePrice'], df_train[var]], axis=1)
data.plot.scatter(x=var, y='SalePrice', ylim=(0,800000));
  • 较大的'GrLivArea'这两个值似乎很奇怪,我们将它们定义为异常值并删除它们。
  • 顶部的两个值看起来像特例,但是他们看起来符合趋势,出于这个原因,我们将保留它们。
In [21]:
#deleting points
df_train.sort_values(by = 'GrLivArea', ascending = False)[:2]
df_train = df_train.drop(df_train[df_train['Id'] == 1299].index)
df_train = df_train.drop(df_train[df_train['Id'] == 524].index)
In [22]:
#bivariate analysis saleprice/grlivarea
var = 'TotalBsmtSF'
data = pd.concat([df_train['SalePrice'], df_train[var]], axis=1)
data.plot.scatter(x=var, y='SalePrice', ylim=(0,800000));

5. 核心部分

我们已经做了一些数据清理并发现了很多关于'SalePrice'的信息。现在是时候深入了解'SalePrice'的统计假设信息,使我们能够应用多变量技术。

根据《Hair et al., 2013, Multivariate Data Analysis, 7th Edition》书中所说,应该测试四个假设:

  • Normality(正态) - When we talk about normality what we mean is that the data should look like a normal distribution. This is important because several statistic tests rely on this (e.g. t-statistics). In this exercise we'll just check univariate normality for 'SalePrice' (which is a limited approach). Remember that univariate normality doesn't ensure multivariate normality (which is what we would like to have), but it helps. Another detail to take into account is that in big samples (>200 observations) normality is not such an issue. However, if we solve normality, we avoid a lot of other problems (e.g. heteroscedacity) so that's the main reason why we are doing this analysis.当我们谈论正常性时,我们的意思是数据应该看起来像正态分布。这很重要,因为有几项统计测试依赖于此(例如t统计)。在本练习中,我们将只检查'SalePrice'的单变量正态性(这是一种有限的方法)。请记住,单变量正态性不能确保多变量正态性(这是我们想要的),但它有所帮助。需要考虑的另一个细节是,在大样本(> 200个观测值)中,正态性不是一个问题。但是,如果我们解决正态性问题,我们会避免很多其他问题(例如异方差),这就是我们进行此分析的主要原因。

  • Homoscedasticity(同方差性) - I just hope I wrote it right. Homoscedasticity refers to the 'assumption that dependent variable(s) exhibit equal levels of variance across the range of predictor variable(s)' (Hair et al., 2013). Homoscedasticity is desirable because we want the error term to be the same across all values of the independent variables.同方差性是指“因变量(s)在预测变量范围内表现出相同的方差水平的假设”(Hair et al。,2013)。同方差性是可取的,因为我们希望误差项在自变量的所有值上都是相同的。同方差性是经典线性回归的重要假定之一,指总体回归函数中的随机误差项(干扰项)在解释变量条件下具有不变的方差。计量经济学中, 一组随机变量具备同方差即指线性回归的最小二乘法(OLS, Ordinary Least Squares)的残值服从均值为0,方差为σ^2的正态分布,即其干扰项必须服从随机分布。与之相对应的异方差性则说明干扰项不满足此均值为0,方差为σ^2的正态分布。同方差性有四个基本假设 [1] ,假设一被称为(White Noise Condition)白色噪音假设, 干扰项为No Autocorrelation(无自相关);即误差部分相互没有关联,假设回归式 y = α+βx+u, 其误差项中,u1,u2各误差之间没有任何联系,即:COV(u1*u2)=0;假设二为干扰项具备同方差性或者等分散, 即误差项与独立变量(independent variable)之间相互独立, 并且误差项的分散(方差 Variance)必须等同,即Var(u|x)=σ^2;解释变量之间不存在多重共线性;解释变量是确定变量。

  • Linearity(线性) - The most common way to assess linearity is to examine scatter plots and search for linear patterns. If patterns are not linear, it would be worthwhile to explore data transformations. However, we'll not get into this because most of the scatter plots we've seen appear to have linear relationships.评估线性度的最常用方法是检查散点图并搜索线性图案。如果不是线性的,那么需要考虑做数据转换。但是,我们不会深入研究这一点,因为我们看到的大多数散点图似乎都有线性关系。

  • Absence of correlated errors(没有相关错误) - Correlated errors, like the definition suggests, happen when one error is correlated to another. For instance, if one positive error makes a negative error systematically, it means that there's a relationship between these variables. This occurs often in time series, where some patterns are time related. We'll also not get into this. However, if you detect something, try to add a variable that can explain the effect you're getting. That's the most common solution for correlated errors.相关错误,即一个错误发生时会与另外一个错误相关。例如,如果一个正误差系统地产生负面误差,则意味着这些变量之间存在关系。这通常以时间序列发生,其中一些模式与时间相关。我们也不会涉及到这一点。但是,如果您检测到某些内容,请尝试添加一个可以解释您所获得效果的变量。这是相关错误的最常见解决方案。

寻找正态性

这里的重点是以非常精益的方式测试'SalePrice'。 我们这样做会注意:

In [23]:
#histogram and normal probability plot
sns.distplot(df_train['SalePrice'], fit=norm);
fig = plt.figure()
res = stats.probplot(df_train['SalePrice'], plot=plt)

好的,'SalePrice'不正常。 它显示“峰值”,正偏态并且不跟随对角线。

但没关系。 简单的数据转换可以解决问题。 这是你可以在统计书中学到的很棒的东西之一:如果是正偏斜,对数变换通常很有效。

In [24]:
#applying log transformation
df_train['SalePrice'] = np.log(df_train['SalePrice'])
In [25]:
#transformed histogram and normal probability plot
sns.distplot(df_train['SalePrice'], fit=norm);
fig = plt.figure()
res = stats.probplot(df_train['SalePrice'], plot=plt)

好了,现在我们再来看看'GrLivArea'

In [26]:
#histogram and normal probability plot
sns.distplot(df_train['GrLivArea'], fit=norm);
fig = plt.figure()
res = stats.probplot(df_train['GrLivArea'], plot=plt)
In [27]:
#data transformation
df_train['GrLivArea'] = np.log(df_train['GrLivArea'])
In [28]:
#transformed histogram and normal probability plot
sns.distplot(df_train['GrLivArea'], fit=norm);
fig = plt.figure()
res = stats.probplot(df_train['GrLivArea'], plot=plt)

再来看看'TotalBsmtSF'

In [29]:
#histogram and normal probability plot
sns.distplot(df_train['TotalBsmtSF'], fit=norm);
fig = plt.figure()
res = stats.probplot(df_train['TotalBsmtSF'], plot=plt)

现在我们遇到的最大的问题,都是什么问题呢?

  • 总的来说,数据不是正态分布的,发生了倾斜
  • 存在大量为0的值(没有地下室的房屋)
  • 对于0值,我们不能做对数变换

    要在这里做对数变换,我们需要创建一个变量,用来标识是否有地下室(二值变量)。接着我们对非零数值进行对数变换,忽略值为0的数据。这样我们就可以做数值变换,同时不用害怕丢失地下室的信息。

    我不确定这种方法是否正确。 这对我来说似乎是对的。 这就是我所谓的“高风险工程”。

In [30]:
#create column for new variable (one is enough because it's a binary categorical feature)
#if area>0 it gets 1, for area==0 it gets 0
df_train['HasBsmt'] = pd.Series(len(df_train['TotalBsmtSF']), index=df_train.index)
df_train['HasBsmt'] = 0 
df_train.loc[df_train['TotalBsmtSF']>0,'HasBsmt'] = 1
In [31]:
#transform data
df_train.loc[df_train['HasBsmt']==1,'TotalBsmtSF'] = np.log(df_train['TotalBsmtSF'])
In [32]:
#histogram and normal probability plot
sns.distplot(df_train[df_train['TotalBsmtSF']>0]['TotalBsmtSF'], fit=norm);
fig = plt.figure()
res = stats.probplot(df_train[df_train['TotalBsmtSF']>0]['TotalBsmtSF'], plot=plt)

尝试寻找同方差性

测试两个度量变量的同方差性的最佳方法是图形。通过形状是像锥体(图的一侧的小色散,相对侧的大色散)还是菱形(分布的中心处的大量点)来判断。

从'SalePrice'和'GrLivArea'开始......

In [33]:
#scatter plot
plt.scatter(df_train['GrLivArea'], df_train['SalePrice']);

在做对数变换之前的版本,'SalePrice'和'GrLivArea'的散点图更像圆锥状。 如您所见,当前的散点图不再具有圆锥形状。 这是正态的力量! 只是通过确保某些变量的正态性,我们解决了同方差性问题。

现在让我们用'TotalBsmtSF'检查'SalePrice'。

In [34]:
#scatter plot
plt.scatter(df_train[df_train['TotalBsmtSF']>0]['TotalBsmtSF'], df_train[df_train['TotalBsmtSF']>0]['SalePrice']);

我们可以说,一般来说,'SalePrice'在'TotalBsmtSF'范围内表现出相同的方差水平。

最后,dummy variable(哑变量/虚拟变量)

很简单

In [35]:
#convert categorical variable into dummy
df_train = pd.get_dummies(df_train)

结论

我们的练习结束了。

在整个Kernel中,我们实践了Hair等人提出的许多策略。我们对变量进行了哲学思考,我们单独分析了“SalePrice”,并且使用最相关的变量,我们处理了缺失数据和异常值,我们测试了一些基本的统计假设,我们甚至将分类变量转换为虚拟变量。 这是Python帮助我们轻松完成的大量工作。

参考文献

对每一列的解释

MSSubClass: Identifies the type of dwelling involved in the sale. 销售的住宅的类型,STORY应该是楼层的意思,所以主要包括楼层和年代信息,虽然在表格中的取值是数值型的,但是应该按照离散型处理,

    20  1-STORY 1946 & NEWER ALL STYLES
    30  1-STORY 1945 & OLDER
    40  1-STORY W/FINISHED ATTIC ALL AGES
    45  1-1/2 STORY - UNFINISHED ALL AGES
    50  1-1/2 STORY FINISHED ALL AGES
    60  2-STORY 1946 & NEWER
    70  2-STORY 1945 & OLDER
    75  2-1/2 STORY ALL AGES
    80  SPLIT OR MULTI-LEVEL
    85  SPLIT FOYER
    90  DUPLEX - ALL STYLES AND AGES
   120  1-STORY PUD (Planned Unit Development) - 1946 & NEWER
   150  1-1/2 STORY PUD - ALL AGES
   160  2-STORY PUD - 1946 & NEWER
   180  PUD - MULTILEVEL - INCL SPLIT LEV/FOYER
   190  2 FAMILY CONVERSION - ALL STYLES AND AGES

MSZoning: Identifies the general zoning classification of the sale. 房屋所在区域,zoning是(城市规划中分成工厂区、住宅区等的)分区制

   A    Agriculture 农业
   C    Commercial 商业
   FV   Floating Village Residential 水上人家(浮村)
   I    Industrial 工业
   RH   Residential High Density 高密住宅
   RL   Residential Low Density 低密住宅
   RP   Residential Low Density Park 低密度庄园
   RM   Residential Medium Density 中密住宅

LotFrontage: Linear feet of street connected to property 路到房屋的距离(延迟英尺,linear meter就相当于"延米")

LotArea: Lot size in square feet 美国的房子通常有两个Size.一个就是我们通常说的房屋面积。在美国指的是房屋的使用面积。用 Sq.Ft. - 平方尺表示。另一个就是'Lot Size'指的是房屋的占地面积,包括前院和后院。

Street: Type of road access to property 房子附近道路类型

   Grvl Gravel  石子路
   Pave Paved   铺有路面的道路

Alley: Type of alley access to property 小巷类型

   Grvl Gravel  石子
   Pave Paved   铺有路面
   NA   No alley access

LotShape: General shape of property 房子形状是否规则

   Reg  Regular 规则
   IR1  Slightly irregular  轻微不规则
   IR2  Moderately Irregular 中度不规则
   IR3  Irregular 不规则

LandContour: Flatness of the property 房产的平整度

   Lvl  Near Flat/Level 平整
   Bnk  Banked - Quick and significant rise from street grade to building 建筑高于旁边的路
   HLS  Hillside - Significant slope from side to side 倾斜
   Low  Depression 洼地

Utilities: Type of utilities available 是否有电、气、水、化粪池

   AllPub   All public Utilities (E,G,W,& S)    电、气、水、化粪池
   NoSewr   Electricity, Gas, and Water (Septic Tank) 电、气、水
   NoSeWa   Electricity and Gas Only 电、气
   ELO  Electricity only    电

LotConfig: Lot configuration

   Inside   Inside lot 内部地段
   Corner   Corner lot 转角地段
   CulDSac  Cul-de-sac 死胡同
   FR2  Frontage on 2 sides of property This property has road frontage on 2 sides 两面朝向路
   FR3  Frontage on 3 sides of property This property has road frontage on 3 sides 三面朝向路

LandSlope: Slope of property 地面倾斜度

   Gtl  Gentle slope 平缓坡度
   Mod  Moderate Slope  适度倾斜
   Sev  Severe Slope 很倾斜

Neighborhood: Physical locations within Ames city limits 所在地区,应该是埃姆斯的一堆区域名

   Blmngtn  Bloomington Heights
   Blueste  Bluestem
   BrDale   Briardale
   BrkSide  Brookside
   ClearCr  Clear Creek
   CollgCr  College Creek
   Crawfor  Crawford
   Edwards  Edwards
   Gilbert  Gilbert
   IDOTRR   Iowa DOT and Rail Road
   MeadowV  Meadow Village
   Mitchel  Mitchell
   Names    North Ames
   NoRidge  Northridge
   NPkVill  Northpark Villa
   NridgHt  Northridge Heights
   NWAmes   Northwest Ames
   OldTown  Old Town
   SWISU    South & West of Iowa State University
   Sawyer   Sawyer
   SawyerW  Sawyer West
   Somerst  Somerset
   StoneBr  Stone Brook
   Timber   Timberland
   Veenker  Veenker

Condition1: Proximity to various conditions 周边资源1

   Artery   Adjacent to arterial street 毗邻干道
   Feedr    Adjacent to feeder street   毗邻支路街道
   Norm Normal  一般
   RRNn Within 200' of North-South Railroad 南北铁路200公里以内
   RRAn Adjacent to North-South Railroad    毗邻南北铁路
   PosN Near positive off-site feature--park, greenbelt, etc.靠近公园绿地
   PosA Adjacent to postive off-site feature 毗邻优势资源
   RRNe Within 200' of East-West Railroad 东西铁路200公里以内
   RRAe Adjacent to East-West Railroad  毗邻东西铁路

Condition2: Proximity to various conditions (if more than one is present) 周边资源2

   Artery   Adjacent to arterial street
   Feedr    Adjacent to feeder street   
   Norm Normal  
   RRNn Within 200' of North-South Railroad
   RRAn Adjacent to North-South Railroad
   PosN Near positive off-site feature--park, greenbelt, etc.
   PosA Adjacent to postive off-site feature
   RRNe Within 200' of East-West Railroad
   RRAe Adjacent to East-West Railroad

BldgType: Type of dwelling 寓所类型

   1Fam Single-family Detached  独栋,独立式的房屋
   2FmCon   Two-family Conversion; originally built as one-family dwelling 拆成两户的独立式的房屋
   Duplx    Duplex 双拼
   TwnhsE   Townhouse End Unit 联排别墅两端的单元
   TwnhsI   Townhouse Inside Unit 联排别墅中间的单元

HouseStyle: Style of dwelling 房屋样式

   1Story   One story 一层
   1.5Fin   One and one-half story**: 2nd level finished 一层半,完工
   1.5Unf   One and one-half story**: 2nd level unfinished 一层半,未完工
   2Story   Two story 两层
   2.5Fin   Two and one-half story**: 2nd level finished 两层半,完工
   2.5Unf   Two and one-half story**: 2nd level unfinished 两层半,未完工
   SFoyer   Split Foyer
   SLvl Split Level 错层住宅 (和Split Foyer差不多)

OverallQual: Rates the overall material and finish of the house 房屋质量,房屋的整体材料和装修

   10   Very Excellent 非常好
   9    Excellent
   8    Very Good
   7    Good
   6    Above Average
   5    Average
   4    Below Average
   3    Fair
   2    Poor
   1    Very Poor 非常差

OverallCond: Rates the overall condition of the house 房屋的整体状况 10 Very Excellent 非常好 9 Excellent 8 Very Good 7 Good 6 Above Average
5 Average 4 Below Average
3 Fair 2 Poor 1 Very Poor 非常差

YearBuilt: Original construction date 原始施工日期,也就是房屋年代

YearRemodAdd: Remodel date (same as construction date if no remodeling or additions) 改建日期(如无改建或增建与施工日期相同)

RoofStyle: Type of roof 屋顶类型

   Flat Flat 平的
   Gable    Gable 有山墙的
   Gambrel  Gabrel (Barn) 复斜屋顶(谷仓),单词应该是gambrel
   Hip  Hip 瓦片
   Mansard  Mansard 双重斜坡的屋顶
   Shed Shed 只有单面倾斜的屋顶

RoofMatl: Roof material 屋顶材料

   ClyTile  Clay or Tile 粘土或瓷砖
   CompShg  Standard (Composite) Shingle 标准(复合)瓦
   Membran  Membrane 张拉膜屋
   Metal    Metal 金属
   Roll Roll 纸、织物等
   Tar&Grv  Gravel & Tar 沥青
   WdShake  Wood Shakes 盖屋板
   WdShngl  Wood Shingles 木瓦

Exterior1st: Exterior covering on house 外墙面1

   AsbShng  Asbestos Shingles 石棉瓦
   AsphShn  Asphalt Shingles 沥青瓦
   BrkComm  Brick Common 普通砖
   BrkFace  Brick Face 外墙饰面
   CBlock   Cinder Block 渣煤(空心)砖
   CemntBd  Cement Board 水泥板
   HdBoard  Hard Board 硬纸板
   ImStucc  Imitation Stucco 仿灰泥
   MetalSd  Metal Siding 金属壁
   Other    Other 其他
   Plywood  Plywood 胶合板
   PreCast  PreCast 预制板
   Stone    Stone 石头
   Stucco   Stucco 灰泥
   VinylSd  Vinyl Siding 乙烯基壁板;防水片
   Wd Sdng  Wood Siding 木壁板
   WdShing  Wood Shingles 木瓦

Exterior2nd: Exterior covering on house (if more than one material) 外墙面2

   AsbShng  Asbestos Shingles
   AsphShn  Asphalt Shingles
   BrkComm  Brick Common
   BrkFace  Brick Face
   CBlock   Cinder Block
   CemntBd  Cement Board
   HdBoard  Hard Board
   ImStucc  Imitation Stucco
   MetalSd  Metal Siding
   Other    Other
   Plywood  Plywood
   PreCast  PreCast
   Stone    Stone
   Stucco   Stucco
   VinylSd  Vinyl Siding
   Wd Sdng  Wood Siding
   WdShing  Wood Shingles

MasVnrType: Masonry veneer type 表层砌体

   BrkCmn   Brick Common 普通砖
   BrkFace  Brick Face 外墙饰面
   CBlock   Cinder Block 渣煤(空心)砖
   None None 其他
   Stone    Stone 石头

MasVnrArea: Masonry veneer area in square feet 表层砌体面积,单位平方英尺

ExterQual: Evaluates the quality of the material on the exterior 外观材料质量

   Ex   Excellent
   Gd   Good
   TA   Average/Typical
   Fa   Fair
   Po   Poor

ExterCond: Evaluates the present condition of the material on the exterior 外观材料现状

   Ex   Excellent
   Gd   Good
   TA   Average/Typical
   Fa   Fair
   Po   Poor

Foundation: Type of foundation

   BrkTil   Brick & Tile 砖瓦
   CBlock   Cinder Block 渣煤(空心)砖
   PConc    Poured Contrete 混凝土浇筑,单词应该是 Poured concrete
   Slab Slab 板(猜测是混凝土面板)
   Stone    Stone 石头
   Wood Wood 木头

BsmtQual: Evaluates the height of the basement 地下室高度

   Ex   Excellent (100+ inches)  254厘米
   Gd   Good (90-99 inches)
   TA   Typical (80-89 inches)
   Fa   Fair (70-79 inches)
   Po   Poor (<70 inches ≈178厘米
   NA   No Basement

BsmtCond: Evaluates the general condition of the basement 地下室状况

   Ex   Excellent
   Gd   Good
   TA   Typical - slight dampness allowed 轻微潮湿
   Fa   Fair - dampness or some cracking or settling 潮湿或开裂或沉淀
   Po   Poor - Severe cracking, settling, or wetness 严重开裂、沉降或潮湿
   NA   No Basement

BsmtExposure: Refers to walkout or garden level walls https**://adampillmore.wordpress.com/2010/02/15/basements/ A standard lot is mostly flat, and the basement is underground with “window wells” encasing all the basement windows. A walkout lot has at least 6-7 feet of slope from the front of the lot going toward the rear of the home. A garden-level lot is somewhere between those two, where there is slope on the lot but not the 6-7 feet necessary for a walkout condition.

   Gd   Good Exposure
   Av   Average Exposure (split levels or foyers typically score average or above)  
   Mn   Mimimum Exposure
   No   No Exposure
   NA   No Basement

BsmtFinType1: Rating of basement finished area 地下室成品面积评级1

   GLQ  Good Living Quarters
   ALQ  Average Living Quarters
   BLQ  Below Average Living Quarters   
   Rec  Average Rec Room
   LwQ  Low Quality
   Unf  Unfinshed
   NA   No Basement

BsmtFinSF1: Type 1 finished square feet 地下室成品面积评级1的面积

BsmtFinType2: Rating of basement finished area (if multiple types) 地下室成品面积评级2

   GLQ  Good Living Quarters
   ALQ  Average Living Quarters
   BLQ  Below Average Living Quarters   
   Rec  Average Rec Room
   LwQ  Low Quality
   Unf  Unfinshed
   NA   No Basement

BsmtFinSF2: Type 2 finished square feet 地下室成品面积评级2的面积

BsmtUnfSF: Unfinished square feet of basement area 地下室未成品面积

TotalBsmtSF: Total square feet of basement area 地下室总面积

Heating: Type of heating 供暖情况

   Floor    Floor Furnace 地板炉,地暖
   GasA Gas forced warm air furnace 燃气直接加热空气
   GasW Gas hot water or steam heat 燃气热水供暖
   Grav Gravity furnace 重力炉,https**://www.carneyphc.com/blog/heating/question-from-buckingham-what-is-a-gravity-furnace/
   OthW Hot water or steam heat other than gas 热水或者热蒸汽,感觉像集中供暖
   Wall Wall furnace 壁炉

HeatingQC: Heating quality and condition 供暖设备的质量与状况

   Ex   Excellent
   Gd   Good
   TA   Average/Typical
   Fa   Fair
   Po   Poor

CentralAir: Central air conditioning 是否有中央空调

   N    No
   Y    Yes

Electrical: Electrical system 电气系统

   SBrkr    Standard Circuit Breakers & Romex 标准断路器,线材全部为Romex
   FuseA    Fuse Box over 60 AMP and all Romex wiring (Average) 超过60安培保险丝,线材全部为Romex
   FuseF    60 AMP Fuse Box and mostly Romex wiring (Fair) 60安培保险丝,线材绝大部分为Romex
   FuseP    60 AMP Fuse Box and mostly knob & tube wiring (poor) 60安培保险丝,劣质线材
   Mix  Mixed 混杂的

1stFlrSF: First Floor square feet 第一层面积

2ndFlrSF: Second floor square feet 第二层面积

LowQualFinSF: Low quality finished square feet (all floors) 低质量建筑面积

GrLivArea: Above grade (ground) living area square feet 地上生活区面积

BsmtFullBath: Basement full bathrooms 地下全浴室的个数(带浴缸的厕所) a "full bathroom" (or "full bath"), containing four plumbing fixtures**: a toilet and sink, and either a bathtub with a shower, or a bathtub and a separate shower stall; "half (1/2) bath" (or "powder room") containing just a toilet and sink; and "3/4 bath" containing toilet, sink, and shower, although the terms vary from market to market.

BsmtHalfBath: Basement half bathrooms 地下半浴室的个数(不带浴缸的厕所)

FullBath: Full bathrooms above grade 应该是地上全浴室的个数(带浴缸的厕所)

HalfBath: Half baths above grade 应该是地上半浴室的个数(不带浴缸的厕所)

Bedroom: Bedrooms above grade (does NOT include basement bedrooms) 地上卧室个数

Kitchen: Kitchens above grade 地上厨房个数

KitchenQual: Kitchen quality 厨房的品质

   Ex   Excellent
   Gd   Good
   TA   Typical/Average
   Fa   Fair
   Po   Poor

TotRmsAbvGrd: Total rooms above grade (does not include bathrooms) 四方房屋个数,(不包括浴室)

Functional: Home functionality (Assume typical unless deductions are warranted) 房屋的状态,是否working; able to work

   Typ  Typical Functionality
   Min1 Minor Deductions 1  小额扣除
   Min2 Minor Deductions 2
   Mod  Moderate Deductions 适度扣减
   Maj1 Major Deductions 1
   Maj2 Major Deductions 2
   Sev  Severely Damaged    严重损坏
   Sal  Salvage only 要抢救的建筑

Fireplaces: Number of fireplaces 壁炉数

FireplaceQu: Fireplace quality 壁炉状态

   Ex   Excellent - Exceptional Masonry Fireplace   特殊砌筑壁炉
   Gd   Good - Masonry Fireplace in main level  主楼砌筑壁炉
   TA   Average - Prefabricated Fireplace in main living area or Masonry Fireplace in basement  主要生活区的预制壁炉或地下室的砌筑壁炉
   Fa   Fair - Prefabricated Fireplace in basement  地下室预制壁炉
   Po   Poor - Ben Franklin Stove   本富兰克林炉
   NA   No Fireplace  无壁炉

GarageType: Garage location 车库位置

   2Types   More than one type of garage    多个车库
   Attchd   Attached to home    挨着房子的车库
   Basment  Basement Garage 地下车库
   BuiltIn  Built-In (Garage part of house - typically has room above garage)   内置车库
   CarPort  Car Port    车棚
   Detchd   Detached from home 和房子分开的车库
   NA   No Garage 没有车库

GarageYrBlt: Year garage was built 年车库建成时间

GarageFinish: Interior finish of the garage 车库是否修建完成

   Fin  Finished 完成
   RFn  Rough Finished  基本完成
   Unf  Unfinished 未完成
   NA   No Garage

GarageCars: Size of garage in car capacity 车库容量

GarageArea: Size of garage in square feet 车库面积

GarageQual: Garage quality 车库质量

   Ex   Excellent
   Gd   Good
   TA   Typical/Average
   Fa   Fair
   Po   Poor
   NA   No Garage

GarageCond: Garage condition 车库状况

   Ex   Excellent
   Gd   Good
   TA   Typical/Average
   Fa   Fair
   Po   Poor
   NA   No Garage

PavedDrive: Paved driveway 铺砌车道

   Y    Paved 全部铺砌
   P    Partial Pavement 部分路面
   N    Dirt/Gravel 没有铺路面,污垢/砾石

WoodDeckSF: Wood deck area in square feet (屋后供憩息的)木制平台面积

OpenPorchSF: Open porch area in square feet 敞廊面积

EnclosedPorch: Enclosed porch area in square feet 内置廊面积

3SsnPorch: Three season porch area in square feet 三季门廊面积

ScreenPorch: Screen porch area in square feet 纱窗阳台;纱门门廊-面积

PoolArea: Pool area in square feet 泳池面积

PoolQC: Pool quality 泳池质量

   Ex   Excellent
   Gd   Good
   TA   Average/Typical
   Fa   Fair
   NA   No Pool

Fence: Fence quality 围栏质量

   GdPrv    Good Privacy
   MnPrv    Minimum Privacy
   GdWo Good Wood
   MnWw Minimum Wood/Wire
   NA   No Fence

MiscFeature: Miscellaneous feature not covered in other categories 房屋的其他附属

   Elev Elevator 电梯
   Gar2 2nd Garage (if not described in garage section) 第二个车库
   Othr Other 其他
   Shed Shed (over 100 SF) 超过100平方英尺的库/棚
   TenC Tennis Court 网球场
   NA   None 无

MiscVal: dollar Value of miscellaneous feature 房屋的其他附属美元价格

MoSold: Month Sold (MM) 成交月份

YrSold: Year Sold (YYYY) 成交年份

SaleType: Type of sale 销售类型

   WD   Warranty Deed - Conventional    担保契约 - 常规的
   CWD  Warranty Deed - Cash    担保契约 - 现金
   VWD  Warranty Deed - VA Loan 担保契约 - 由美国退伍军人事务部担保的抵押贷款
   New  Home just constructed and sold 新房出售
   COD  Court Officer Deed/Estate 法院契据/房产
   Con  Contract 15\% Down payment regular terms 合同15\%定期付款
   ConLw    Contract Low Down payment and low interest 低定金低利息贷款合同
   ConLI    Contract Low Interest 低利息贷款合同
   ConLD    Contract Low Down 低定金合同
   Oth  Other   其他

SaleCondition: Condition of sale 销售状况

   Normal   Normal Sale 正常销售
   Abnorml  Abnormal Sale -  trade, foreclosure, short sale 异常销售
   AdjLand  Adjoining Land Purchase 毗邻土地收购
   Alloca   Allocation - two linked properties with separate deeds, typically condo with a garage unit  分配-两个相连的财产有单独的行为,典型的公寓与车库单位
   Family   Sale between family members 在家庭成员之间销售
   Partial  Home was not completed when last assessed (associated with New Homes)   上次评估时没有完成(与新居有关)