Python tensorflow GradientDescentOptimizer未更新变量?

Python tensorflow GradientDescentOptimizer未更新变量?,python,tensorflow,machine-learning,Python,Tensorflow,Machine Learning,我是机器学习新手。我从使用softmax和梯度下降对mnist手写图像进行分类的最简单示例开始。通过参考其他一些例子,我得出了我自己的逻辑回归如下: import tensorflow as tf import 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.float

我是机器学习新手。我从使用softmax和梯度下降对mnist手写图像进行分类的最简单示例开始。通过参考其他一些例子,我得出了我自己的逻辑回归如下:

import tensorflow as tf
import 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.trunched_normal()
tf.random_normal()
tf.contrib.layers.xavier_initializer()
或其他方法,但不能使用零

这是一个类似的问题