機器學習-非線性迴歸(Logistic Regression)及應用

1. 機率python

   1.1 定義:機率(Probability):對一件事情發生的可能性的衡量。dom

   1.2 範圍:0 <= P <= 1函數

   1.3 計算方法:學習

        1.3.1 根據我的置信測試

        1.3.2 根據歷史數據spa

        1.3.3 根據模擬數據3d

    1.4 條件機率:orm

                                           

 

2. Logistic Regression(邏輯迴歸)blog

   2.1 列子:模擬癌症腫瘤是良性仍是惡性utf-8

            

 

                            h(x) > 0.5

 

 

         

                                 h(x) > 0.2

    2.2 基本模型

          測試數據爲:

          要學習的參數爲:

                               

           向量表示:

                                

 

 

           因爲y取值在[0,1]之間,全部須要處理二值數據,引入Sigmoid函數來使得曲線平滑化

                               

                       

          預測函數:

                      

 

 

          用機率表示:

          正例(y = 1):

                        

 

           反例(y = 0):       

                            

       2.3 Cost函數

              線性迴歸:

         

                                           (預測值-實例值)

                                                                 (相似於線性模型)

                在簡單線性模型中找到合適的使得上式最小

                Logistic regression:

                Cost函數:

               

                                               上式合併能夠獲得下面的式子

                     目標:找到合適的使得上式最小

             2.4 解法:梯度降低法(gradient decent)

                               

                                                       

                                                   

                                                            爲學習率

                      更新法則:

                                      

                                                                                   爲學習率

                               同時對全部的進行更新,重複更新知道收斂

 

# -*- coding:utf-8 -*-

import numpy as np
import random

#產生模擬數據 numPoints實例個數  bias偏好值 variance方差
def genData(numPoints, bias, variance):
    x = np.zeros(shape=(numPoints, 2))
    y = np.zeros(shape=(numPoints)) #1行 如:1x100
    for i in range(0, numPoints):#每一行循環
        x[i][0] = 0 #每行第一列等於1
        x[i][1] = i #每行第二列等於i
        y[i] = (i + bias) + random.uniform(0, 1) + variance
    return x,y


#梯度降低
def gradientDescent(x, y, theta, alpha, m, numIterations): #alpha學習率 m實例個數 numIterations更新次數
    xTran = np.transpose(x)#轉置
    for i in range(numIterations):
        hypothesis = np.dot(x, theta)#估計值
        loss = hypothesis - y#估計值-實際值
        cost = np.sum(loss**2)/(2*m)#這裏的定義最簡單的cost函數和實際定義有出入
        gradient = np.dot(xTran,loss)/m#更新量
        theta = theta - alpha*gradient
        print("Iteration %d | cost: %f" %(i, cost))
    return theta

#測試
x, y = genData(100, 25, 10)
# print("x:")
# print(x)
# print("y:")
# print(y)
#
m, n = np.shape(x)
n_y = np.shape(y)
#
# print("x_shape:" ,str(m)," ",str(n))
# print("y_shape:" , str(n_y))

numIterations = 100000
alpha = 0.0005
theta = np.ones(n)
theta = gradientDescent(x, y, theta, alpha, m, numIterations)
print(theta)
相關文章
相關標籤/搜索