1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
| import numpy import numpy as np 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
x = T.dmatrix("x") y = T.dvector("y")
w = theano.shared(rng.randn(feats), name="w")
b = theano.shared(0., name="b")
print("Initial model:") print(w.get_value().shape) print(b.get_value().shape)
p_1 = 1 / (1 + T.exp(-T.dot(x, w) - b)) prediction = p_1 > 0.5 xent = -y * T.log(p_1) - (1-y) * T.log(1-p_1) cost = xent.mean() + 0.01 * (w ** 2).sum() gw, gb = T.grad(cost, [w, b])
updates = [(w, w - 0.1 * gw),(b, b - 0.1 * gb)]
train = theano.function( inputs=[x,y], outputs=[prediction, xent,cost], updates= updates )
predict = theano.function(inputs=[x], outputs=prediction)
for i in range(training_steps): pred, xcent,cost_t = train(D[0], D[1])
prediction = predict(D[0])
accuracy = 100* np.mean( np.equal(prediction,D[1]) )
print("Final model:") print(w.get_value().shape) print(b.get_value().shape)
print "\nCost = ",cost_t print "Accuracy = ", accuracy,"%"
print("\ntarget values for D:")
print("prediction on D:")
|