我是机器学习的新手。我从最简单的分类例子开始,使用softmax和梯度下降来识别手写MNIST图像。通过参考其他例子,我创建了自己的逻辑回归模型如下:
import tensorflow as tfimport numpy as np(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()x_train = np.float32(x_train / 255.0)x_test = np.float32(x_test / 255.0)X = tf.placeholder(tf.float32, [None, 28, 28])Y = tf.placeholder(tf.uint8, [100])XX = tf.reshape(X, [-1, 784])W = tf.Variable(tf.zeros([784, 10]))b = tf.Variable(tf.zeros([10]))def err(x, y): predictions = tf.matmul(x, W) + b loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=tf.reshape(y, [-1, 1]), logits=predictions)) # value = tf.reduce_mean(y * tf.log(predictions)) # loss = -tf.reduce_mean(tf.one_hot(y, 10) * tf.log(predictions)) * 100. return loss# cost = err(np.reshape(x_train[:100], (-1, 784)), y_train[:100])cost = err(tf.reshape(X, (-1, 784)), Y)optimizer = tf.train.GradientDescentOptimizer(0.005).minimize(cost)init = tf.global_variables_initializer()sess = tf.Session()sess.run(init)# temp = sess.run(tf.matmul(XX, W) + b, feed_dict={X: x_train[:100]})temp = sess.run(cost, feed_dict={X: x_train[:100], Y: y_train[:100]})print(temp)# print(temp.dtype)# print(type(temp))for i in range(100): sess.run(optimizer, feed_dict={X: x_train[i * 100: 100 * (i + 1)], Y: y_train[i * 100: 100 * (i + 1)]}) # sess.run(optimizer, feed_dict={X: x_train[: 100], Y: y_train[:100]})temp = sess.run(cost, feed_dict={X: x_train[:100], Y: y_train[:100]})print(temp)sess.close()
我尝试运行优化器进行了一些迭代,使用训练图像数据和标签来喂数据。根据我的理解,在优化器运行期间,变量’W’和’b’应该被更新,因此模型在训练前后应该产生不同的结果。但是在这个代码中,模型在优化器运行前后的成本值是相同的。导致这种情况的原因可能是什么?
回答:
你将权重矩阵W
初始化为零,因此在每次权重更新时,所有参数都会接收到相同的值。请使用tf.truncated_normal()
、tf.random_normal()
、tf.contrib.layers.xavier_initializer()
或其他方法来初始化权重,而不要使用零值。
这个是一个类似的问题。