Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLogisticRegression.py
More file actions
Latest commit
36 lines (25 loc) · 1.61 KB
/
Copy pathLogisticRegression.py
File metadata and controls
36 lines (25 loc) · 1.61 KB
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
# from https://github.com/nlintz/TensorFlow-Tutorials/blob/master/02_logistic_regression.py
importtensorflowastf
importnumpyasnp
fromtensorflow.examples.tutorials.mnistimportinput_data
definit_weights(shape):
returntf.Variable(tf.random_normal(shape, stddev=0.01))
defmodel(X, w):
returntf.matmul(X, w) # notice we use the same model as linear regression, this is because there is a baked in cost function which performs softmax and cross entropy
mnist=input_data.read_data_sets("MNIST_data/", one_hot=True)
trX, trY, teX, teY=mnist.train.images, mnist.train.labels, mnist.test.images, mnist.test.labels
X=tf.placeholder("float", [None, 784]) # create symbolic variables
Y=tf.placeholder("float", [None, 10])
w=init_weights([784, 10]) # like in linear regression, we need a shared variable weight matrix for logistic regression
py_x=model(X, w)
cost=tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=py_x, labels=Y)) # compute mean cross entropy (softmax is applied internally)
train_op=tf.train.GradientDescentOptimizer(0.05).minimize(cost) # construct optimizer
predict_op=tf.argmax(py_x, 1) # at predict time, evaluate the argmax of the logistic regression
# Launch the graph in a session
withtf.Session() assess:
# you need to initialize all variables
tf.global_variables_initializer().run()
foriinrange(100):
forstart, endinzip(range(0, len(trX), 128), range(128, len(trX)+1, 128)):
sess.run(train_op, feed_dict={X: trX[start:end], Y: trY[start:end]})
print(i, np.mean(np.argmax(teY, axis=1) ==sess.run(predict_op, feed_dict={X: teX})))