AttributeError:“元组”对象没有属性“ ndim”

时间:2019-05-01 00:39:32

标签: python numpy tensorflow keras

我正在尝试建立一个暹罗网络,该网络需要两个输入,并且有一个培训标签。 使用model.fit()时出现上述错误。

请告诉我该怎么办才能纠正错误。

请在下面找到代码。

input_shape = (data.shape[1],) #input_shape --> (474,)
print(input_shape)

left_input = Input(input_shape)
right_input = Input(input_shape)
from keras.optimizers import SGD,Adam

dropoutRate=0.0
numNeurons=40 
optimizer='adam' 
numNeuronsFirstTwo=40

convnet = Sequential()
convnet.add(Dense(numNeuronsFirstTwo, kernel_regularizer=l2(0.001)))
convnet.add(Dense(numNeuronsFirstTwo, kernel_regularizer=l2(0.001)))
convnet.add(Dropout(dropoutRate))
convnet.add(Dense(numNeurons, kernel_regularizer=l2(0.001)))

encoded_l = convnet(left_input)
encoded_r = convnet(right_input)

#layer to merge two encoded inputs with the l1 distance between them
L1_layer = Lambda(lambda tensors:K.abs(tensors[0] - tensors[1]))

#call this layer on list of two input tensors.
L1_distance = L1_layer([encoded_l, encoded_r])
prediction = Dense(1,activation='sigmoid',bias_initializer='zeros')(L1_distance)
siamese_net = Model(inputs=[left_input,right_input],outputs=prediction)

optimizer = Adam(0.00006)
siamese_net.compile(loss="binary_crossentropy",optimizer=optimizer)

这是模型:

__________________________________________________________________________________________________
Layer (type)                    Output Shape         Param #     Connected to                     
==================================================================================================
input_1 (InputLayer)            (None, 474)          0                                            
__________________________________________________________________________________________________
input_2 (InputLayer)            (None, 474)          0                                            
__________________________________________________________________________________________________
sequential_1 (Sequential)       (None, 40)           22280       input_1[0][0]                    
                                                                 input_2[0][0]                    
__________________________________________________________________________________________________
lambda_1 (Lambda)               (None, 40)           0           sequential_1[1][0]               
                                                                 sequential_1[2][0]               
__________________________________________________________________________________________________
dense_4 (Dense)                 (None, 1)            41          lambda_1[0][0]                   
==================================================================================================
Total params: 22,321
Trainable params: 22,321
Non-trainable params: 0
batch_size = 32
epochs = 50
class_weight = {0:1, 1:15}

#print(len(trainValiData))

labels = [1,0]
labels = np.asarray(labels)
print(labels)

siamese_net.summary()
siamese_net.fit((trainValiData[1], trainValiData[2]), labels)

我得到的错误如下:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-18-b55790c3f858> in <module>()
     13 
     14 siamese_net.summary()
---> 15 siamese_net.fit((trainValiData[1], trainValiData[2]), labels)

~\Anaconda3\lib\site-packages\keras\engine\training.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, **kwargs)
    953             sample_weight=sample_weight,
    954             class_weight=class_weight,
--> 955             batch_size=batch_size)
    956         # Prepare validation data.
    957         do_validation = False

~\Anaconda3\lib\site-packages\keras\engine\training.py in _standardize_user_data(self, x, y, sample_weight, class_weight, check_array_lengths, batch_size)
    752             feed_input_shapes,
    753             check_batch_axis=False,  # Don't enforce the batch size.
--> 754             exception_prefix='input')
    755 
    756         if y is not None:

~\Anaconda3\lib\site-packages\keras\engine\training_utils.py in standardize_input_data(data, names, shapes, check_batch_axis, exception_prefix)
     88         data = data.values if data.__class__.__name__ == 'DataFrame' else data
     89         data = [data]
---> 90     data = [standardize_single_array(x) for x in data]
     91 
     92     if len(data) != len(names):

~\Anaconda3\lib\site-packages\keras\engine\training_utils.py in <listcomp>(.0)
     88         data = data.values if data.__class__.__name__ == 'DataFrame' else data
     89         data = [data]
---> 90     data = [standardize_single_array(x) for x in data]
     91 
     92     if len(data) != len(names):

~\Anaconda3\lib\site-packages\keras\engine\training_utils.py in standardize_single_array(x)
     23                 'Got tensor with shape: %s' % str(shape))
     24         return x
---> 25     elif x.ndim == 1:
     26         x = np.expand_dims(x, 1)
     27     return x

AttributeError: 'tuple' object has no attribute 'ndim'

请告诉我该如何解决。 非常感谢。

编辑:新错误:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-20-93dfa1f77351> in <module>()
     15 
     16 siamese_net.summary()
---> 17 siamese_net.fit([trainValiData[1], trainValiData[2]], labels)

~\Anaconda3\lib\site-packages\keras\engine\training.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, **kwargs)
    953             sample_weight=sample_weight,
    954             class_weight=class_weight,
--> 955             batch_size=batch_size)
    956         # Prepare validation data.
    957         do_validation = False

~\Anaconda3\lib\site-packages\keras\engine\training.py in _standardize_user_data(self, x, y, sample_weight, class_weight, check_array_lengths, batch_size)
    752             feed_input_shapes,
    753             check_batch_axis=False,  # Don't enforce the batch size.
--> 754             exception_prefix='input')
    755 
    756         if y is not None:

~\Anaconda3\lib\site-packages\keras\engine\training_utils.py in standardize_input_data(data, names, shapes, check_batch_axis, exception_prefix)
    134                             ': expected ' + names[i] + ' to have shape ' +
    135                             str(shape) + ' but got array with shape ' +
--> 136                             str(data_shape))
    137     return data
    138 

ValueError: Error when checking input: expected input_1 to have shape (474,) but got array with shape (1,)

0 个答案:

没有答案