无法在keras中定义自定义丢失函数

时间:2018-06-05 09:21:55

标签: python tensorflow keras jupyter-notebook

使用:

  1. Keras 2.1.5
  2. ipython 6.2.1
  3. ipython_genutils 0.2.0
  4. Python 3
  5. Windows 7(x64) - 8GB内存 - 仅限CPU
  6. 我正在尝试在jupyter笔记本上创建一个神经网络,它工作正常,直到我决定编写自定义丢失函数。对于初学者,我决定编写一个简单的均方损失函数。 损失函数是:

    def msqeloss(y_true, y_pred):
         return K.sum(K.square(y_true-y_pred),0)
    

    我将此函数输入到模型中:

    ...
    model.add(Dropout(0.1))
    model.add(Flatten())
    model.add(Dense(120,activation='relu'))
    model.add(Dropout(0.1))
    model.add(Dense(3,activation='softmax'))
    model.compile(optimizer='RMSprop',loss=msqeloss,metrics=['accuracy'])
    ...
    

    完整堆栈错误出现了:

     AttributeError                            Traceback (most recent call last)
    <ipython-input-10-86f0a38b9a14> in <module>()
         42         model.add(Dropout(0.1))
         43         model.add(Dense(3,activation='softmax'))
    ---> 44         model.compile(optimizer='RMSprop',loss=msqeloss,metrics=['accuracy'])
         45         csv_logger = CSVLogger('meanlog_loss_log'+str(index)+'.csv', append=True, separator=';')
         46         model.fit(Xtrain,one_hot_labels,batch_size=10,epochs=Epochs,validation_data=(Xtest,np_utils.to_categorical(ytest, num_classes=3)),callbacks=[csv_logger])
    
    ~\Anaconda3\lib\site-packages\keras\models.py in compile(self, optimizer, loss, metrics, sample_weight_mode, weighted_metrics, target_tensors, **kwargs)
        822                            weighted_metrics=weighted_metrics,
        823                            target_tensors=target_tensors,
    --> 824                            **kwargs)
        825         self.optimizer = self.model.optimizer
        826         self.loss = self.model.loss
    
    ~\Anaconda3\lib\site-packages\keras\engine\training.py in compile(self, optimizer, loss, metrics, loss_weights, sample_weight_mode, weighted_metrics, target_tensors, **kwargs)
        828                 with K.name_scope(self.output_names[i] + '_loss'):
        829                     output_loss = weighted_loss(y_true, y_pred,
    --> 830                                                 sample_weight, mask)
        831                 if len(self.outputs) > 1:
        832                     self.metrics_tensors.append(output_loss)
    
    ~\Anaconda3\lib\site-packages\keras\engine\training.py in weighted(y_true, y_pred, weights, mask)
        427         """
        428         # score_array has ndim >= 2
    --> 429         score_array = fn(y_true, y_pred)
        430         if mask is not None:
        431             # Cast the mask to floatX to avoid float64 upcasting in Theano
    
    <ipython-input-9-d8157a575c41> in msqeloss(y_true, y_pred)
          1 def msqeloss(y_true, y_pred):
    ----> 2     return K.sum(K.square(y_true-y_pred),0)
    
    AttributeError: 'int' object has no attribute 'sum'
    

    我对Keras很新,任何帮助都会受到高度赞赏。请帮我解决这个问题,因为它已经困扰了我2天了。 提前谢谢。

0 个答案:

没有答案