import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials import input_data
# import input_data
mnist = input_data.read_data_sets('data/', one_hot= True)
trainimg = mnist.train.images
trainlabel = mnist.train.labels
testimg = mnist.test.images
testimg = mnist.test.labels
x = tf.placeholder('float',[None,784])
y = tf.placeholder('float',[None,10])
w = tf.Variable(tf.zeros([784,10]))
b = tf.Variable(tf.zeros([10]))
active = tf.nn.softmax(tf.matmul(x,w)+b)
#损失函数
loss = tf.reduce_mean(-tf.reduce_sum(y*tf.log(active), reduction_indices=1))
#定义优化器
optimizer = tf.train.GradientDescentOptimizer(0.01).minimize(loss)
#判断所有样本中预测和事实是不是相等
pred = tf.equal(tf.argmax(active,1),tf.argmax(y,1))
accr = tf.reduce_mean(tf.cast(pred,'float'))
init = tf.global_variables_initializer()
batch_size =100
with tf.Session() as sess:
sess.run(init)
for epoch in range(50):
avg_cost = 0
num_batch = int(mnist.train.num_examples/batch_size)
for i in range(num_batch):
batch_xs, batch_ys = mnist.train.next_batch(batch_size)
sess.run(optimizer,feed_dict={x:batch_xs, y:batch_ys})
avg_cost += sess.run(loss,feed_dict={x:batch_xs, y:batch_ys})
if epoch %5 ==0:
feeds_train = {x:batch_xs, y:batch_ys}
feeds_test = {x:mnist.test.images,y:mnist.test.labels}
train_acc = sess.run(accr, feed_dict=feeds_train)
test_acc = sess.run(accr, feed_dict=feeds_test )
print('epoch %03d/%03d loss:%.9f train_acc:%.3f, test_acc:%.3f'
%(epoch, 100,avg_cost,train_acc,test_acc))
tensorflow学习(三)基于mnist数据的十分类
最新推荐文章于 2023-12-17 11:24:18 发布