非线性回归(Non-linear Regression)
生活随笔
收集整理的這篇文章主要介紹了
非线性回归(Non-linear Regression)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
非線性回歸應用(Logistic Regression Application)
import numpy as np import random# 一個函數為梯度下降的算法 def GradientDescent(x,y,theta,alpha,m,numInterations):# m denotes the number of examples here, not the number of features'''x:實例;y:分類標簽theta:要學習的參數θalpha:learning ratem:更新法則公式中實例的個數,對應矩陣的維數[]numInterations:使用此方法循環訓練更新的次數'''xTrans = x.transpose() #轉置x便于后面運算for i in range(0,numInterations):hypothesis = np.dot(x,theta) #這里為什么要放在for循環里面,并不受循環影響? #for循環次數即為更新次數loss = hypothesis - y #hypothesis其實就是y_hat,這里loss就等于y_hat減去y(實際)# avg cost per example (the 2 in 2*m doesn't really matter here.# But to be consistent with the gradient, I include itcost = np.sum(loss**2)/(2*m)#這里的cost函數與課文中提到的cost函數不一樣,這里使用了一個簡單的cost便于計算'''cost:對精確度的衡量,每一次gradient都會減小'''print('Interation:%d|cost:%f'%(i,cost))# avg gradient per examplegradient = np.dot(xTrans,loss)/m #每一次的下降梯度值,除以m:取平均# updatatheta = theta-alpha*gradient #即更新法則的公式:θ=θ-α∑(h(x)-y)xreturn theta# 一個函數用來產生數據用來測試擬合 def genData(numPoints,bias,variance):'''numPoints:實例的行數(矩陣形式,每一行對應一對實例)bias:生成y時產生一個偏差值variance:方差'''x = np.zeros(shape=(numPoints,2)) #numPoints行,2列的矩陣y = np.zeros(shape=(numPoints))#basically a staight linefor i in range(0,numPoints):# bias featurex[i][0] = 1x[i][1] = i# target variabley[i] = (i+bias)+random.uniform(0,1)*variance #random.uniform(0,1)同random.random()產生0~1隨機數return x,y# generate 100 columns with a bias of 25 and 10 variance as a bit of noise x,y = genData(100,25,10)#前面函數返回了兩個變量x,y此處可以任意取兩個變量按偏移量賦值給返回的x和y # print(x) # print(y) m,n = np.shape(x) #x的行數賦值給m,列數賦值為n a = np.shape(y) #y只有一列不會返回列的數值,會返回行的數值 # print(m,n) #(100行,2列) # print(a) #(100行,1列)numInterations = 100000 alpha = 0.0005 #取0~1,比較好的算法會設置開始的alpha數值較大后期數值較小 theta = np.ones(n) # 初始化θ:[1. 1.] 為什么設置為1? theta = GradientDescent(x,y,theta,alpha,m,numInterations) print(theta) #約為[30 1]# 得出的theta就可以用于對新實例的計算和預測 #回歸算法和神經網絡中都會用到此梯度下降的方法總結
以上是生活随笔為你收集整理的非线性回归(Non-linear Regression)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: oracle忽略除数为0,ora-014
- 下一篇: 华三交换机ping大包命令_华三交换机常