python theano库学习(1)

来源:互联网 发布:今天电信网络怎么了 编辑:程序博客网 时间:2024/05/16 04:34
import theanoimport theano.tensor as Trng = numpy.randomN = 400feats = 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 variablesx = 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,否则归为类0prediction = 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 functioncost = 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)# Compiletrain = 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)# Trainfor 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]))
0 0