Created
November 2, 2018 09:01
-
-
Save kezunlin/75c76cb68e9b97a4f5a052baf33e8794 to your computer and use it in GitHub Desktop.
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
#!/usr/bin/python3 | |
# http://www.tensorfly.cn/tfdoc/tutorials/mnist_beginners.html | |
# http://www.tensorfly.cn/tfdoc/tutorials/mnist_pros.html | |
""" | |
import numpy as np | |
a = [1,0,0,0,0] | |
b = [0,1,0,0,0] | |
c = [0,0,1,0,0] | |
data = [a,b,c] | |
data2 = [a,b,a] | |
print(np.argmax(a)) # 1 dim---> 0 dim | |
print(np.argmax(b)) # 1 dim---> 0 dim | |
print(np.argmax(c)) # 1 dim---> 0 dim | |
#print(np.argmax(data,0)) # 2 dim: matrix---> 1 dim: vector | |
#print(np.argmax(data2,0)) | |
print(np.argmax(data,1)) # 2 dim: matrix---> 1 dim: vector | |
print(np.argmax(data2,1)) | |
print( np.equal(np.argmax(data,1),np.argmax(data2,1)) ) # 1 vector | |
0 | |
1 | |
2 | |
[0 1 2] | |
[0 1 0] | |
[ True True False] | |
""" | |
import os | |
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' | |
# 默认为0:输出所有log信息 | |
# 设置为1:进一步屏蔽INFO信息 | |
# 设置为2:进一步屏蔽WARNING信息 | |
# 设置为3:进一步屏蔽ERROR信息 | |
import tensorflow as tf | |
import tensorflow.examples.tutorials.mnist.input_data as input_data | |
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) | |
x = tf.placeholder("float", [None, 784]) | |
y_ = tf.placeholder("float", [None,10]) # real results | |
W = tf.Variable(tf.zeros([784,10])) | |
b = tf.Variable(tf.zeros([10])) | |
y = tf.nn.softmax(tf.matmul(x,W) + b) # predicted results | |
cross_entropy = -tf.reduce_sum(y_*tf.log(y)) # cost: 2 matrix ---> scalar | |
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy) | |
init = tf.global_variables_initializer() | |
config_proto = tf.ConfigProto() | |
config_proto.gpu_options.allow_growth = True # allow gpu dynamic grow | |
sess = tf.Session(config=config_proto) | |
sess.run(init) # initial all variables to default 0 | |
with tf.device("/gpu:0"): | |
for i in range(1000): | |
batch_xs, batch_ys = mnist.train.next_batch(100) | |
sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys}) | |
correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1)) # [True,True,False] | |
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float")) # [1,1,0] ---> 0.67 | |
print("") | |
print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels})) # we got 90.88% | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment