"AttributeError: 'tuple' object has no attribute 'shape'" in Keras Model

1,918 views
Skip to first unread message

Alper Kursat Uysal

unread,
Sep 20, 2022, 4:42:06 PM9/20/22
to keras...@googlegroups.com
In the following sample code from the website " https://ai-leader.com/2020/05/09/using-lstm-with-1d-2d-and-3d-array/ ", I face with an error displaying "AttributeError: 'tuple' object has no attribute 'shape'". How can I get rid of that error ? Is there any size mismatch ?
 
# Using 3D array with LSTM
 
from keras import Model
from keras.layers import Input, Dense, Bidirectional
from keras.layers.recurrent import LSTM
import numpy as np
# define model for simple BI-LSTM + DNN based binary classifier
def define_model():
    input1 = Input(shape=(2,2)) #use row and column size as input size
    lstm1 = Bidirectional(LSTM(units=32))(input1)
    dnn_hidden_layer1 = Dense(3, activation='relu')(lstm1)
    dnn_output = Dense(1, activation='sigmoid')(dnn_hidden_layer1)
    model = Model(inputs=[input1],outputs=[dnn_output])
    # compile the model
    model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
    model.summary()
    return model
# Take a dummy 3D numpy array to train the model
data = np.array([[[0.1, 0.15], [0.2, 0.25]],
                 [[0.3, 0.35], [0.4, 0.45]],
                 [[0.5, 0.55], [0.6, 0.65]],
                 [[0.7, 0.75], [0.8, 0.85]],
                 [[0.9, 0.95], [1.0, 1.5]]])
Y = [1,1,1,0,0] #define binary class level for this model
print("data = ", data)
# NO NEED TO RESHAPE THE DATA as it is already in 3D format
# Call the model
model = define_model()
# Fit the model
model.fit([data],[np.array(Y)],epochs=4,batch_size=2,verbose=1)
# Take a test data to test the working of the model
test_data = np.array([[[0.2, 0.33],[0.2, 0.33]]])
# predict the sigmoid output [0,1] for the 'test_data'
pred = model.predict(test_data)
print("predicted sigmoid output => ",pred)

Robert Kanasz

unread,
Oct 16, 2022, 4:59:39 PM10/16/22
to Keras-users
Hi,

you can fix this problem by changing:
model.fit([data],[np.array(Y)],epochs=4,batch_size=2,verbose=1)
to
model.fit(data,np.array(Y),epochs=4,batch_size=2,verbose=1)

Regards
Robert

Reply all
Reply to author
Forward
0 new messages