Tensorflow:在MNIST数据集上可视化线性分类器的训练权重

时间:2017-05-13 09:24:38

标签: machine-learning tensorflow deep-learning mnist

我在MNIST数据集上训练了一个线性分类器,准确率为92%。然后我固定了权重并优化了输入图像,使得8的softmax概率最大化。但softmax损失不会低于2.302(-log(1/10)),这意味着我的训练毫无用处。我做错了什么?

训练重量的代码:

import tensorflow as tf
import numpy as np
from tensorflow.examples.tutorials.mnist import input_data

mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
trX, trY, teX, teY = mnist.train.images, mnist.train.labels,       
mnist.test.images, mnist.test.labels

X = tf.placeholder("float", [None, 784])
Y = tf.placeholder("float", [None, 10])

w = tf.Variable(tf.random_normal([784, 10], stddev=0.01))
b = tf.Variable(tf.zeros([10]))

o = tf.nn.sigmoid(tf.matmul(X, w)+b)

cost= tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=o, labels=Y))
train_op = tf.train.RMSPropOptimizer(0.001, 0.9).minimize(cost)
predict_op = tf.argmax(o, 1)

sess=tf.Session()
sess.run(tf.global_variables_initializer())
for i in range(100):
  for start, end in zip(range(0, len(trX), 256), range(256, len(trX)+1, 256)):
      sess.run(train_op, feed_dict={X: trX[start:end], Y: trY[start:end]})
  print(i, np.mean(np.argmax(teY, axis=1) == sess.run(predict_op, feed_dict={X: teX})))

训练固定重量图像的代码:

#Copy trained weights into W,B and pass them as placeholders to new model
W=sess.run(w)
B=sess.run(b)

X=tf.Variable(tf.random_normal([1, 784], stddev=0.01))
Y=tf.constant([0, 0, 0, 0, 0, 0, 0, 0, 1, 0])

w=tf.placeholder("float")
b=tf.placeholder("float")

o = tf.nn.sigmoid(tf.matmul(X, w)+b)

cost= tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=o, labels=Y))
train_op = tf.train.RMSPropOptimizer(0.001, 0.9).minimize(cost)
predict_op = tf.argmax(o, 1)

sess.run(tf.global_variables_initializer())
for i in range(1000):
  sess.run(train_op, feed_dict={w:W, b:B})
  if i%50==0:
    sess.run(cost, feed_dict={w:W, b:B})
    print(i, sess.run(predict_op, feed_dict={w:W, b:B}))

1 个答案:

答案 0 :(得分:1)

您不应该在网络输出上拨打tf.sigmoidsoftmax_cross_entropy_with_logits假设您的输入是logits,即无约束的实数。使用

o = tf.matmul(X, w)+b

将准确度提高到92.8%。

通过此修改,您的第二次培训将起作用。成本达到0,尽管得到的图像不过是吸引人的。

enter image description here

相关问题