from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) # 使用one-hot编码
print(mnist.train.images.shape, mnist.train.labels.shape)
print(mnist.test.images.shape, mnist.test.labels.shape)
import tensorflow as tf
sess = tf.InteractiveSession() #将session注册为默认的session,之后的运算跑在这个session中
x = tf.placeholder(tf.float32, [None, 784]) # 构建占位符,None表示样本的数量可以是任意的 占位符可以不指定初始值主要为真实的输入数据
W = tf.Variable(tf.zeros([784, 10])) # 构建一个变量,代表权重矩阵,初始化为0 变量主要用于权值和偏置,需指定初始值
b = tf.Variable(tf.zeros([10])) # 构建一个变量,代表偏置,初始化为0
y = tf.nn.softmax(tf.matmul(x, W) + b) # 构建了一个softmax的模型:y = softmax(Wx + b),y指样本标签的预测值
y_ = tf.placeholder(tf.float32, [None, 10])
cross_entropy = -tf.reduce_sum(y_ * tf.log(y)) #求交叉熵
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy) #使用随机梯度下降最优化算法
tf.global_variables_initializer().run() #在使用变量之前,必须对变量进行初始化。按照习惯用法,使用tf.global_variables_initializer()将所有全局变量的初始化器汇总,并对其进行初始化。
for i in range(8000): # 迭代次数1000
batch_xs, batch_ys = mnist.train.next_batch(100) # 使用minibatch,一个batch大小为100
train_step.run({x: batch_xs, y_: batch_ys})
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1)) # tf.argmax()返回的是某一维度上其数据最大所在的索引值,tf.equal 来检测我们的预测是否真实标签匹配(索引位置一样表示匹配)。
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) # reduce_mean用平均值来统计测试准确率
print(accuracy.eval({x: mnist.test.images, y_: mnist.test.labels})) # 打印测试信息
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) # 使用one-hot编码
print(mnist.train.images.shape, mnist.train.labels.shape)
print(mnist.test.images.shape, mnist.test.labels.shape)
import tensorflow as tf
sess = tf.InteractiveSession() #将session注册为默认的session,之后的运算跑在这个session中
x = tf.placeholder(tf.float32, [None, 784]) # 构建占位符,None表示样本的数量可以是任意的 占位符可以不指定初始值主要为真实的输入数据
W = tf.Variable(tf.zeros([784, 10])) # 构建一个变量,代表权重矩阵,初始化为0 变量主要用于权值和偏置,需指定初始值
b = tf.Variable(tf.zeros([10])) # 构建一个变量,代表偏置,初始化为0
y = tf.nn.softmax(tf.matmul(x, W) + b) # 构建了一个softmax的模型:y = softmax(Wx + b),y指样本标签的预测值
y_ = tf.placeholder(tf.float32, [None, 10])
cross_entropy = -tf.reduce_sum(y_ * tf.log(y)) #求交叉熵
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy) #使用随机梯度下降最优化算法
tf.global_variables_initializer().run() #在使用变量之前,必须对变量进行初始化。按照习惯用法,使用tf.global_variables_initializer()将所有全局变量的初始化器汇总,并对其进行初始化。
for i in range(8000): # 迭代次数1000
batch_xs, batch_ys = mnist.train.next_batch(100) # 使用minibatch,一个batch大小为100
train_step.run({x: batch_xs, y_: batch_ys})
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1)) # tf.argmax()返回的是某一维度上其数据最大所在的索引值,tf.equal 来检测我们的预测是否真实标签匹配(索引位置一样表示匹配)。
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) # reduce_mean用平均值来统计测试准确率
print(accuracy.eval({x: mnist.test.images, y_: mnist.test.labels})) # 打印测试信息