如何使用tensorflow后端来交互张量的每个元素

时间:2017-03-19 19:04:58

标签: python tensorflow backend keras

我是Keras和Tensorflow的新手。这可能是一些基本问题。我正在使用Tensorflow后端在Keras中编写自己的损失函数。在我的损失函数中,我想迭代y_pred和y_true张量中的每个元素。我尝试了下面显示的代码,但是发生了这个错误。那么有人能告诉我如何处理这个问题吗? 这是我的损失函数代码:

from keras import backend as K
def cost_estimation(y_true, y_pred):
    print(y_true[1])
    for k in range(10):
        d=K.log(1+K.exp((int(bool(y_true[k]==min(y_true)))*2-1)*(y_pred[k]-y_true[k])))
        cost=cost+d
    return cost

这是错误:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-5-2669c733fd5f> in <module>()
    130 model.compile(loss=cost_estimation,
    131               optimizer='Adam',
--> 132               metrics=['accuracy'])
    133 
    134 model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs,

/usr/local/lib/python2.7/dist-packages/keras/models.pyc in compile(self, optimizer, loss, metrics, sample_weight_mode, **kwargs)
    764                            metrics=metrics,
    765                            sample_weight_mode=sample_weight_mode,
--> 766                            **kwargs)
    767         self.optimizer = self.model.optimizer
    768         self.loss = self.model.loss

/usr/local/lib/python2.7/dist-packages/keras/engine/training.pyc in compile(self, optimizer, loss, metrics, loss_weights, sample_weight_mode, **kwargs)
    897             loss_weight = loss_weights_list[i]
    898             output_loss = weighted_loss(y_true, y_pred,
--> 899                                         sample_weight, mask)
    900             if len(self.outputs) > 1:
    901                 self.metrics_tensors.append(output_loss)

/usr/local/lib/python2.7/dist-packages/keras/engine/training.pyc in weighted(y_true, y_pred, weights, mask)
    428         """
    429         # score_array has ndim >= 2
--> 430         score_array = fn(y_true, y_pred)
    431         if mask is not None:
    432             # Cast the mask to floatX to avoid float64 upcasting in theano

<ipython-input-4-e74322d8ebbf> in cost_estimation(y_true, y_pred)
      8     print(y_pred[43481])
      9     for k in range(10):
---> 10         d=K.log(1+K.exp((int(bool(y_true[k]==min(y_true)))*2-1)*(y_pred[k]-y_true[k])))
     11         cost=cost+d
     12     return  K.mean(d)

/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.pyc in __iter__(self)
    508       TypeError: when invoked.
    509     """
--> 510     raise TypeError("'Tensor' object is not iterable.")
    511 
    512   def __bool__(self):

TypeError: 'Tensor' object is not iterable.

0 个答案:

没有答案