【问题标题】:ValueError: Error when checking input: expected dense_1_input to have shape (1,) but got array with shape (5000,)ValueError:检查输入时出错:预期dense_1_input的形状为(1,)但得到的数组形状为(5000,)
【发布时间】:2020-11-22 02:54:27
【问题描述】:

我正在尝试为 kaggle 上的讽刺检测数据集构建 NLP 模型。我是实现神经网络的初学者,这是我第一次使用 Keras 实现神经网络。这是我的代码:

# Neural Network.
import tensorflow as tf
print(tf.__version__)

import keras
print(keras.__version__)

from keras.models import Sequential
from keras.layers import Dense

# Create a new sequential model.
model = Sequential()

# Add input layer and Dense layer.
# Input layer contains 1 feature whereas first hidden layer has 5 neurons.
model.add(Dense(5,input_shape=(1,),activation="relu"))

# Add a final output one neuron layer.
model.add(Dense(1,activation="sigmoid"))

# Summarize a model:
model.summary()

# Model output shape.
print(model.output_shape)

# Model config.
print(model.get_config())

# List all weight tensors.
print(model.get_weights())

# Compile the Model.
model.compile(loss='binary_crossentropy',optimizer='adam',metrics=['accuracy'])

# Fit the model.
model.fit(vector_array_train,y_train,epochs=20,batch_size=1, verbose=1)

代码的输出是:

2.0.0
Using TensorFlow backend.
2.3.1
2020-08-01 18:58:02.364557: I tensorflow/core/platform/cpu_feature_guard.cc:142] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2
Model: "sequential_1"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
dense_1 (Dense)              (None, 5)                 10        
_________________________________________________________________
dense_2 (Dense)              (None, 1)                 6         
=================================================================
Total params: 16
Trainable params: 16
Non-trainable params: 0
_________________________________________________________________
(None, 1)
{'name': 'sequential_1', 'layers': [{'class_name': 'Dense', 'config': {'name': 'dense_1', 'trainable': True, 'batch_input_shape': (None, 1), 'dtype': 'float32', 'units': 5, 'activation': 'relu', 'use_bias': True, 'kernel_initializer': {'class_name': 'VarianceScaling', 'config': {'scale': 1.0, 'mode': 'fan_avg', 'distribution': 'uniform', 'seed': None}}, 'bias_initializer': {'class_name': 'Zeros', 'config': {}}, 'kernel_regularizer': None, 'bias_regularizer': None, 'activity_regularizer': None, 'kernel_constraint': None, 'bias_constraint': None}}, {'class_name': 'Dense', 'config': {'name': 'dense_2', 'trainable': True, 'dtype': 'float32', 'units': 1, 'activation': 'sigmoid', 'use_bias': True, 'kernel_initializer': {'class_name': 'VarianceScaling', 'config': {'scale': 1.0, 'mode': 'fan_avg', 'distribution': 'uniform', 'seed': None}}, 'bias_initializer': {'class_name': 'Zeros', 'config': {}}, 'kernel_regularizer': None, 'bias_regularizer': None, 'activity_regularizer': None, 'kernel_constraint': None, 'bias_constraint': None}}]}
[array([[-0.85931516,  0.5637381 , -0.6789112 ,  0.1663289 ,  0.1063652 ]],
      dtype=float32), array([0., 0., 0., 0., 0.], dtype=float32), array([[ 0.6834357 ],
       [ 0.5921519 ],
       [-0.71200275],
       [ 0.13235688],
       [ 0.589782  ]], dtype=float32), array([0.], dtype=float32)]
Traceback (most recent call last):
  File "C:/Users/sumed/Desktop/DataScience_Projects/NLPProjects/Sarcasm_Detection/sarcasm_detection.py", line 180, in <module>
    model.fit(vector_array_train,y_train,epochs=20,batch_size=1, verbose=1)
  File "C:\Python3.6.6\lib\site-packages\keras\engine\training.py", line 1154, in fit
    batch_size=batch_size)
  File "C:\Python3.6.6\lib\site-packages\keras\engine\training.py", line 579, in _standardize_user_data
    exception_prefix='input')
  File "C:\Python3.6.6\lib\site-packages\keras\engine\training_utils.py", line 145, in standardize_input_data
    str(data_shape))
ValueError: Error when checking input: expected dense_1_input to have shape (1,) but got array with shape (5000,)


我在最后一行代码中遇到错误: ValueError:检查输入时出错:预期dense_1_input 的形状为(1,),但得到的数组的形状为(5000,)

作为一个新手,我无法理解,这里有什么问题?请帮忙。

【问题讨论】:

    标签: python keras deep-learning neural-network


    【解决方案1】:

    当你定义模型时,你告诉模型期望输入形状为 (1,):model.add(Dense(5,input_shape=(1,),activation="relu"))

    将其更改为model.add(Dense(5,input_shape=(None,),activation="relu"))。 或者,您也可以将其设置为 5000 而不是 None

    【讨论】:

    • 谢谢,我试过 None 但没有用,而 (5000,) 对我有用。我也明白为什么 (5000,) 有效,因为在使用 Tfidf 对特征进行矢量化时,我使用了 max_features = 5000 和后来我忘了考虑到这一点。非常感谢。
    猜你喜欢
    • 2020-04-11
    • 1970-01-01
    • 2018-10-24
    • 2018-09-30
    • 2020-05-30
    • 2019-10-22
    • 1970-01-01
    • 1970-01-01
    • 2019-11-21
    相关资源
    最近更新 更多