构建了具有输入Tensor形状的Tensorflow模型,但在形状不兼容的输入上调用了该模型(神经网络)

时间:2020-09-28 09:55:43

标签: python tensorflow keras neural-network

基本上,我正在尝试构建一个使用嵌入式单词作为输入的模型,但是我一直收到此警告。我曾尝试根据模型的训练数据多次更改输入的形状,但这对模型构建没有任何影响。我正在尝试预测输入的温度值,范围是0-100

在训练过程中,损失分数有时会变化,而其他时候则不会。我不太确定这是怎么回事。

数据的原始形状:

x_train shape: (17405, 3840)
y_train shape: (17405,)
x_valid shape: (4352, 3840)
y_valid shape: (4352,)

建立模型

# Initializing the ANN
model = Sequential()

# Adding the input layer and the first hidden layer
model.add(Dense(units=1, activation='relu', input_shape = x_train.shape))

# Adding the second hidden layer
model.add(Dense(units=1, activation='relu'))

# Adding the output layer
model.add(Dense(units=1, activation='linear'))

编译和培训

#Global Variables for Model
optimizer = tf.keras.optimizers.Adam(learning_rate=0.0001) #methods used to change the attributes of the nn
# tf.keras.optimizers.SGD(learning_rate=0.001)
batch_size = 100 # Defines the number of samples that will be propagated through the network.
loss = 'mean_squared_error' #Cmpute the quantity that a model should seek to minimize during training
EPOCHS = 20 # How many times to go through the training set.

# Compiling the Model
model.compile(optimizer = optimizer, loss = loss, metrics=['mae'])

# Training/Fitting the Model on the Training set
model.fit(x_train, y_train, batch_size = batch_size, 
                     epochs = EPOCHS, verbose = 1)
    
#Model Summary
model.summary()
    
#Model Evaluation
score = model.evaluate(x_valid, y_valid, verbose=1)

如前所述,模型可以运行,但是出现以下错误:

WARNING:tensorflow:Model was constructed with shape (None, 17405, 3840) for input Tensor("dense_73_input:0", shape=(None, 17405, 3840), dtype=float32), but it was called on an input with incompatible shape (None, 3840).

1 个答案:

答案 0 :(得分:1)

您的数据形状实际上是(None, 3840),因为形状中的17405意味着您数据中的元素数量,而不必传递给模型。

所以您应该改用它:

model = Sequential()
model.add(Dense(units=1, activation='relu', input_shape = x_train.shape[1]))
model.add(Dense(units=1, activation='relu'))
model.add(Dense(units=1, activation='linear'))