Last active
March 1, 2017 00:51
-
-
Save finlay-liu/7e318cab8d2a3b2cf380833711c55089 to your computer and use it in GitHub Desktop.
tensorflow with keras example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import tensorflow as tf | |
from keras.metrics import categorical_accuracy as accuracy | |
sess = tf.Session() | |
from keras import backend as K | |
K.set_session(sess) | |
img = tf.placeholder(tf.float32, shape=(None, 784)) | |
from keras.layers import Dense | |
# Keras layers can be called on TensorFlow tensors: | |
x = Dense(128, activation='relu')(img) # fully-connected layer with 128 units and ReLU activation | |
x = Dense(128, activation='relu')(x) | |
preds = Dense(10, activation='softmax')(x) # output layer with 10 units and a softmax activation | |
labels = tf.placeholder(tf.float32, shape=(None, 10)) | |
from keras.objectives import categorical_crossentropy | |
loss = tf.reduce_mean(categorical_crossentropy(labels, preds)) | |
from tensorflow.examples.tutorials.mnist import input_data | |
mnist_data = input_data.read_data_sets('MNIST_data', one_hot=True) | |
acc_value = accuracy(labels, preds) | |
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(loss) | |
sess.run(tf.global_variables_initializer()) | |
with sess.as_default(): | |
for i in range(10000): | |
batch = mnist_data.train.next_batch(50) | |
train_step.run(feed_dict={img: batch[0], | |
labels: batch[1]}) | |
print acc_value.eval(feed_dict={img: mnist_data.test.images, | |
labels: mnist_data.test.labels}) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment