Kaggle Titanic Tutorial by Manav Sehgal

Data science work flow: 

  1. define question 
  2. get trainning & testing data 
  3. prepare data, such as cleanse data 
  4. explore data, such as find certain pattern, and analyze it. 
  5. predict data, build the model 
  6. report & visualize

goal: 

  1. find correlation among the features 
  2. convert categorial value to numerial value 
  3. complete: if there is any missing value 
  4. detect: if any outlier exists, or discard a feature if it's not contributing 
  5. create: if we can create new features based on the existing feature(s). 
  6. visualizing: select the right visualization tool to present the data 

Analyze data 

train.columns          # 返回的是index
train.columns.values   # 返回的是array格式, 更方便使用

Which features are categorical? Define them. 

  1. nominal : name without any quantitative value 

  2.  ordinal: has an order, but the difference between each other is unknown. like Pclass in Titanic. 

  3. Interval: not only we know the order, but also we know the difference between each other. like zip code. 

  4. ratio: besides the characteristics in interval, it has an absolute zero, like temperature. 

Which features are numerical? Define them. 

  1. discrete: how many siblings do you have 

  2. continuous: price of the ticket, age

What features that contains MIXED data type, such as alphanumeric? Find out 

What features that contain typo or error? Find out 

Which features that contain null, empty values? Correct them. 

train=pd.read_csv('train.csv',index_col='PassengerId') # 修改index column

查看每个feature的数据类型:

data.info() 

查看每个numerical feature的数据分布情况:

data.describe() # 显示的都是numerical features

查看每个caregorical feature 的数据分布情况:

data.describe(include=['O']     # 这里是大写字母O,不是零

查看某一列分别有哪些不同的值,并列出每一个不同的值的数量:value_counts()注意count是复数

train_df['Sex'].value_counts()

另一个只是简单地显示某一列有多少值

train_df['Sex'].count()

在正式take any action前,我们需要做几个方面的工作: 

  1. find correlating features
  2. fill any missing values 
  3. drop any features that contain too many missing values, null, or duplicates. 
  4. create new feature by combining existing features, or extracting from existing feature, or by converting continuous numerical feature to ordinal categorical feature( such as age 1-80 to 1-20,21-30 etc) 
  5. is there any your own assumptions that you think are correlated to the output. 

Feature Selection by Groupby()

通过将一些features分成不同阶段,比如性别。看出不同性别与存活率的关系,最终帮助我们决定某个feature是否保留或删除。 

data.groupby().mean()

sort_values(by=你想要按哪列排序,ascending=True as default)

train[['Pclass','Survived']].groupby(['Pclass'],as_index=False) 
# 选择多个列时,train[['Pclass'],['Survived']]这样是不对的。 是左右两个[[列1,列2]]

train[['Pclass','Survived']].groupby(['Pclass'],as_index=False).mean()

train[['Pclass','Survived']].groupby(['Pclass'],as_index=False).mean().sort_values('Survived',ascending=False) 

groupby():

# groupby()内的参数: as_index=True as default
# 如果你不想用分组的feature作为index,则说明as_index=False

data['Pclass'].groupby(['Survived'],as_index=False)
data['Pclass'].groupby(data['Survived'],as_index=False)
data['Pclass'].groupby(data.Survived,as_index=False)


# 通常groupby之后,你是想要总结你分组后的数据,所以通常后面搭配mean() 这样的函数一起使用

data.groupby().mean
data.groupby().describe() 
median()
max()
data.groupby(["班级","性别"]).agg([np.sum, np.mean, np.std]) #一次运用多个函数同时计算


# 选择两列来分组:

data.groupby([data['key1'],data['key2']])
data.groupby(['key1','key2'])


# 选择一列来分组:两种表达式都可以

df.groupby(df['key1'])
df.groupby(['key1'])


# 选取某一列 将其按其他feature来分组

df=data['Fare'].groupby(data['Sex'])  #将Fare列用Sex来分组
survived_sex=data['Survived'].groupby(['Sex']).sum()

Feature Selection by Visualizing 

 记住: 你visualize这些correlation的最终目的是为了做feature selection

  • sns.facetgrid()

“当您想要在数据集的子集中分别可视化变量的分布或多个变量之间的关系时,该类非常有用。

一个FacetGrid可以与多达三个维度可以得出:row,col,和hue。前两个与得到的轴阵列有明显的对应关系; 将色调变量视为沿深度轴的第三个维度,其中不同的级别用不同的颜色绘制。

这里row和column的意思是:如果你在column参数输入的是Survived,那么就会有2列,Survived=0和Survived=1。如果输入了row参数为Pclass,那么就会有3行,,分别为Pclass=1,Pclass=2,Pclass=3。所以最后出来的图像是一个3x2的Matrix 

  基本工作流程是FacetGrid使用数据集和用于构造网格的变量初始化对象。然后,可以通过调用FacetGrid.map()或将一个或多个绘图函数应用于每个子集 FacetGrid.map_dataframe()。”

总之,选中你想要分析的feature作为FacetGrid的col或row参数。结果会根据参数分成几个不同的画像。

比如,你选择Survived作为参数,数据中Survived为1和0,那么output会是两个图像,一个显示survived=1 另一个survived=0,横轴和纵轴则是你map()里面的参数。 

如果你选择了survived作为col参数,pclass作为row参数,survived有1和0 Pclass有1、2、3,那么output图像一共会有3x2=6个图像。 

而图像上的横轴与纵轴 跟FacetGrid参数没关系,是map()里输入的参数决定的。 map()的参数不管是几个 都不影响最终output图像的个数。 

参考:​​​​​​Seaborn学习(一)------- 构建结构化多绘图网格(FacetGrid()、map())详解_进击的菜鸟-CSDN博客

  • Correlating numerical features:

这里用到的histogram 来分析Age这个continuous numerical variable。用histogram的原因是它把年龄这个numerical varibale分成了不同的bins,这样更容易看出不同的年龄段是存活率的关系。 

g=sns.FacetGrid(train_df,col='Survived)
g.map(plt.hist,'Age',bins=20)

做完关于feature和result的corrrelation visualization,我们需要决定几点:

  1.         是否保留这个feature,它对我们接下来的预测是有有用。
  2.         如果保留,则需要对其含有的null 或missing value进行完整。 
  3.         是否需要对这个continuous numerical feature进行划分档次
  • Correlating between numerical feature and ordinal feature 

grid=sns.FacetGrid(train_df, col='Survived',row='Pclass')
grid.map(plt.hist,'Age',bins=20)   # when plot hist, don't forget state bins 
grid.add_legend()
  • Correlating categorical feature 

sns.pointplot(): 

点图用于集中在一个或多个分类变量的不同级别之间的比较,有时比条形图更有用。
注:点图只显示平均值(或其他估计值)。

一些参数:seaborn.pointplot(x=None, y=None, hue=None, data=None,。。。。。

grid=sns.FacetGrid(train_df,'Embarked')
grid.map(sns.pointplot,'Pclass', 'Survived', 'Sex')
grid.add_legend()
  • Correlating categorical and numerical features

seaborn.barplot(x=None, y=None, hue=None, data=None, order=None, hue_order=None,\
                estimator=<function mean>,ci=95, n_boot=1000, units=None, orient=None,\
                color=None, palette=None, saturation=0.75,\
                errcolor='.26', errwidth=None, capsize=None, dodge=True, ax=None, **kwargs)

条形图以矩形条的方式展示数据的点估值

输入数据的格式可以不同,包括:

以列表,numpy array 或者 pandas 中的 Series object 表示的向量。这些向量可以直接传入 x, y, 以及 hue 参数。
长表, x 值,y 值和色相变量决定了数据是如何绘制的。
宽表,每个列的数值都会被绘制出来.
数组或者列表的向量。
大多数情况下,可以使用 numpy 的对象或者 python 的对象,但是用 pandas 对象更好,因为相关的列名会被标注在图标上。 另外,为了控制绘图元素 也可以可以用分类类型来组合不同的变量。

参考:超详细Seaborn绘图 ——(一)barplot_邱邱邱的博客-CSDN博客_barplot

grid=sns.FacetGrid(train_df,row='Embarked', col='Survived')
grid.map(sns.barplot, 'Sex', 'Fare')
grid.add_legend()

Wrangle Data 

  1. Drop 

通过上个section,已经得出了哪些feature是和output相关 哪些并没有什么联系。

把没有联系的feature drop掉。

drop()

注意:drop()默认的是drop rows,所以当drop feature时,需要额外标明axis=1。 

#标明drop的参数axis,表明是drop column

train=train.drop(['Ticket','Cabin'],axis=1) 


#不仅要drop train数据集,同时也不要忘了drop test数据集,使两个数据集所有的variable/feature是一致的。 

test=test.drop(['Ticket','Cabin'],axis=1)


# 确认不需要的feature已经drop掉

print(train.shape,test.shape) 


2. Create new feature based on existing features

extract(), 参数expand=False returns a DataFrame.

for dataset in combine:
    dataset['Title']=dataset.Name.str.extract('[A-Za-a]+\.',expand=False)

pd.crosstab(train_df['Title'],train_df['Sex'])

pd.crosstab(行,列),同时行和列都可以是复合的:

以下代码来自:关于pandas中crosstab的用法 - 知乎

pd.crosstab(df.Nationality, df.Handedness)

pd.crosstab(df.Sex, df.Handedness, margins = True)

pd.crosstab(df.Sex, [df.Handedness, df.Nationality], margins = True)

pd.crosstab([df.Nationality, df.Sex], df.Handedness, margins = True)


# 用来求百分比:

pd.crosstab(df.Sex, df.Handedness, normalize='index')  
# 显示的不同sex在每个feature的百分比情况


# 求平均值:

import numpy as np
pd.crosstab(df.Sex, df.Handedness, values=df.Age, aggfunc=np.average)

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值