解决tensorflow中的InvalidArgumentError

时间:2020-07-05 14:33:53

标签: python tensorflow machine-learning keras

我也无话可说,我遇到了一个错误,以下代码似乎无法解决。

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',但似乎也不起作用。我正在运行python 3.7,真的会提供一些帮助。我对此也很陌生。

谢谢。

1 个答案:

答案 0 :(得分: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)