解决TensorFlow中的InvalidArgumentError

我也没有太多可以说的,只是我在运行以下代码时遇到了一个无法解决的错误。

import tensorflow as tfimport 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,非常希望能得到一些帮助。我在这方面也是新手。

提前感谢。


回答:

问题在于你如何管理网络中的维度…你接收的是3D图像,但没有转换为2D来获取概率…这可以通过使用Flatten或全局池化操作简单地解决。你的情况下使用sparse_categorical_crossentropy是正确的。这里是一个示例

import tensorflow as tfimport 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) #<== GlobalAvgPool2D或Flatten也可以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)

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注