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. 匯入基本的library
  • 2.讀取資料並了解資料
  • 3.繪製圖表分析資料
  • 5. 使用Skikit-learn library
  • 6. 利用Skikit-learn進行預測

Was this helpful?

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

2.1.11.2.Linear regression with Python

Previous2.1.11.1.Introduction to Scikit-learnNext2.1.12.Logistic regression

Last updated 5 years ago

Was this helpful?

1. 匯入基本的library

  • , , ,

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

%matplotlib inline

2.讀取資料並了解資料

  • 讀取資料

      df = pd.read_csv('USA_Housing.csv')
  • 可以確認前幾筆資料的內容長怎樣, 例如確認前10筆

      df.head(10)
  • 了解資料欄位的型別以及變數的型態

      df.info()
  • 取得資料的基本統計數值: 如數量, 平均值, 標準差, 四分位數等數值

      df.describe()
  • 取得df中的欄位名稱

      df.columns
    
      output:
      Index(['Avg. Area Income', 'Avg. Area House Age', 'Avg. Area Number of Rooms',
         'Avg. Area Number of Bedrooms', 'Area Population', 'Price', 'Address'],
        dtype='object')

3.繪製圖表分析資料

  •   sns.pairplot(df)
  •   sns.distplot(df['Price'])
    • 其中df.corr()會拿資料中的數值欄位來形成相關係數矩陣

      sns.heatmap(df.corr(), annot = True)

5. 使用Skikit-learn library

  • Skikit-learn model的使用方式都是用from sklearn.family import model的形式

      # from sklearn.family import model
      from sklearn.cross_validation import train_test_split
  • 首先介紹train_test_split, 這個函式可以隨機劃分訓練集和測試集

      #从样本中随机的按比例选取train data和testdata
      #X:features of data, 或是稱為所要劃分的樣本特徵集
      #Y:labels of data, 或是稱為所要劃分的樣本結果
      #test_size:樣本占比, 如果是整数的话就是樣本的数量
      #random_state:是隨機數的種子
      X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.4, random_state=101)
    • 舉例來說, 如果我們想用每天的氣溫資料預測飲料的銷售業績, 則可以把X帶入每天的氣溫資料, Y帶入飲料的銷售業績資料

  • 建立複回歸模型

    • 在這個例子中, 我們希望做的事情是用Avg. Area Income (平均區域所得), Avg. Area House Age (平均屋齡), Avg. Area Number of Rooms (平均房間數), Avg. Area Number of Bedrooms (平均臥房數), Area Population (區域人數)來預估Price (房價), 回歸模型中若有多個變量參與則稱為複回歸模型

      X = df[['Avg. Area Income', 'Avg. Area House Age', 'Avg. Area Number of Rooms', 'Avg. Area Number of Bedrooms', 'Area Population']]
      Y = df['Price']
      X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.4, random_state=101)
    • 建立線性回歸模型

      from sklearn.linear_model import LinearRegression
      lm = LinearRegression()
      lm.fit(X_train, y_train)
      #印出相關係數
      print(lm.coef_)
      #印出截距
      print(lm.intercept_)

6. 利用Skikit-learn進行預測

  • 用測試集資料進行預測

      predictions = lm.predict(X_test)
  • 繪圖來看看預測值與測試集的一致性

    • 散布圖

      plt.scatter(y_test, predictions)
    • 直方圖

      sns.distplot((y_test-predictions))
    from sklearn import metrics
    metrics.mean_absolute_error(y_test, predictions)
    metrics.mean_squared_error(y_test, predictions)
    np.sqrt(metrics.mean_squared_error(y_test, predictions))

利用, 多變量圖的輸入資料可以用sns.load_dataset()讀入資料, 也可以用pd.read_csv所讀入的資料

利用

利用

評估線性回歸模型品質的指標 (Regression Evaluation Metrics) 1. Mean Absolute Error (MAE): 即為平均誤差 2. Mean Square Error (MSE): 平均平方誤差 3. Root Mean Square Error (RMSE)

pandas
numpy
matplotlib
seaborn
seaborn繪製多變量圖(pairplot)
seanborn繪製散點圖(distplot)
seaborn繪製不同數值間相關係數的熱力圖