Keras为目标添加额外维度(检查目标时出错)

时间:2017-10-25 10:55:25

标签: python numpy tensorflow keras

我使用此代码定义了一个Siamese Keras模型:

image1 = Input(shape=(128,128,3))
image2 = Input(shape=(128,128,3))

mobilenet = keras.applications.mobilenet.MobileNet(
        input_shape=(128,128,3), 
        alpha=0.25, 
        depth_multiplier=1, 
        dropout=1e-3, 
        include_top=False, 
        weights='imagenet', 
        input_tensor=None, 
        pooling='avg')

out1 = mobilenet(image1)
out2 = mobilenet(image2)

diff = subtract([out1, out2])

distance = Lambda(lambda x: K.sqrt(K.sum(K.square(x), axis=1)))(diff)

model = Model(inputs=[image1, image2], outputs=distance)
model.compile(optimizer='rmsprop',
                  loss='hinge',
                  metrics=['accuracy'])

模型摘要如下:

____________________________________________________________________________________________________
Layer (type)                     Output Shape          Param #     Connected to                     
====================================================================================================
input_1 (InputLayer)             (None, 128, 128, 3)   0                                            
____________________________________________________________________________________________________
input_2 (InputLayer)             (None, 128, 128, 3)   0                                            
____________________________________________________________________________________________________
mobilenet_0.25_128 (Model)       (None, 256)           218544      input_1[0][0]                    
                                                                   input_2[0][0]                    
____________________________________________________________________________________________________
subtract_1 (Subtract)            (None, 256)           0           mobilenet_0.25_128[1][0]         
                                                                   mobilenet_0.25_128[2][0]         
____________________________________________________________________________________________________
lambda_1 (Lambda)                (None,)               0           subtract_1[0][0]                 
====================================================================================================
Total params: 218,544
Trainable params: 213,072
Non-trainable params: 5,472
____________________________________________________________________________________________________

我正在努力训练模型。我的训练程序如下:

for i in range(1000):
    X1,X2,y = data_source.getTrainingBatch(10, sameProb=0.5)
    y = y[:,0] // grab ground truth for class 0
    print(y.shape) // (10,)
    loss=model.train_on_batch([X1,X2], y)

X1和X2的形状为(10, 128, 128, 3)

y具有形状(10,2),并且是2个类的单热编码向量的列表。我只对第一堂课采取基本的事实并尝试将其提供给模型。

print(y.shape)语句打印(10,),因此数组为1D。但是当我运行代码时,我收到以下错误:

ValueError                                Traceback (most recent call last)
<ipython-input-2-bf89243ee200> in <module>()
----> 1 n=net.SiamNet("drug-net")

~/development/drug_master/net_keras.py in __init__(self, model_name, training)
     16                         print(self.model.summary())
     17                         self.data_source = data.BoxComparisonData()
---> 18                         self.train()
     19                         self.save()
     20                 else:

~/development/drug_master/net_keras.py in train(self)
     75                         X1,X2,y = self.data_source.getTrainingBatch(10, sameProb=0.5)
     76                         print(y.shape)
---> 77                         loss=self.model.train_on_batch([X1,X2], y[:,0].flatten())  # starts training
     78                         print("Loss (%d):" % i, loss)
     79                         if(i%20 == 0):

~/anaconda3/lib/python3.6/site-packages/keras/engine/training.py in train_on_batch(self, x, y, sample_weight, class_weight)
   1754             sample_weight=sample_weight,
   1755             class_weight=class_weight,
-> 1756             check_batch_axis=True)
   1757         if self.uses_learning_phase and not isinstance(K.learning_phase(), int):
   1758             ins = x + y + sample_weights + [1.]

~/anaconda3/lib/python3.6/site-packages/keras/engine/training.py in _standardize_user_data(self, x, y, sample_weight, class_weight, check_batch_axis, batch_size)
   1380                                     output_shapes,
   1381                                     check_batch_axis=False,
-> 1382                                     exception_prefix='target')
   1383         sample_weights = _standardize_sample_weights(sample_weight,
   1384                                                      self._feed_output_names)

~/anaconda3/lib/python3.6/site-packages/keras/engine/training.py in _standardize_input_data(data, names, shapes, check_batch_axis, exception_prefix)
    130                                  ' to have ' + str(len(shapes[i])) +
    131                                  ' dimensions, but got array with shape ' +
--> 132                                  str(array.shape))
    133             for j, (dim, ref_dim) in enumerate(zip(array.shape, shapes[i])):
    134                 if not j and not check_batch_axis:

ValueError: Error when checking target: expected lambda_1 to have 1 dimensions, but got array with shape (10, 1)

据我所知,模型期望目标有一个维度,在本例中为(10,),但是接收具有形状(10,1)的2D目标。似乎Keras为我的目标添加了额外的维度。我错过了什么?

Keras版本是2.0.8

我使用tensorflow作为后端(1.3.0)

1 个答案:

答案 0 :(得分:0)

这很奇怪。

似乎y实际上是(10,1)

您可以在keepdims=True中使用K.sum让keras期待(10,1)数组。

不确定原因是什么。也许你有旧的Y vars(也许是大写的?)没有被删除而且你偶然使用它们了?