2015-11-22 14 views
9

あなたがあなた自身の目的関数を作成する方法があり、多くの目的関数はKerasでカスタム目的関数を作成するには?

Keras here.である。しかし、私は非常に基本的な目的関数を作成しようとしましたが、それはエラーを与え、私はの大きさを知る方法はありません実行時に関数に渡されるパラメーター。

def loss(y_true,y_pred): 
    loss = T.vector('float64') 
    for i in range(1): 
     flag = True 
     for j in range(y_true.ndim): 
      if(y_true[i][j] == y_pred[i][j]): 
       flag = False 
     if(flag): 
      loss = loss + 1.0 
    loss /= y_true.shape[0] 
    print loss.type 
    print y_true.shape[0] 
    return loss 

私はそれは、コストや損失がスカラーでなければならない機能に戻ったが、言う

model.compile(loss=loss, optimizer=ada) 
    File "/usr/local/lib/python2.7/dist-packages/Keras-0.0.1-py2.7.egg/keras/models.py", line 75, in compile 
    updates = self.optimizer.get_updates(self.params, self.regularizers, self.constraints, train_loss) 
    File "/usr/local/lib/python2.7/dist-packages/Keras-0.0.1-py2.7.egg/keras/optimizers.py", line 113, in get_updates 
    grads = self.get_gradients(cost, params, regularizers) 
    File "/usr/local/lib/python2.7/dist-packages/Keras-0.0.1-py2.7.egg/keras/optimizers.py", line 23, in get_gradients 
    grads = T.grad(cost, params) 
    File "/usr/local/lib/python2.7/dist-packages/theano/gradient.py", line 432, in grad 
    raise TypeError("cost must be a scalar.") 
TypeError: cost must be a scalar. 

2つの矛盾エラーを取得しています私は 損失= T.vector(」から2行目を変更した場合float64 ')

に損失= T.scalar(' のfloat64' )

このエラーを示します
model.compile(loss=loss, optimizer=ada) 
    File "/usr/local/lib/python2.7/dist-packages/Keras-0.0.1-py2.7.egg/keras/models.py", line 75, in compile 
    updates = self.optimizer.get_updates(self.params, self.regularizers, self.constraints, train_loss) 
    File "/usr/local/lib/python2.7/dist-packages/Keras-0.0.1-py2.7.egg/keras/optimizers.py", line 113, in get_updates 
    grads = self.get_gradients(cost, params, regularizers) 
    File "/usr/local/lib/python2.7/dist-packages/Keras-0.0.1-py2.7.egg/keras/optimizers.py", line 23, in get_gradients 
    grads = T.grad(cost, params) 
    File "/usr/local/lib/python2.7/dist-packages/theano/gradient.py", line 529, in grad 
    handle_disconnected(elem) 
    File "/usr/local/lib/python2.7/dist-packages/theano/gradient.py", line 516, in handle_disconnected 
    raise DisconnectedInputError(message) 
theano.gradient.DisconnectedInputError: grad method was asked to compute the gradient with respect to a variable that is not part of the computational graph of the cost, or is used only by a non-differentiable operator: <TensorType(float64, matrix)> 
+2

あなたの損失、すなわち、それはこれらのパラメータにテンソル操作の用語で表現されなければならない、 '' 'y_true'''と' 'y_pred'''のTheano関数であるべきです。 –

答えて

0

(固定回答)それはKerasバックエンド呼び出して行うための簡単な方法:次に

import keras.backend as K 

def custom_loss(y_true,y_pred): 
    return K.mean((y_true - y_pred)**2) 

:ここ

model.compile(loss='mean_squared_error', optimizer=sgd,metrics = ['accuracy']) 
+0

それはちょうど通常の損失ではなく、カスタム損失関数 – Kev1n91

11

に等しい私の小さな断片です

model.compile(loss=custom_loss, optimizer=sgd,metrics = ['accuracy']) 

新しい損失関数を書き、使用する前にテストしてください:

ここで
import numpy as np 

from keras import backend as K 

_EPSILON = K.epsilon() 

def _loss_tensor(y_true, y_pred): 
    y_pred = K.clip(y_pred, _EPSILON, 1.0-_EPSILON) 
    out = -(y_true * K.log(y_pred) + (1.0 - y_true) * K.log(1.0 - y_pred)) 
    return K.mean(out, axis=-1) 

def _loss_np(y_true, y_pred): 
    y_pred = np.clip(y_pred, _EPSILON, 1.0-_EPSILON) 
    out = -(y_true * np.log(y_pred) + (1.0 - y_true) * np.log(1.0 - y_pred)) 
    return np.mean(out, axis=-1) 

def check_loss(_shape): 
    if _shape == '2d': 
     shape = (6, 7) 
    elif _shape == '3d': 
     shape = (5, 6, 7) 
    elif _shape == '4d': 
     shape = (8, 5, 6, 7) 
    elif _shape == '5d': 
     shape = (9, 8, 5, 6, 7) 

    y_a = np.random.random(shape) 
    y_b = np.random.random(shape) 

    out1 = K.eval(_loss_tensor(K.variable(y_a), K.variable(y_b))) 
    out2 = _loss_np(y_a, y_b) 

    assert out1.shape == out2.shape 
    assert out1.shape == shape[:-1] 
    print np.linalg.norm(out1) 
    print np.linalg.norm(out2) 
    print np.linalg.norm(out1-out2) 


def test_loss(): 
    shape_list = ['2d', '3d', '4d', '5d'] 
    for _shape in shape_list: 
     check_loss(_shape) 
     print '======================' 

if __name__ == '__main__': 
    test_loss() 

別のテンソル版(_loss_tensorを)あなたは私がbinary_crossentropy損失をテストしてい見ることができ、そして2つの別々の損失は1つのnumpyのバージョン(_loss_np)、定義したよう注意:あなたがちょうどそのkeras機能を使用する場合、それは動作しますTheanoとTensorflowの両方を使用していますが、それらのいずれかに依存している場合は、K.theano.tensor.functionまたはK.tf.functionで参照することもできます。

後で出力の形状と出力のL2ノルム(ほぼ等しい)と差のL2ノルム(0になるはず)

損失関数が適切に働いていることが分かったら使用することができ:

model.compile(loss=_loss_tensor, optimizer=sgd) 
+0

あなたは支配する!テスト駆動型開発のための+1 - 機械学習にとっては何も良いことはありません。 – johndodo

+0

ありがとう@johndodo ... – indraforyou

関連する問題