张量输入形状拟合模型的问题

时间:2020-02-01 00:48:00

标签: python tensorflow

我正在运行一个简单的神经网络接口。

model = tf.keras.models.Sequential([
  #tf.keras.layers.Flatten(input_shape=(10, 1)),
  tf.keras.layers.Dense(128, activation='relu'),
  tf.keras.layers.Dropout(0.2),
  tf.keras.layers.Dense(2, activation='softmax')
])

具有给定的损失函数:

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

以张量[10,1]的形式进给,即表示值和标签。 当我拟合模型时,出现错误:

output_shape = [product,shape [-1]] IndexError:列表索引超出 范围

我正在使用tensorflow 2.0

这是输出错误:

If using Keras pass *_constraint arguments to layers.
Train on 200000 steps
Epoch 1/5
2020-02-02 12:48:13.088278: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10.0
Traceback (most recent call last):
  File "MLP.py", line 121, in <module>
    model.fit(train, epochs=5)
  File "/home/jacek/anaconda3/envs/alice_tf/lib/python3.7/site-packages/tensorflow_core/python/keras/engine/training.py", line 727, in fit
    use_multiprocessing=use_multiprocessing)
  File "/home/jacek/anaconda3/envs/alice_tf/lib/python3.7/site-packages/tensorflow_core/python/keras/engine/training_arrays.py", line 675, in fit
    steps_name='steps_per_epoch')
  File "/home/jacek/anaconda3/envs/alice_tf/lib/python3.7/site-packages/tensorflow_core/python/keras/engine/training_arrays.py", line 300, in model_iteration
    batch_outs = f(actual_inputs)
  File "/home/jacek/anaconda3/envs/alice_tf/lib/python3.7/site-packages/tensorflow_core/python/keras/backend.py", line 3476, in __call__
    run_metadata=self.run_metadata)
  File "/home/jacek/anaconda3/envs/alice_tf/lib/python3.7/site-packages/tensorflow_core/python/client/session.py", line 1472, in __call__
    run_metadata_ptr)
tensorflow.python.framework.errors_impl.InvalidArgumentError: 2 root error(s) found.
  (0) Invalid argument: Expected dimension in the range [0, 0), but got -1
     [[{{node metrics/acc/ArgMax}}]]
     [[loss/mul/_59]]
  (1) Invalid argument: Expected dimension in the range [0, 0), but got -1
     [[{{node metrics/acc/ArgMax}}]]
0 successful operations.
0 derived errors ignored.

1 个答案:

答案 0 :(得分:0)

您可以提供model.fit电话吗?这是一组工作代码。工作正常,这意味着它在使用Tensorflow 2.0或2.1时不会引发错误。

import numpy as np
import tensorflow as tf

model = tf.keras.models.Sequential([
  #tf.keras.layers.Flatten(input_shape=(10, 1)),
  tf.keras.layers.Dense(128, activation='relu'),
  tf.keras.layers.Dropout(0.2),
  tf.keras.layers.Dense(2, activation='softmax')
])

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

# Generate fake data.
x = np.ones([10, 1], dtype=np.float32)
y = np.ones([10, 2], dtype=np.float32)

# Train the model, providing features and labels.
model.fit(x, y)

您收到的错误可能是因为您没有向y提供model.fit