python - 形状不匹配:标签的形状与 logits 的形状不兼容
问题描述
我正在尝试在 TensorFlow 中训练模型。我的标签有问题。这是我的输入功能:
def my_input_fn():
filenames = tf.constant(glob.glob("C:/test_proje/*.jpg"))
labels = tf.constant([0, 0, 1, 1, 1, 1, 1, 0, 0, 0])
labels = tf.one_hot(labels, 2)
dataset = tf.data.Dataset.from_tensor_slices((filenames, labels))
dataset = dataset.map(_parse_function)
return dataset
这是CNN模型
def cnn_model_fn(features, labels, mode):
"""Model function for CNN."""
print(labels.shape)
print(labels[0])
# Input Layer
input_layer = tf.reshape(features["image"], [-1, 168, 84, 3])
# Convolutional Layer #1
conv1 = tf.layers.conv2d(
inputs=input_layer,
filters=32,
kernel_size=[5, 5],
padding="same",
activation=tf.nn.relu)
# Pooling Layer #1
pool1 = tf.layers.max_pooling2d(inputs=conv1, pool_size=[2, 2],
strides=2)
# Convolutional Layer #2 and Pooling Layer #2
conv2 = tf.layers.conv2d(
inputs=pool1,
filters=64,
kernel_size=[5, 5],
padding="same",
activation=tf.nn.relu)
pool2 = tf.layers.max_pooling2d(inputs=conv2, pool_size=[2, 2],
strides=2)
# Dense Layer
pool2_flat = tf.reshape(pool2, [-1, 42 * 21 * 64])
dense = tf.layers.dense(inputs=pool2_flat, units=4,
activation=tf.nn.relu)
dropout = tf.layers.dropout(
inputs=dense, rate=0.4, training=mode ==
tf.estimator.ModeKeys.TRAIN)
# Logits Layer
logits = tf.layers.dense(inputs=dropout, units=2)
predictions = {
# Generate predictions (for PREDICT and EVAL mode)
"classes": tf.argmax(input=logits, axis=1),
# Add `softmax_tensor` to the graph. It is used for PREDICT and by
the
# `logging_hook`.
"probabilities": tf.nn.softmax(logits, name="softmax_tensor")
}
if mode == tf.estimator.ModeKeys.PREDICT:
return tf.estimator.EstimatorSpec(mode=mode, predictions=predictions)
# Calculate Loss (for both TRAIN and EVAL modes)
loss = tf.losses.sparse_softmax_cross_entropy(labels=labels,
logits=logits)
# Configure the Training Op (for TRAIN mode)
if mode == tf.estimator.ModeKeys.TRAIN:
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.001)
train_op = optimizer.minimize(
loss=loss,
global_step=tf.train.get_global_step())
return tf.estimator.EstimatorSpec(mode=mode, loss=loss,
train_op=train_op)
# Add evaluation metrics (for EVAL mode)
eval_metric_ops = {
"accuracy": tf.metrics.accuracy(
labels=labels, predictions=predictions["classes"])}
return tf.estimator.EstimatorSpec(
mode=mode, loss=loss, eval_metric_ops=eval_metric_ops)
我收到此错误:ValueError:形状不匹配:标签的形状(收到的 (2,))应该等于 logits 的形状,除了最后一个维度(收到的 (1, 2))。
当我在cnn_model_fn之前打印标签的形状时,它是(10,2)。但是当我在cnn_model_fn中打印出来的时候,突然变成了(2,)
谢谢。
解决方案
我认为这是您对 sparse_softmax_cross_entropy 的使用。你给它一个它不想要的热编码标签。
切换到正常的 softmax_cross_entropy 看看是否有效。
推荐阅读
- asp.net-core - 请求正文太大 - Kestrel - 在 context.Request.Body.CopyToAsync 失败
- node.js - 即使没有人在做请求,Nodemon 也会继续记录中间件的内容
- regex - 正则表达式搜索多个字符串垃圾邮件
- javascript - 对 GraphQl 查询不区分大小写进行排序
- java - 无法绑定“spring.rabbitmq”下的属性
- rest - 为什么每当我尝试将 rest 运算符作为参数输入箭头函数时,vscode 的智能感知一直在执行代码完成?
- javascript - 点击后如何使用javascript显示菜单,再次点击空白处或按钮关闭菜单?
- java - 在请求并授予权限后立即执行 ACTION_CALL 意图
- android - 如何为小部件 Flutter 添加垂直间距
- javascript - 如何将新值推送到 JavaScript 对象数组