python theano库学习(1)

import theano
import theano.tensor as T
rng = numpy.random
N = 400
feats = 784
//D[0]是一个服从正态分布的400x784的随机矩阵。D[1]是取值为01400x1的随机矩阵
//D[0]是作为训练数据,每一行数据就是一次输入。D[1]是对应D[0]的标签数据
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,b,w为1x784的矩阵
w = theano.shared(rng.randn(feats), name="w")
b = theano.shared(0., name="b")
print("Initial model:")
print(w.get_value())
print(b.get_value())
# Construct Theano expression graph
//x*wT,p_1为一个列向量,里面的元素为取值01的概率
p_1 = 1 / (1 + T.exp(-T.dot(x, w) - b)) # Probability that target = 1
//若若p_1中的元素>0.5,则预测该类数据归属于类1,否则归为类0
prediction = p_1 > 0.5 # The prediction thresholded
//xent.mean()就是我们常用的平均代价函数。xent只是一个代价列向量矩阵
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)
# 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)
# Train
for i in range(training_steps):
    pred, err = train(D[0], D[1])
print("Final model:")
//训练结束,更新w,b的值;get_value函数是为了更新shared变量矩阵
print(w.get_value())
print(b.get_value())
print("target values for D:")
print(D[1])
print("prediction on D:")
//预测D[0]矩阵中每一行数据所属的类
print(predict(D[0]))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值