#!/usr/bin/env python#Coding=utf-8
#这个例子相对来讲比较简单可以作为训练编程的模板
ImportNumPyImportTheanoImportTheano.tensor as Trng=Numpy.randomn= 400Feats= 784D= (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= Theano.shared (Rng.randn (feats), name="W") b= theano.shared (0., name="b")Print "Initial Model:"PrintW.get_value (), B.get_value ()#Construct Theano Expression GraphP_1 = 1/(1 + t.exp (-t.dot (x, W)-B))#probability that target = 1Prediction = p_1 > 0.5#The prediction thresholdedXent =-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 minimizeGW, GB = T.grad (Cost, [w, b])#Compute The gradient of the cost #(We shall return to this in a)#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)#Train forIinchRange (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])
#!/usr/bin/env python
# Coding=utf-8
Import NumPy
Import Theano
Import Theano.tensor as T
RNG = Numpy.random
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:"
Print W.get_value (), B.get_value ()
# Construct Theano Expression graph
P_1 = 1/(1 + t.exp (-t.dot (x, W)-B)) # probability that target = 1
Prediction = p_1 > 0.5 # The Prediction 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)
# 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:"
Print W.get_value (), B.get_value ()
Print "target values for D:", d[1]
Print "Prediction on D:", Predict (d[0])
[Theano] Getting started-a simple example of training