提问者:小点点

解决tensorflow中的InvalidArgumentError


我也没什么好说的,从这一点上,我得到了一个错误,我似乎无法从下面的代码段中解决。

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)

我尝试过将损失函数更改为“categorical_crossentropy”,但似乎也不起作用。 我正在运行Python3.7,我真的会得到一些帮助。 我也是个新手。

提前谢谢你。


共1个答案

匿名用户

问题在于你在网络中管理维度的方式。。。 你收到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)