{ "cells": [ { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": true }, "outputs": [], "source": [ "import tensorflow as tf\n", "import numpy as np\n", "from tensorflow.examples.tutorials.mnist import input_data" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "def init_weights(shape):\n", " return tf.Variable(tf.random_normal(shape, stddev=0.01))\n", "\n", "def model(X, w):\n", " return tf.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\n", "\n", "mnist = input_data.read_data_sets(\"MNIST_data/\", one_hot=True)\n", "trX, trY, teX, teY = mnist.train.images, mnist.train.labels, mnist.test.images, mnist.test.labels" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "collapsed": false }, "outputs": [], "source": [ "X = tf.placeholder(\"float\", [None, 784]) # create symbolic variables\n", "Y = tf.placeholder(\"float\", [None, 10])\n", "\n", "w = init_weights([784, 10]) # like in linear regression, we need a shared variable weight matrix for logistic regression\n", "\n", "py_x = model(X, w)\n", "\n", "cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=py_x, labels=Y)) # compute mean cross entropy (softmax is applied internally)\n", "train_op = tf.train.GradientDescentOptimizer(0.05).minimize(cost) # construct optimizer\n", "predict_op = tf.argmax(py_x, 1) # at predict time, evaluate the argmax of the logistic regression" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# Launch the graph in a session\n", "with tf.Session() as sess:\n", " # you need to initialize all variables\n", " tf.global_variables_initializer().run()\n", "\n", " for i in range(100):\n", " for start, end in zip(range(0, len(trX), 128), range(128, len(trX)+1, 128)):\n", " sess.run(train_op, feed_dict={X: trX[start:end], Y: trY[start:end]})\n", " print(i, np.mean(np.argmax(teY, axis=1) ==\n", " sess.run(predict_op, feed_dict={X: teX})))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 2", "language": "python", "name": "python2" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 2 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython2", "version": "2.7.13" } }, "nbformat": 4, "nbformat_minor": 1 }