Python
  • Introduction
  • Chapter 1.Notes from research
    • 1.Introduction of Python
    • 2. Build developer environment
      • 2.1.Sublime Text3
      • 2.2.Jupyter(IPython notebook)
        • 2.2.1.Introduction
        • 2.2.2.Basic usage
        • 2.2.3.some common operations
      • 2.3.Github
        • 2.3.1.Create Github account
        • 2.3.2.Create a new repository
        • 2.3.3.Basic operations: config, clone, push
      • 2.4.Install Python 3.4 in Windows
    • 3. Write Python code
      • 3.1.Hello Python
      • 3.2.Basic knowledges
      • 3.3.撰寫獨立python程式
      • 3.4.Arguments parser
      • 3.5.Class
      • 3.6.Sequence
    • 4. Web crawler
      • 4.1.Introduction
      • 4.2.requests
      • 4.3.beautifulSoup4
      • 3.4.a little web crawler
    • 5. Software testing
      • 5.1. Robot Framework
        • 1.1.Introduction
        • 1.2.What is test-automation framework?
        • 1.3.Robot Framework Architecture
        • 1.4.Robot Framework Library
        • 1.5.Reference
    • 6. encode/ decode
      • 6.1.編碼/解碼器的基本概念
      • 6.2.常見的編碼/ 解碼錯誤訊息與其意義
      • 6.3 .處理文字檔案
    • 7. module
      • 7.1.Write a module
      • 7.2.Common module
        • 7.2.1.sched
        • 7.2.2.threading
    • 8. Integrate IIS with django
      • 8.1.Integrate IIS with django
  • Chapter 2.Courses
    • 2.1.Python for Data Science and Machine Learning Bootcamp
      • 2.1.1.Virtual Environment
      • 2.1.2.Python crash course
      • 2.1.3.Python for Data Analysis - NumPy
        • 2.1.3.1.Numpy arrays
        • 2.1.3.2.Numpy Array Indexing
        • 2.1.3.3.Numpy Operations
      • 2.1.4.Python for Data Analysis - Pandas
        • 2.1.4.1.Introduction
        • 2.1.4.2.Series
        • 2.1.4.3.DataFrames
        • 2.1.4.4.Missing Data
        • 2.1.4.5.GroupBy
        • 2.1.4.6.Merging joining and Concatenating
        • 2.1.4.7.Data input and output
      • 2.1.5.Python for Data Visual Visualization - Pandas Built-in Data Visualization
      • 2.1.6.Python for Data Visualization - Matplotlib
        • 2.1.6.1.Introduction of Matplotlib
        • 2.1.6.2.Matplotlib
      • 2.1.7.Python for Data Visualization - Seaborn
        • 2.1.7.1.Introduction to Seaborn
        • 2.1.7.2.Distribution Plots
        • 2.1.7.3.Categorical Plots
        • 2.1.7.4.Matrix Plots
        • 2.1.7.5.Grids
        • 2.1.7.6.Regression Plots
      • 2.1.8. Python for Data Visualization - Plotly and Cufflinks
        • 2.1.8.1.Introduction to Plotly and Cufflinks
        • 2.1.8.2.Plotly and Cufflinks
      • 2.1.9. Python for Data Visualization - Geographical plotting
        • 2.1.9.1.Choropleth Maps - USA
        • 2.1.9.2.Choropleth Maps - World
      • 2.1.10.Combine data analysis and visualization to tackle real world data sets
        • 911 calls capstone project
      • 2.1.11.Linear regression
        • 2.1.11.1.Introduction to Scikit-learn
        • 2.1.11.2.Linear regression with Python
      • 2.1.12.Logistic regression
        • 2.1.12.1.Logistic regression Theory
        • 2.1.12.2.Logistic regression with Python
      • 2.1.13.K Nearest Neighbors
        • 2.1.13.1.KNN Theory
        • 2.1.13.2.KNN with Python
      • 2.1.14.Decision trees and random forests
        • 2.1.14.1.Introduction of tree methods
        • 2.1.14.2.Decision trees and Random Forests with Python
      • 2.1.15.Support Vector Machines
      • 2.1.16.K means clustering
      • 2.1.17.Principal Component Analysis
    • 2.2. Machine Learning Crash Course Jam
Powered by GitBook
On this page
  • 1. Titanic: Machine Learning from Disaster
  • 2.資料探勘及分析
  • 3.分類及處理不存在的資料
  • 4.訓練及建模以預測乘客是否會生還

Was this helpful?

  1. Chapter 2.Courses
  2. 2.1.Python for Data Science and Machine Learning Bootcamp
  3. 2.1.12.Logistic regression

2.1.12.2.Logistic regression with Python

Previous2.1.12.1.Logistic regression TheoryNext2.1.13.K Nearest Neighbors

Last updated 5 years ago

Was this helpful?

1. Titanic: Machine Learning from Disaster

  • 在按下Download, 即可下載CSV檔

  • 從頁面上可得到資料欄位的說明

2.資料探勘及分析

  1. 匯入基本的library

    • import pandas as pd
      import numpy as np
      import matplotlib.pyplot as plt
      import seaborn as sns
  2. 將圖表直接嵌入到Notebook之中

     %matplotlib inline
  3. 讀取資料並了解資料

    • 讀取資料

      train = pd.read_csv('USA_Housing.csv')
    • 先了解資料欄位的型別以及變數的型態, 由pd.info()可以知道這份資料有9個欄位: 有2筆屬於float, 4筆屬於int64, 3筆屬於uint8

      train.info()
    • 可以確認前幾筆資料的內容長怎樣, 例如確認前10筆

      train.head(10)
  4. 視覺化分析

      • 可以發現Age, Cabin有一些屬於null的資料

        sns.heatmap(train.isnull(), yticklabels = False, cbar = False, cmap='viridis')
      • 表示生還者

      sns.set_style('whitegrid')
      sns.countplot(x = 'Survived', data = train)
    • sns.countplot(x = 'Survived', hue = 'Sex', data = train, palette='RdBu_r')
    • sns.countplot(x = 'Survived', hue = 'Embarked', data = train, palette='RdBu_r')
    • sns.countplot(x = 'Survived', hue = 'Pclass', data = train, palette='RdBu_r')
    • sns.distplot(train['Age'].dropna(), kde = False, bins = 30)
    • sns.countplot(x = 'SibSp', data = train)
    • train['Fare'].plot.hist(bins=40, figsize = (10, 4))
    • import cufflinks as cf
      cf.go_offline()
      train['Fare'].iplot(bins=40)
    • plt.figure(figsize=(10,7))
      sns.boxplot(x='Pclass', y='Age',data=train)

3.分類及處理不存在的資料

  • 在進行訓練之前, 需要先檢視原始資料是否有缺漏, 並設法補充缺漏的地方

    • 先對Age資料做處理: 目的是填充NA的資料

      • 定義一個function用來替換掉null值的資料

      #將null值換成假資料
      def impute_age(cols):
        Age = cols[0]
        Pclass = cols[1]
      
        if pd.isnull(Age):
      
            if Pclass == 1: 
                return 37
            elif Pclass == 2:
                return 29
            else:
                return 24
        else:
            return Age
      
      train['Age'] = train[['Age', 'Pclass']].apply(impute_age, axis = 1)
      
      #重新畫heat map
      sns.heatmap(train.isnull(), yticklabels = False, cbar = False, cmap='viridis')
    • 接著處理Cabin: 目的是丟棄NA的資料

      • drop Cabin

        train.drop('Cabin', axis = 1, inplace = True)
        #drop後仍有一些NA
        sns.heatmap(train.isnull(), yticklabels = False, cbar = False, cmap='viridis')
      • drop NA的column

        train.dropna(inplace = True)
        sns.heatmap(train.isnull(), yticklabels = False, cbar = False, cmap='viridis')
      • 處理Sex資料

        #性別
        #one hot 編碼
        sex = pd.get_dummies(train['Sex'], drop_first=True)
        sex.head()
      • 處理Embarked資料

        #登船港口
        embark = pd.get_dummies(train['Embarked'], drop_first=True)
        embark.head()
    • 將原始資料跟one-hot的資料concat在一起

      train = pd.concat([train, sex, embark], axis = 1)
      train.head()
    • 從資料中移除原始的Sex, Embarked資料, 此外移除不需要的Name, Ticket, PassengerId

      train.drop(['Sex', 'Embarked', 'Name', 'Ticket', 'PassengerId'], axis = 1, inplace = True)
      train.head()

4.訓練及建模以預測乘客是否會生還

    • 首先用train_test_split, 這個函式可以隨機劃分訓練集和測試集

      X = train.drop('Survived', axis = 1)
      Y = train['Survived']
      from sklearn.cross_validation import train_test_split
      X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.4, random_state=101)
    • 接著使用Logic regression的library進行訓練, 接著進行預測

      from sklearn.linear_model import LogisticRegression
      logmodel = LogisticRegression()
      logmodel.fit(X_train, y_train)
      predictions = logmodel.predict(X_test)
  • Evaluate model

      from sklearn.metrics import classification_report
      print(classification_report(y_test, predictions))
    • from sklearn.metrics import confusion_matrix
      confusion_matrix(y_test, predictions)

, , ,

從heat map中可以發現Age, Cabin有一些屬於null的資料

重新畫出的heat map可以看出, Age的部分的na已經處理好了

對於某些離散特徵, 例如Sex, Embarked, 可以, 目的是利用one-hot編碼數值化這些離散資料以進行後面的training

接著用除了Survived以外的資料來預測Survived, 在實際案例時可以使用另一批資料做為測試資料. 這邊使用的是

pandas
numpy
matplotlib
seaborn
Seaborn Heatmap: 創建一個映射圖以了解缺少的資料
Seaborn countplot: 瞭解倖存者的比例
Seaborn countplot:瞭解倖存者/非倖存者的男女比例
Seaborn countplot:瞭解倖存者/非倖存者的上船港口比例
Seaborn countplot:瞭解倖存者/非倖存者跟艙等間的關係
Seaborn distplot: 瞭解船上的乘客年齡分佈
Seaborn countplot:船上的人是否有兄弟姊妹: 大多數的人都是單身
pandas plot: 乘客票價區間的分佈
Plotly and Cufflinks: 建立互動式的圖表
Seaborn boxplot: 可以看出不同等級的機艙乘客的年齡分佈
轉成one-hot編碼
sklearn
confusion matrix
資料頁面