python-3.x - tensorflow 2.0 中的 MSE 损失将 y_true 错误作为归约键
问题描述
我在运行 python 3.7.0 的 jupyter notebook 上使用了一个非常简单的神经网络和最新版本的 tensorflow 2.0。NN 有 Xip,一个浮点数作为输出,我将其用作函数 MainGaussian_1_U 中的参数,该函数近似于图像。当我尝试使用真实图像 img 和近似值 mk 之间的 MeanSquareError 计算损失时,我得到一个错误,其中损失函数似乎将 img 作为归约键。经过搜索,我仍然不知道这个键应该是什么,也找不到调试代码的方法:
model = tf.keras.models.Sequential()
# Add the layers
model.add(tf.keras.layers.Dense(64, activation="relu"))
model.add(tf.keras.layers.Dense(32, activation="relu"))
model.add(tf.keras.layers.Dense(1, activation="relu"))
# The loss method
loss_object = tf.keras.losses.MeanSquaredError()
# The optimize
optimizer = tf.keras.optimizers.Adam()
# This metrics is used to track the progress of the training loss during the training
train_loss = tf.keras.metrics.Mean(name='train_loss')
def train_step(Data, img):
MainGaussian_init(Data)
for _ in range (5):
with tf.GradientTape() as tape:
Xip= model( (sizeh**-2 * np.ones((sizeh, sizeh))).reshape(-1, 49))
MainGaussian_1_U ()
print ("img=", img)
loss= tf.keras.losses.MeanSquaredError(img, mk)
print ("loss=", loss)
gradients = tape.gradient(loss, model.trainable_variables)
print (gradients)
optimizer.apply_gradients(zip(gradients, model.trainable_variables))
train_loss(loss)
train_step (TestFile, TestFile[4])
给出的错误是:
c:\program files\python37\lib\site-packages\tensorflow_core\python\ops\losses\loss_reduction.py:67: FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison
if key not in cls.all():
...
ValueError: Invalid Reduction Key [[21.05224609 20.79420471 34.9659729 ... 48.09233093 68.83874512
83.10766602]
[20.93516541 17.0511322 39.00476074 ... 56.74258423 47.75274658
98.57067871]
[38.18562317 22.70791626 24.37176514 ... 64.9606781 47.65338135
67.61506653]
...
[85.76565552 79.45443726 73.64129639 ... 73.66456604 47.06422424
49.44664001]
[87.14616394 82.38183594 77.00856018 ... 66.21652222 71.32862854
58.39285278]
[36.74142456 37.27145386 34.52891541 ... 29.58699036 37.37667847
30.25990295]].
这是我在 Stack Overflow 上的第一个问题:请让我知道是否可以更清楚!
解决方案
您正确地创建了“损失对象”,但从不使用它。相反,您的代码尝试使用图像作为参数创建一个新的“损失对象”(这不起作用)。相反,您希望将图像放入已经创建的损失对象中。你只需要改变这条线
loss= tf.keras.losses.MeanSquaredError(img, mk)
至
loss= loss_object(img, mk)
推荐阅读
- sql-server - AX 2012 - 通过非生产恢复生产
- codenameone - createBackgroundMedia 方法不适用于 URL 和本地文件
- architecture - 单周期 mips,存储 word(sw) 控制值,为什么 MemRead 为 0 而不是“不关心”?
- google-cloud-platform - 如何使用 Google Cloud Armor 将 GKE 上的几个 IP 列入白名单?
- java - MethodHandles.lookup().defineClass 保留
- r - 我希望 R 在将我的输出导出为 pdf 时提示输入文件名和位置
- python - 如何在张量流的占位符中接受张量列表?
- testing - Ranorex 8.3.0,在尝试创建新记录时,它不显示选择网络、桌面或移动应用程序的选项
- javascript - 如何启用特定 div 的禁用复选框?
- java - 如何防止应用关闭时 startCommand 的意图返回 null