将张量转换为Numpy数组 - 自定义丢失功能在keras中

Aar*_*aac 5 python keras tensorflow

我正在尝试在keras中构建自定义丢失函数.不幸的是,我对张量流很少了解.有没有办法我可以将传入的张量转换成一个numpy数组,这样我可以计算我的损失函数?

这是我的功能:

def getBalance(x_true, x_pred):

    x_true = np.round(x_true)
    x_pred = np.round(x_pred)

    NumberOfBars = len(x_true)
    NumberOfHours = NumberOfBars/60

    TradeIndex = np.where( x_pred[:,1] == 0 )[0]

    ##remove predictions that are not tradable
    x_true = np.delete(x_true[:,0], TradeIndex)
    x_pred = np.delete(x_pred[:,0], TradeIndex)

    CM = confusion_matrix(x_true, x_pred)

    correctPredictions = CM[0,0]+CM[1,1]
    wrongPredictions = CM[1,0]+CM[0,1]
    TotalTrades = correctPredictions+wrongPredictions
    Accuracy = (correctPredictions/TotalTrades)*100

    return Accuracy 
Run Code Online (Sandbox Code Playgroud)

如果不能使用numpy数组,那么用tensorflow计算该函数的最佳方法是什么?任何方向都将不胜感激,谢谢!

编辑1: 以下是我的模型的一些细节.我正在使用LSTM网络,辍学率很高.输入是多变量多时间步骤.输出是二进制数字的二维数组(20000,2)

model = Sequential()

model.add(Dropout(0.4, input_shape=(train_input_data_NN.shape[1], train_input_data_NN.shape[2])))

model.add(LSTM(30, dropout=0.4, recurrent_dropout=0.4))

model.add(Dense(2))

model.compile(loss='getBalance', optimizer='adam')

history = model.fit(train_input_data_NN, outputs_NN, epochs=50,  batch_size=64, verbose=1, validation_data=(test_input_data_NN, outputs_NN_test))
Run Code Online (Sandbox Code Playgroud)

ors*_*ady 1

编辑:1 这是一个未经测试的替代:

(擅自规范变量名称)

def get_balance(x_true, x_pred):

    x_true = K.tf.round(x_true)
    x_pred = K.tf.round(x_pred)

    # didnt see the  need for these
    # NumberOfBars = (x_true)
    # NumberOfHours = NumberOfBars/60

    trade_index = K.tf.not_equal(x_pred[:,1], 0 )

    ##remove predictions that are not tradable
    x_true_tradeable = K.tf.boolean_mask(x_true[:,0], trade_index)
    x_pred_tradeable = K.tf.boolean_mask(x_pred[:,0], trade_index)

    cm = K.tf.confusion_matrix(x_true_tradeable, x_pred_tradeable)

    correct_predictions = cm[0,0]+cm[1,1]
    wrong_predictions = cm[1,0]+cm[0,1]
    total_trades = correction_predictions + wrong_predictions
    accuracy = (correct_predictions/total_trades)*100

    return accuracy 
Run Code Online (Sandbox Code Playgroud)

原答案

欢迎来到SO。正如您可能知道的,我们需要计算损失函数的梯度。我们无法在 numpy 数组上正确计算梯度(它们只是常量)。

所做的(在 keras/theano 中,这是与 keras 一起使用的后端)是对张量进行自动微分(例如tf.placeholder())。这不是整个故事,但此时您应该知道的是 tf / theano 默认为我们提供梯度诸如tf.max,之类的运算符tf.sum

这对您来说意味着张量 (y_truey_pred) 上的所有操作都应该重写为使用 tf / theano 运算符。

我将评论我认为会重写的内容,您可以相应地替换并测试。

请参阅 tf.round 用作K.tf.round其中 K 是对导入为的 keras 后端的引用 import keras.backend as K

x_true = np.round(x_true)  
x_pred = np.round(x_pred)
Run Code Online (Sandbox Code Playgroud)

获取张量 x_true 的形状。K.形状。计算与常数的比率可以保持如下所示

NumberOfBars = len(x_true) 
NumberOfHours = NumberOfBars/60
Run Code Online (Sandbox Code Playgroud)

参见tf.where用作K.tf.where

TradeIndex = np.where( x_pred[:,1] == 0 )[0] 
Run Code Online (Sandbox Code Playgroud)

您可以使用条件屏蔽张量而不是删除 - 请参阅屏蔽

##remove predictions that are not tradable
x_true = np.delete(x_true[:,0], TradeIndex) 
x_pred = np.delete(x_pred[:,0], TradeIndex)
Run Code Online (Sandbox Code Playgroud)

tf.confusion_matrix

CM = confusion_matrix(x_true, x_pred)
Run Code Online (Sandbox Code Playgroud)

接下来的计算是对常量的计算,因此本质上保持不变(取决于
新 API 必须做出的任何更改)

希望我可以用运行的有效替换来更新这个答案。但我希望这能走上正确的道路。

关于编码风格的建议:我看到您在代码中使用了三种版本的变量命名,选择一种并坚持使用。