简体   繁体   English

解决 tensorflow 中的 InvalidArgumentError

[英]Solve InvalidArgumentError in tensorflow

Nothing much I can say either from that I'm getting an error which I can't seem to solve from the following piece of code.我也没有什么可以说的,因为我收到了一个我似乎无法从下面的代码中解决的错误。

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)

I've tried changing the loss function to 'categorical_crossentropy', but seemed to not work either.我尝试将损失 function 更改为“categorical_crossentropy”,但似乎也不起作用。 I am running Python 3.7 and would really appriciate some help.我正在运行 Python 3.7 并且真的会提供一些帮助。 I am kind of new to this as well.我对此也很陌生。

Thanks in advance.提前致谢。

the problem is in the way you manage the dimensionality in your network... you receive 3D images and don't pass to 2D to obtain probabilities... this can simply be done using Flatten or global pooling operation.问题在于您管理网络维度的方式......您收到 3D 图像并且不传递到 2D 以获得概率......这可以简单地使用 Flatten 或全局池操作来完成。 sparse_categorical_crossentropy is correct in your case. sparse_categorical_crossentropy 在您的情况下是正确的。 here an example这是一个例子

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