tensorflow GradientDescentOptimizer不更新变量?

我是机器学习的新手。我从最简单的分类例子开始,使用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()或其他方法来初始化权重,而不要使用零值。

这个是一个类似的问题。

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注