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]))

来源

猜你喜欢

转载自blog.csdn.net/weixin_40849273/article/details/84617223