繁体   English   中英

解决 tensorflow 中的 InvalidArgumentError

[英]Solve InvalidArgumentError in tensorflow

我也没有什么可以说的,因为我收到了一个我似乎无法从下面的代码中解决的错误。

import tensorflow as tf
import matplotlib.pyplot as plt

(x_train, y_train), (x_test, y_test) = tf.keras.datasets.cifar10.load_data()

inpTensor = tf.keras.layers.Input(x_train.shape[1:],)

hidden1Out = tf.keras.layers.Dense(units=128, activation=tf.nn.relu)(inpTensor)
hidden2Out = tf.keras.layers.Dense(units=128, activation=tf.nn.relu)(hidden1Out)  
finalOut = tf.keras.layers.Dense(units=10, activation=tf.nn.softmax)(hidden2Out)

model = tf.keras.Model(inputs=inpTensor, outputs=finalOut)

model.summary()

model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

model.fit(x_train,y_train, epochs = 4)

我尝试将损失 function 更改为“categorical_crossentropy”,但似乎也不起作用。 我正在运行 Python 3.7 并且真的会提供一些帮助。 我对此也很陌生。

提前致谢。

问题在于您管理网络维度的方式......您收到 3D 图像并且不传递到 2D 以获得概率......这可以简单地使用 Flatten 或全局池操作来完成。 sparse_categorical_crossentropy 在您的情况下是正确的。 这是一个例子

import tensorflow as tf
import matplotlib.pyplot as plt

(x_train, y_train), (x_test, y_test) = tf.keras.datasets.cifar10.load_data()

inpTensor = tf.keras.layers.Input(x_train.shape[1:],)

hidden1Out = tf.keras.layers.Dense(units=128, activation=tf.nn.relu)(inpTensor)
hidden2Out = tf.keras.layers.Dense(units=128, activation=tf.nn.relu)(hidden1Out)
pooling = tf.keras.layers.GlobalMaxPool2D()(hidden2Out) #<== also GlobalAvgPool2D or Flatten are ok
finalOut = tf.keras.layers.Dense(units=10, activation=tf.nn.softmax)(pooling)

model = tf.keras.Model(inputs=inpTensor, outputs=finalOut)

model.summary()

model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

model.fit(x_train,y_train, epochs = 4)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM