使用tensorflow进行分类任务
这个就还是和之前的回归用的一样的建立一个层的函数
定义了权重,偏差以及计算方法
def add_layer(inputs, in_size, out_size, activation_function=None,):
# add one more layer and return the output of this layer
Weights = tf.Variable(tf.random_normal([in_size, out_size]))
biases = tf.Variable(tf.zeros([1, out_size]) + 0.1,)
Wx_plus_b = tf.matmul(inputs, Weights) + biases
if activation_function is None:
outputs = Wx_plus_b
else:
outputs = activation_function(Wx_plus_b,)
return outputs
这个是新定义的一个函数,用来计算相似的精确度的,首先获取了全局的prediction,这个prediction用的是28×28的输入,10的输出,原因是输入的图片是28×28的像素值,需要预测到底是1到10中的哪个数字。激活函数是softmax,看斯坦福231n的时候好像讲过这个,但当时走神没认真听,大概是说分类问题要用这个激活函数配合下面这个【cross_entropy】(交叉熵?)的minimize来使用。
下面一句correct_prediction = tf.equal(tf.argmax(y_pre,1), tf.argmax(v_ys,1))
就是将预测值和真实值比较具体怎么来的教程里也没说。以后看斯坦福231n或者别的资料也许能找到吧。
def compute_accuracy(v_xs, v_ys):
global prediction
y_pre = sess.run(prediction, feed_dict={xs: v_xs})
correct_prediction = tf.equal(tf.argmax(y_pre,1), tf.argmax(v_ys,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
result = sess.run(accuracy, feed_dict={xs: v_xs, ys: v_ys})
return result
从mnist里抽出100个样本进行训练,也算随机梯度下降吧。
for i in range(1000):
batch_xs, batch_ys = mnist.train.next_batch(100)
sess.run(train_step, feed_dict={xs: batch_xs, ys: batch_ys})
if i % 50 == 0:
print(compute_accuracy(
mnist.test.images, mnist.test.labels))
网友评论