Theano學(xué)習(xí)筆記(二)――邏輯回歸函數(shù)解析
來源:程序員人生 發(fā)布時間:2014-09-02 17:23:07 閱讀次數(shù):3184次
有了前面的準(zhǔn)備,可以用Theano實現(xiàn)一個邏輯回歸程序,邏輯回歸是典型的有監(jiān)督學(xué)習(xí)。
為了形象,這里我們假設(shè)分類任務(wù)是區(qū)分人與狗的照片。
首先是生成隨機數(shù)對象
importnumpy
importtheano
importtheano.tensor as T
rng= numpy.random
數(shù)據(jù)初始化
有400張照片,這些照片不是人的就是狗的。
每張照片是28*28=784的維度。
D[0]是訓(xùn)練集,是個400*784的矩陣,每一行都是一張照片。
D[1]是每張照片對應(yīng)的標(biāo)簽,用來記錄這張照片是人還是狗。
training_steps是迭代上限。
N= 400
feats= 784
D= (rng.randn(N, feats), rng.randint(size=N, low=0, high=2))
training_steps= 10000
#Declare Theano symbolic variables
x= T.matrix("x")
y= T.vector("y")
w= theano.shared(rng.randn(feats), name="w")
b= theano.shared(0., name="b")
print"Initial model:"
printw.get_value(), b.get_value()
x是輸入的訓(xùn)練集,是個矩陣,把D[0]賦值給它。
y是標(biāo)簽,是個列向量,400個樣本所以有400維。把D[1]賦給它。
w是權(quán)重列向量,維數(shù)為圖像的尺寸784維。
b是偏倚項向量,初始值都是0,這里沒寫成向量是因為之后要廣播形式。
#Construct Theano expression graph
p_1= 1 / (1 + T.exp(-T.dot(x, w) - b)) #Probability that target = 1
prediction= p_1 > 0.5 # Theprediction thresholded
xent= -y * T.log(p_1) - (1-y) * T.log(1-p_1) # Cross-entropy loss function
cost= xent.mean() + 0.01 * (w ** 2).sum()# The cost to minimize
gw,gb = T.grad(cost, [w, b]) #Compute the gradient of the cost
# (we shall return to this in a
#following section of this tutorial)
這里是函數(shù)的主干部分,涉及到3個公式
1.判定函數(shù)
 = frac{1}{{I + {e^{ - { heta ^T}X}}}})
2.代價函數(shù)
,y}
ight) = left{ egin{array}{r}egin{array}{*{20}{c}}{ - log left( {{h_ heta }left( x
ight)}
ight)}&{egin{array}{*{20}{c}}{if}&{y = 1}end{array}}end{array}egin{array}{*{20}{c}}{ - log left( {1 - {h_ heta }left( x
ight)}
ight)}&{egin{array}{*{20}{c}}{if}&{y = 0}end{array}}end{array}end{array}
ight.)
3.總目標(biāo)函數(shù)
 = - frac{1}{m}left[ {sumlimits_{i = 1}^m {left( {{y^{left( i
ight)}}log {h_ heta }left( {{x^{left( i
ight)}}}
ight) + left( {1 - {y^{left( i
ight)}}}
ight)log left( {1 - {h_ heta }left( {{x^{left( i
ight)}}}
ight)}
ight)}
ight)} }
ight] + frac{lambda }{2}sumlimits_{i = 1}^m {W_i^2} )
第二項是權(quán)重衰減項,減小權(quán)重的幅度,用來防止過擬合的。
#Compile
train= theano.function(
inputs=[x,y],
outputs=[prediction, xent],
updates=((w, w - 0.1 * gw), (b, b -0.1 * gb)))
predict= theano.function(inputs=[x], outputs=prediction)
構(gòu)造預(yù)測和訓(xùn)練函數(shù)。
#Train
fori in range(training_steps):
pred,err = train(D[0], D[1])
print"Final model:"
printw.get_value(), b.get_value()
print"target values for D:", D[1]
print"prediction on D:", predict(D[0])
這里算過之后發(fā)現(xiàn),經(jīng)過10000次訓(xùn)練,預(yù)測結(jié)果與標(biāo)簽已經(jīng)完全相同了。
歡迎參與討論并關(guān)注本博客和微博以及知乎個人主頁后續(xù)內(nèi)容繼續(xù)更新哦~
轉(zhuǎn)載請您尊重作者的勞動,完整保留上述文字以及文章鏈接,謝謝您的支持!
生活不易,碼農(nóng)辛苦
如果您覺得本網(wǎng)站對您的學(xué)習(xí)有所幫助,可以手機掃描二維碼進(jìn)行捐贈