import tensorflow as tf
from numpy.random import RandomState
from tensorflow.examples.tutorials.mnist import input_data
x = tf.placeholder(tf.float32, shape=(None, 28*28), name="x-input")
batch_size = 8
w1= tf.Variable(tf.random_normal([28*28,40], stddev=0.3, seed=1))
b1= tf.Variable(tf.zeros([40]))
f1 = tf.add(tf.matmul(x, w1),b1)
y1 = tf.nn.relu(f1)
print(tf.size(x))
print(tf.size(w1))
w2= tf.Variable(tf.zeros([40, 10]))
b2=tf.Variable(tf.zeros([10]))
f2 = tf.add(tf.matmul(y1, w2),b2)
y = tf.nn.softmax(f2)
y_= tf.placeholder(tf.float32, shape=(None, 10), name='y-input')
cross_entropy = -tf.reduce_mean(y_ * tf.log(tf.clip_by_value(y, 1e-10, 1.0))+ (1-y_) * tf.log(tf.clip_by_value(1 - y, 1e-10, 1.0)))
#cross_entropy = -tf.reduce_mean(tf.reduce_sum(y_ * tf.log(y)))
train_step = tf.train.AdamOptimizer(0.001).minimize(cross_entropy)
with tf.Session() as session:
init_op = tf.global_variables_initializer()
session.run(init_op)
# 输出目前(未经训练)的参数取值。
mnist = input_data.read_data_sets("MNIST_data/",one_hot=True)
for i in range(100):
batch_xs,batch_ys = mnist.train.next_batch(100)
session.run(train_step,feed_dict={x:batch_xs,y_:batch_ys})
correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction,"float"))
print(session.run(accuracy,feed_dict={x:mnist.test.images,y_:mnist.test.labels}))
其中MNIST_data数据集可以到https://download.csdn.net/download/a486259/10814273里下载(含代码,案例有softmax分类、knn分类和神经网络分类)下载后可直接运行