# -*- coding: utf-8 -*-
"""
Created on Sun Jul 21 23:01:29 2019
@author: hm
"""
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
# 导入数据
mnist = input_data.read_data_sets("C:\\Users\\hm\\Desktop\\shuju", one_hot=True)
'''
如果不用one_hot编码,则会报错:
ValueError: Cannot feed value of shape (100,) for
Tensor 'Placeholder_21:0', which has shape '(?, 10)'
'''
'''
#分别是train test validation datasets的大小
print(mnist.train.images.shape,mnist.train.labels.shape)
print(mnist.test.images.shape,mnist.test.labels.shape)
print(mnist.validation.images.shape,mnist.validation.labels.shape)
'''
sess = tf.InteractiveSession()
x = tf.placeholder(tf.float32,[None,784])
W = tf.Variable(tf.zeros([784,10]))
b = tf.Variable(tf.zeros([10]))
y = tf.nn.softmax(tf.matmul(x,W) + b)
y_ = tf.placeholder(tf.float32,[None,10])
loss = tf.reduce_mean(-tf.reduce_sum(y_*tf.log(y),
reduction_indices=[1]))
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(loss)
tf.global_variables_initializer().run()
for i in range(1000):
batch_xs,batch_ys = mnist.train.next_batch(100) #每次读取100个数据
train_step.run({x:batch_xs,y_:batch_ys})
correct_prediction = tf.equal(tf.argmax(y,1),tf.arg_max(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
print(accuracy.eval({x:mnist.test.images,y_:mnist.test.labels}))
#输出0.9161
##查看训练好的权重
import numpy as np
np.set_printoptions(threshold=np.inf) #tensorflow 打印张量时,输出不完全,总有省略号怎么办
print(W.eval())
print(b.eval())
注意:
(1)训练数据先用placehloder()占位,但是要注意相应的shape
(2)如果不用one_hot编码,则会报错:
ValueError: Cannot feed value of shape (100,) for Tensor 'Placeholder_21:0', which has shape '(?, 10)'
(3)本文是最简单的Tensorflow实现的小demo,旨在于了解相应的模型构造和训练。
(4)查看训练好的权重:直接print相应的权重变量,本文是W,b
但是,打印张量时,输出不完全,总有省略号或者只保留小数点前面几位数字,解决方法如下:
import numpy as np
np.set_printoptions(threshold=np.inf) #tensorflow print(W.eval())
print(b.eval())