線性回歸

概念

  • label 試圖預測的變量

  • feature 預測依據(jù)的變量

  • example 包含一對 label 和 feature,用來訓練模型

  • Training

    向模型中加入 example,模型根據(jù) example 自我修改feature 和 example 關系的過程

  • Inference

    在模型訓練完后,根據(jù) feature 預測對應的 label值

  • 三種變量

    • A continuous variable 連續(xù)變量

      • any value is possible for the variable.

      • 連續(xù)變量是在任意兩個值之間具有無限個值的數(shù)值變量。連續(xù)變量可以是數(shù)值變量,也可以是日期/時間變量。例如,零件的長度,或者收到付款的日期和時間

      • 連續(xù)變量與離散變量的簡單區(qū)別方法:連續(xù)變量是一直疊加上去的,增長量可以劃分為固定的單位

    • discrete variable 離散變量

      • only take on a certain number of values. 只能是某些值

      • 離散變量是在任意兩個值之間具有可計數(shù)的值的數(shù)值變量。離散變量始終為數(shù)值變量。例如,客戶投訴數(shù)量或者瑕疵或缺陷數(shù)。

      • 是通過計數(shù)方式取得的

    • a categorical variable 分類變量

      • take on one of a limited and usually fixed number of possible values

      • 可以采用有限且通常固定數(shù)量的可能值之一的變量

      • 類別變量包含有限的類別數(shù)或可區(qū)分組數(shù)。類別數(shù)據(jù)可能不是邏輯順序。例如,類別變量包括性別、材料類型和付款方式。

        比如有關于天氣的變量:晴,陰,雨。只能是其中單獨一個,不存在介于兩種之間的,即不能又晴又

latex 輸入數(shù)學公式

  • 最大值、最小值函數(shù)等用\max、 \min輸入,不能直接寫max、min等

  • 將限制條件a<x<b放在max 正下方:

    ?

  • 上下標 ? ? a_{1} b^{2} ?

  • 除號 ? \frac{}{}

線性回歸

  • 回歸是根據(jù)數(shù)據(jù)確定兩種或兩種以上變量間相互依賴的定量關系的辦法

    線性回歸 使用最佳的擬合直線(也就是回歸線)在因變量(Y)和一個或多個自變量(X)之間建立一種關系

  • 訓練回歸模型是

    根據(jù)訓練數(shù)據(jù),找到最佳參數(shù)以最小化模擬結果和真實值之間的誤差的過程。

    然后用訓練好的模型預測目標值 target。

  • 線性回歸是有條件的

    • feature 矩陣滿秩
  • Simple Linear Regression 簡單線性回歸

    只有一個feature特征值

  • Multiple Linear Regression 多變量線性回歸

    有多個特征值

  • loss 函數(shù)或者 cost 函數(shù)

    • 預測值和實際值的誤差

    • 目標函數(shù)

      理想情況是所有點都落在直線上。

      如果 ? 的值最小時,擬合的效果最好

      訓練的結果是確定?、?的值,得到目標函數(shù)的最小值

      有兩種方法找到這條直線

      • 普通最小二乘法(OSL)

        分別對a和b求一階偏導:

        image
        image

        求導之后我們分別讓其等于0,得到當目標函數(shù)取最小值時的各參數(shù)值

        image
        • 手動實現(xiàn)

          <pre spellcheck="false" class="md-fences md-end-block md-fences-with-lineno ty-contain-cm modeLoaded" lang="python" cid="n111" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); font-size: 0.9em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-size: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-top-left-radius: 3px; border-top-right-radius: 3px; border-bottom-right-radius: 3px; border-bottom-left-radius: 3px; padding: 8px 4px 6px 0px; margin-bottom: 15px; margin-top: 15px; width: inherit; background-position: inherit inherit; background-repeat: inherit inherit;"> def classic_lstsqr(x_list, y_list):
          N = len(x_list)
          x_avg = sum(x_list)/N
          y_avg = sum(y_list)/N
          var_x, cov_xy = 0, 0
          for x,y in zip(x_list, y_list):
          temp = x - x_avg
          var_x += temp*2
          cov_xy += temp * (y - y_avg)
          slope = cov_xy / var_x
          y_interc = y_avg - slope
          x_avg
          return (slope, y_interc)</pre>

        • 梯度下降法

      類型變量處理

      • "Dummy Variables".

        Dummy 變量虛擬變量,也叫啞變量和離散特征編碼,可用來表示分類變量、非數(shù)量因素可能產生的影響。有時也稱為布爾指示變量。

        引入啞變量的目的是,將不能夠定量處理的變量量化,例如:職業(yè)、性別、季節(jié)

        根據(jù)這些因素的屬性類型,構造只取“0”或“1”的人工變量,通常稱為啞變量(dummy variables),記為D

        舉一個例子,假設變量“職業(yè)”的取值分別為:工人、農民、學生、企業(yè)職員、其他,5種選項,我們可以增加4個啞變量來代替“職業(yè)”這個變量,分別為D1(1=工人/0=非工人)、D2(1=農民/0=非農民)、D3(1=學生/0=非學生)、D4(1=企業(yè)職員/0=非企業(yè)職員),最后一個選項“其他”的信息已經(jīng)包含在這4個變量中了,所以不需要再增加一個D5(1=其他/0=非其他)了。這個過程就是引入啞變量的過程,其實在結合分析(conjoint analysis)中,就是利用啞變量來分析各個屬性的效用值的。

      • 如何處理

        • 離散特征的取值之間有大小的意義

          • 例如:尺寸(L、XL、XXL)

          • 處理函數(shù)map pandas.Series.map(dict)

          • 參數(shù) dict: 映射的字典類型

        • <pre spellcheck="false" class="md-fences md-end-block md-fences-with-lineno ty-contain-cm modeLoaded" lang="python" cid="n135" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); font-size: 0.9em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-size: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-top-left-radius: 3px; border-top-right-radius: 3px; border-bottom-right-radius: 3px; border-bottom-left-radius: 3px; padding: 8px 4px 6px 0px; margin-bottom: 15px; margin-top: 0px; width: inherit; background-position: inherit inherit; background-repeat: inherit inherit;"> """
          博士后 Post-Doc
          博士 Doctorate
          碩士 Master's Degree
          學士 Bachelor's Degree
          副學士 Associate's Degree
          專業(yè)院校 Some College
          職業(yè)學校 Trade School
          高中 High School
          小學 Grade School
          """
          educationLevelDict = {
          'Post-Doc': 9,
          'Doctorate': 8,
          'Master's Degree': 7,
          'Bachelor's Degree': 6,
          'Associate's Degree': 5,
          'Some College': 4,
          'Trade School': 3,
          'High School': 2,
          'Grade School': 1
          }

          data['Education Level Map'] = data[
          'Education Level'
          ].map(
          educationLevelDict
          )
          ?</pre>

        • 字典是另一種可變容器模型,且可存儲任意類型對象。

          字典的每個鍵值 key=>value 對用冒號 : 分割,每個鍵值對之間用逗號 , 分割,整個字典包括在花括號 {} 中 ,格式如下所示

          <pre spellcheck="false" class="md-fences md-end-block md-fences-with-lineno ty-contain-cm modeLoaded" lang="" cid="n139" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); font-size: 0.9em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-size: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-top-left-radius: 3px; border-top-right-radius: 3px; border-bottom-right-radius: 3px; border-bottom-left-radius: 3px; padding: 8px 4px 6px 0px; margin-bottom: 15px; margin-top: 15px; width: inherit; background-position: inherit inherit; background-repeat: inherit inherit;"> d = {key1 : value1, key2 : value2 }</pre>

          • 鍵一般是唯一的,如果重復最后的一個鍵值對會替換前面的,值不需要唯一。

            <pre spellcheck="false" class="md-fences md-end-block md-fences-with-lineno ty-contain-cm modeLoaded" lang="" cid="n143" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); font-size: 0.9em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-size: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-top-left-radius: 3px; border-top-right-radius: 3px; border-bottom-right-radius: 3px; border-bottom-left-radius: 3px; padding: 8px 4px 6px 0px; margin-bottom: 15px; margin-top: 15px; width: inherit; background-position: inherit inherit; background-repeat: inherit inherit;"> dict = {'a': 1, 'b': 2, 'b': '3'}</pre>

          • 訪問字典里的值

            把相應的鍵放入方括弧

            <pre spellcheck="false" class="md-fences md-end-block md-fences-with-lineno ty-contain-cm modeLoaded" lang="" cid="n147" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); font-size: 0.9em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-size: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-top-left-radius: 3px; border-top-right-radius: 3px; border-bottom-right-radius: 3px; border-bottom-left-radius: 3px; padding: 8px 4px 6px 0px; margin-bottom: 15px; margin-top: 15px; width: inherit; background-position: inherit inherit; background-repeat: inherit inherit;"> dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
            print( "dict['Name']: ", dict['Name'])
            print ("dict['Age']: ", dict['Age'])</pre>

          • 修改字典

            向字典添加新內容的方法是增加新的鍵/值對,修改或刪除已有鍵/值對如下實例:

            <pre spellcheck="false" class="md-fences md-end-block md-fences-with-lineno ty-contain-cm modeLoaded" lang="" cid="n151" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); font-size: 0.9em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-size: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-top-left-radius: 3px; border-top-right-radius: 3px; border-bottom-right-radius: 3px; border-bottom-left-radius: 3px; padding: 8px 4px 6px 0px; margin-bottom: 15px; margin-top: 15px; width: inherit; background-position: inherit inherit; background-repeat: inherit inherit;"> dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
            dict['Age'] = 8; # update existing entry
            dict['School'] = "DPS School"; # Add new entry
            print ("dict['Age']: ", dict['Age'])
            print( "dict['School']: ", dict['School'])</pre>

          • 刪除字典

            用del命令能刪單一的元素,,

            dict.clear()能清空字典。

            <pre spellcheck="false" class="md-fences md-end-block md-fences-with-lineno ty-contain-cm modeLoaded" lang="python" cid="n156" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); font-size: 0.9em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-size: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-top-left-radius: 3px; border-top-right-radius: 3px; border-bottom-right-radius: 3px; border-bottom-left-radius: 3px; padding: 8px 4px 6px 0px; margin-bottom: 15px; margin-top: 15px; width: inherit; background-position: inherit inherit; background-repeat: inherit inherit;"> dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
            del dict['Name']; # 刪除鍵是'Name'的條目
            dict.clear(); # 清空詞典所有條目
            del dict ; # 刪除詞典
            print ("dict['Age']: ", dict['Age'])
            print ("dict['School']: ", dict['School'])</pre>

          • np.where() 函數(shù)處理二元的類型變量

            • e.g. np.where(wdbc.Diagnosis == 'B', 1, 0)
          • 離散特征的取值之間沒有大小的意義

            • 顏色(Red,Blue,Green)

            • get_dummies(data,prefix=None,prefix_sep="_",dummy_na=False,columns=None,drop_first=False)

              ① data 要處理的DataFrame ② columns 要處理的列名,如果不指定該列,那么默認處理所有列 ③ drop_first 是否從備選項中刪除第一個,建模的時候為避免多重共線性

            • 多重共線性是指線性回歸模型中的解釋變量之間由于存在精確相關關系或高度相關關系而使模型估計失真或難以估計準確

            • <pre spellcheck="false" class="md-fences md-end-block md-fences-with-lineno ty-contain-cm modeLoaded" lang="python" cid="n168" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); font-size: 0.9em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-size: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-top-left-radius: 3px; border-top-right-radius: 3px; border-bottom-right-radius: 3px; border-bottom-left-radius: 3px; padding: 8px 4px 6px 0px; margin-bottom: 15px; margin-top: 0px; width: inherit; background-position: inherit inherit; background-repeat: inherit inherit;"> import pandas as pd
              import numpy as np
              ?
              s = pd.Series(list('YNNY'))
              print(s)
              print(pd.get_dummies(s).Y)
              ?
              a = np.where(s == 'Y', 1, 0)
              print(a)</pre>

        使用工具庫完成線性回歸

        • 選擇 feature

          • 選擇哪個 feature 能更好的預測 label 的值

            • 每個 feature與依賴變量的散點圖

            • 計算自變量和從屬變量之間的線性相關性

              • 相關分數(shù)僅反映變量之間的線性相關性 。如果存在強的非線性關系,則可能會錯過。
          • 計算相關分數(shù)

            • 皮爾遜相關系數(shù)

              定義式

              [1]
              image

              Cov(X,Y)為X與Y的協(xié)方差,Var[X]為X的方差,Var[Y]為Y的方差

            • 性質

              (1)
              image

              (2)
              image

              的充要條件是,存在常數(shù)a,b,使得
              image
            • 相關系數(shù)定量地刻畫了 X 和 Y的相關程度,

              image

              越大,相關程度越大;

              image

              對應相關程度最低;

            • X 和Y 完全相關的含義是在概率為1的意義下存在線性關系,于是

              image

              是一個可以表征X 和Y 之間線性關系緊密程度的量。

              image

              較大時,通常說X 和Y相關程度較好;

              image

              較小時,通常說X 和Y相關程度較差; 當X和Y不相關,通常認為X和Y之間不存在線性關系,但并不能排除X和Y之間可能存在其他關系。

          • dateframe.corr()

            • 默認是 pearson 方法

            • 返回各列之間的相關分數(shù)

            • 絕對值越大的相關性越好

        • 畫散點圖

          • plt.scatter(x,y,s=None, c=None, marker=None, cmap=None, norm=None, vmin=None, vmax=None, alpha=None, linewidths=None, verts=None, edgecolors=None, hold=None, data=None)

          • s 各點的大小,可以是一個數(shù)字,如果 傳入一個長度和 x 相同的 List ,則規(guī)定每個點的大小

          • c 個點的顏色, 可以是一個代表顏色的字符,如果 傳入一個長度和 x 相同的 List 規(guī)定每個點的顏色

          • marker 每個點的形狀

          • alpha 透明度

        • 調用工具庫

          • import statsmodels.api as sm

            • 數(shù)學模型庫

            • sm.OLS 線性回歸模型最小二乘法

          • from sklearn.linear_model import LinearRegression

          • 修改feature 矩陣,在 feature 前加一列1

            • statsmodels.tools.add_constant(data, prepend=True, has_constant='skip')

              data (array-like) – data is the column-ordered design matrix

              prepend (bool) – If true, the constant is in the first column. Else the constant is appended (last column).

            • 為什么要用add_constant

              • 因為sm.OLS 默認模型是沒有截距 intercept 的

                而我們的 feature 里是包括 截距 ? 和 斜率 ? 的,如果只有一個 feature,最后擬合的結果也是只有一個斜率?

              • 數(shù)學證明在網(wǎng)頁

                常數(shù)的加法可以通過將X與秩n的n×n矩陣Z相乘來表示。 這是通過獲取單位矩陣并將常量(例如x = 2(但x不能為-1))添加到與截距相關的列i對應的行來完成的

              • 為什么不在每個 x 的值上加個值

                原因是可能這個值就將矩陣中的某個數(shù)變成0,失去了相關性

          • 建立模型

            model = sm.OLS( label, feature )

            Ordinary least squares

            建立線性回歸模型,第一個數(shù)據(jù)是待預測的變量,第二個數(shù)據(jù)是建模依據(jù)的變量 ? 返回模型對象

          • 訓練模型

            result = model.fit( )

            返回results對象

          • 得到建模參數(shù)

            results.params

            返回建模參數(shù) {? ? }

          • 得到模型數(shù)據(jù)摘要

            results.summary()

            摘要將顯示系數(shù)值(β)和統(tǒng)計量,如R平方和p值等。

          • 預target值

            results.predict(params)

            輸入feature矩陣,這里需要第一列加1

            返回預測的 label 值

          • 使用statsmodels公式接口來定義模型( R 語言風格)

            • formular = 'str'

            • “~” 左邊是feature 右邊是 label

            • 這里 feature 不用加上一列1

          • 畫出回歸函數(shù)圖

            • np.linspace( start , stop, num)

              • 生成等間距的數(shù)字 list

              • start 起點

              • stop 終點

              • num 數(shù)字個數(shù)

          • 模型分析

            • Goodness of fit 模型適合度·

              • the Root Mean Square Error(RMSE) 均方根誤差

                • 測量總誤差(每個訓練數(shù)據(jù)點的回歸線和實際因變量值之間的距離,對所有訓練數(shù)據(jù)點求和)。
              • R 方

                • R平方值是模型解釋的方差量的度量。

                • R 方越大越好,值為1表示該模型完全解釋了所有方差。 但是,在大多數(shù)情況下,這將被視為過度擬合。

                • R2為回歸平方和與總離差平方和的比值,這一比值越大,表示總離差平方和中可以由回歸平方和解釋的比例越大,模型越精確,回歸效果越顯著

            • 變量的影響

              • p值是指在一個概率模型中,統(tǒng)計摘要(如兩組樣本均值差)與實際觀測數(shù)據(jù)相同,或甚至更大這一事件發(fā)生的概率 。 換言之,是檢驗假設零假設成立或表現(xiàn)更嚴重的可能性。p值若與選定顯著性水平(0.05或0.01)相比更小,則零假設會被否定而不可接受。

                • 臨界值一般是0.05

                • p<0.05說明這個因素對結果有影響,保留此因素,p>0.05說明這個因素對結果無影響

                • 回歸里出現(xiàn)的p值也是針對于假設檢驗來說的。

                  假設你的回歸模型是Y=aX1+bX2+c.Y=aX1+bX2+c.

                  aa所對應的假設檢驗中,零假設是在bb和cc都是正確值得情況下a=0a=0,對立假設是在bb和cc都正確的情況下a≠0a≠0。這一般都是采用雙側t檢驗。aa所對應的p值就是這個假設檢驗的p值。

              • 系數(shù)值:系數(shù)/參數(shù)值的大小。 該值越大,它對轉移因變量值的貢獻就越大。 較大的系數(shù)值意味著該變量具有實際意義。

            • 預測

              • 根據(jù)擬合的模型對輸入的參數(shù)的結果進行預測

              • 每行預測值之前也要加一列1

              • formula 方法

                • 最簡單的方法是使用字典列表

                • 或者是 dataframe

          • Newton-Raphson方法

            • 查找函數(shù)根的算法

            • np.inf 正無窮大的浮點數(shù)

            • 學這個的原因,

              • 我們回歸要得到的結果是要讓 loss 函數(shù)最小,

              • 首先我們要對 loss 函數(shù)求導

              • 然后求讓導數(shù)為0 時,對應的極值點,

                就是求 loss 函數(shù)對應的導函數(shù)為0 的根

              • 很多時候,優(yōu)化函數(shù)g(x)可以歸結為g'(x)= 0的根找到。

?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容