The Dataset was acquired from https://www.kaggle.com/c/titanic

For data preprocessing, I firstly defined three transformers:

  • DataFrameSelector: Select features to handle.
  • CombinedAttributesAdder: Add a categorical feature Age_cat which divided all passengers into three catagories according to their ages.
  • ImputeMostFrequent: Since the SimpleImputer( ) method was only suitable for numerical variables, I wrote an transformer to impute string missing values with the mode value. Here I was inspired by https://stackoverflow.com/questions/25239958/impute-categorical-missing-values-in-scikit-learn.

Then I wrote pipelines separately for different features

  • For numerical features, I applied DataFrameSelector, SimpleImputer and StandardScaler
  • For categorical features, I applied DataFrameSelector, ImputeMostFrequent and OneHotEncoder
  • For the new created feature Age_cat, since itself was a category but was derived from a numerical feature, I wrote an individual pipeline to impute the missing values and encode the categories.

Finally, we can build a full pipeline through FeatureUnion. Here is the code:

 # Read data
import pandas as pd
import numpy as np
import os
titanic_train = pd.read_csv('Dataset/Titanic/train.csv')
titanic_test = pd.read_csv('Dataset/Titanic/test.csv')
submission = pd.read_csv('Dataset/Titanic/gender_submission.csv') # Divide attributes and labels
titanic_labels = titanic_train['Survived'].copy()
titanic = titanic_train.drop(['Survived'],axis=1) # Feature Selection
from sklearn.base import BaseEstimator, TransformerMixin class DataFrameSelector(BaseEstimator, TransformerMixin):
def __init__(self,attribute_name):
self.attribute_name = attribute_name
def fit(self, X):
return self
def transform (self, X, y=None):
if 'Pclass' in self.attribute_name:
X['Pclass'] = X['Pclass'].astype(str)
return X[self.attribute_name] # Feature Creation
class CombinedAttributesAdder(BaseEstimator, TransformerMixin):
def fit(self, X, y=None):
return self # nothing else to do
def transform(self, X, y=None):
Age_cat = pd.cut(X['Age'],[0,18,60,100],labels=['child', 'adult', 'old'])
Age_cat=np.array(Age_cat)
return pd.DataFrame(Age_cat,columns=['Age_Cat']) # Impute Categorical variables
class ImputeMostFrequent(BaseEstimator, TransformerMixin):
def fit(self, X, y=None):
self.fill = pd.Series([X[c].value_counts().index[0] for c in X],index=X.columns)
return self
def transform(self, X, y=None):
return X.fillna(self.fill) #Pipeline
from sklearn.impute import SimpleImputer # Scikit-Learn 0.20+
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import OneHotEncoder
from sklearn.pipeline import FeatureUnion num_pipeline = Pipeline([
('selector',DataFrameSelector(['Age','SibSp','Parch','Fare'])),
('imputer', SimpleImputer(strategy="median")),
('std_scaler', StandardScaler()),
]) cat_pipeline = Pipeline([
('selector',DataFrameSelector(['Pclass','Sex','Embarked'])),
('imputer',ImputeMostFrequent()),
('encoder', OneHotEncoder()),
]) new_pipeline = Pipeline([
('selector',DataFrameSelector(['Age'])),
#('imputer', SimpleImputer(strategy="median")),
('attr_adder',CombinedAttributesAdder()),
('imputer',ImputeMostFrequent()),
('encoder', OneHotEncoder()),
]) full_pipeline = FeatureUnion([
("num", num_pipeline),
("cat", cat_pipeline),
("new", new_pipeline),
]) titanic_prepared = full_pipeline.fit_transform(titanic)

Another thing I want to mention is that the output of a pipeline should be a 2D array rather a 1D array. So if you wanna choose only one feature, don't forget to transform the 1D array by reshape() method. Otherwise, you will receive an error like

ValueError: Expected 2D array, got 1D array instead

Specifically, apply reshape(-1,1) for column and reshape(1,-1). More about the issue can be found at https://stackoverflow.com/questions/51150153/valueerror-expected-2d-array-got-1d-array-instead.


												

[Machine Learning with Python] My First Data Preprocessing Pipeline with Titanic Dataset的更多相关文章

  1. Getting started with machine learning in Python

    Getting started with machine learning in Python Machine learning is a field that uses algorithms to ...

  2. 《Learning scikit-learn Machine Learning in Python》chapter1

    前言 由于实验原因,准备入坑 python 机器学习,而 python 机器学习常用的包就是 scikit-learn ,准备先了解一下这个工具.在这里搜了有 scikit-learn 关键字的书,找 ...

  3. Python (1) - 7 Steps to Mastering Machine Learning With Python

    Step 1: Basic Python Skills install Anacondaincluding numpy, scikit-learn, and matplotlib Step 2: Fo ...

  4. 【Machine Learning】Python开发工具:Anaconda+Sublime

    Python开发工具:Anaconda+Sublime 作者:白宁超 2016年12月23日21:24:51 摘要:随着机器学习和深度学习的热潮,各种图书层出不穷.然而多数是基础理论知识介绍,缺乏实现 ...

  5. Machine Learning的Python环境设置

    Machine Learning目前经常使用的语言有Python.R和MATLAB.如果采用Python,需要安装大量的数学相关和Machine Learning的包.一般安装Anaconda,可以把 ...

  6. [Machine Learning with Python] Data Preparation through Transformation Pipeline

    In the former article "Data Preparation by Pandas and Scikit-Learn", we discussed about a ...

  7. [Machine Learning with Python] Data Preparation by Pandas and Scikit-Learn

    In this article, we dicuss some main steps in data preparation. Drop Labels Firstly, we drop labels ...

  8. [Machine Learning with Python] Familiar with Your Data

    Here I list some useful functions in Python to get familiar with your data. As an example, we load a ...

  9. [Machine Learning with Python] How to get your data?

    Using Pandas Library The simplest way is to read data from .csv files and store it as a data frame o ...

随机推荐

  1. (Winform)控件中添加GIF图片以及运用双缓冲使其不闪烁以及背景是gif时使控件(如panel)变透明

    Image img = Image.FromFile(@"C:\Users\joeymary\Desktop\3.gif"); pictureBox1.Image =img.Clo ...

  2. Aizu 2560 Point Distance FFT

    题意: 有一个\(N \times N\)的方阵,第\(x\)行第\(y\)列有\(C_{x,y}\)个点\((0 \leq C_{x,y} \leq 9)\). 任选两个不同的点,求两点欧几里德距离 ...

  3. activity切换交互动画

    activity切换的时候,想要有动画,那么... 1.想要有效果的activity设置theme <activity android:name=".MainActivity" ...

  4. MySQL之索引(一)

    创建高性能索引 索引是存储引擎用于快速找到记录的一种数据结构.这是索引的基本功能.索引对于良好的性能非常关键.尤其是当表中的数据量越来越大时,索引对性能的影响愈发重要.在数据量较小且负载较低时,不恰当 ...

  5. Python协程详解(一)

    yield有两个意思,一个是生产,一个是退让,对于Python生成器的yield来说,这两个含义都成立.yield这个关键字,既可以在生成器中产生一个值,传输给调用方,同时也可以从调用方那获取一个值, ...

  6. 【Remove Duplicates from Sorted Array II】cpp

    题目: Follow up for "Remove Duplicates":What if duplicates are allowed at most twice? For ex ...

  7. 图说不为人知的IT传奇故事-1-计算机新生

    此系列文章为“图说不为人知的IT传奇故事”,各位大忙人可以在一分钟甚至几秒内了解把握整个内容,真可谓“大忙人的福利”呀!!希望各位IT界的朋友在钻研技术的同时,也能在文学.历史上有所把握.了解这些故事 ...

  8. fastjosn在低版本丢字段问题

    简单的说: 对于java bean中有字段类似pId这种写法,特征是第一个字母小写,第二个字母大写,在eclipse中生成的getter setter方法是 getpId, setpId. 在低版本的 ...

  9. Windows 7中安装SQL2005提示IIS未安装 解决办法 .(转载)

    在Windows 7系统中安装SQL Server 2005时,可能会收到一个警告:提示IIS未安装或者未启用.在通过“控制面板”的“打开或关闭Windows功能”按默认设置安装IIS后,发现仍有这个 ...

  10. html之表单标签

    表单标签的属性: 用于向服务器传输数据 表单能够包含input元素,比如文本字段,复选框,单选框,提交按钮等等 表单还可以包含textarea(简介之类的),select(下拉),fieldset和l ...