1. 程式人生 > >theano學習之分類學習

theano學習之分類學習

程式碼:
from __future__ import print_function
import numpy as np
import theano
import theano.tensor as T

#該函式功能用來計算準確率
def compute_accuracy(y_target, y_predict):
    correct_prediction = np.equal(y_predict, y_target)
    accuracy = np.sum(correct_prediction)/len(correct_prediction)
    return accuracy


# generate a dataset: D = (input_values, target_class)
#用 randn 隨機生成資料集。 D 中的 input_values 是 400 個樣本,784 個feature。
# target_class 是有兩類,0 和 1。 要做的是,用神經網路訓練資料學習哪些輸入對應 0,哪些對應1
# 生成隨機數: D = (input_values, target_class)
rng = np.random
N = 400                                   # training sample size
feats = 784                               # number of input variables
D = (rng.randn(N, feats), rng.randint(size=N, low=0, high=2))#D[0]表特徵,D[1]表標籤
print(D[0])
print(D[1])

#定義x,y容器,相當於TensorFlow中的placeholder,用來存資料
x = T.dmatrix("x")
y = T.dvector("y")

#初始化權重和偏置
W = theano.shared(rng.randn(feats), name="w")
b = theano.shared(0., name="b")


#定義啟用函式和交叉熵
p_1 = T.nnet.sigmoid(T.dot(x, W) + b)    #啟用函式
prediction = p_1  > 0.5                  # The prediction thresholded閾值,呼叫了p_1函式,預測當前權重下的值,這個是個布林值,ture或false
xent = -y * T.log(p_1) - (1-y) * T.log(1-p_1) # 交叉熵
# or
# xent = T.nnet.binary_crossentropy(p_1, y) # this is provided by theano
cost = xent.mean() + 0.01 * (W ** 2).sum()#正則化後的代價函式(L2正則化)
gW, gb = T.grad(cost, [W, b])             # 梯度


#啟用網路
learning_rate = 0.1
train = theano.function(
          inputs=[x, y],
          outputs=[prediction, xent.mean()],
          updates=((W, W - learning_rate * gW), (b, b - learning_rate * gb)))
predict = theano.function(inputs=[x], outputs=prediction)

#訓練模型
for i in range(500):
    pred, err = train(D[0], D[1])#D[0]指特徵所有資料,D[1]指標籤所有資料
    if i % 50 == 0:
        print('cost:', err)
        print("accuracy:", compute_accuracy(D[1], predict(D[0])))

print("target values for D:")
print(D[1])
print("prediction on D:")
print(predict(D[0]))

來源