【问题标题】:Converting Tensor to Numpy Array - Custom Loss function In keras将张量转换为 Numpy 数组 - keras 中的自定义损失函数
【发布时间】:2018-03-21 13:38:38
【问题描述】:

我正在尝试在 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 

如果无法使用 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))

【问题讨论】:

    标签: python tensorflow keras


    【解决方案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 
    

    原答案

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

    所做的事情(在 keras/theano 中,这是一个与 keras 一起使用的后端)是张量的自动微分(例如tf.placeholder())。这不是全部,但此时您应该知道的是 tf /默认情况下,theano 在 tf.maxtf.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)
    

    抓取张量 x_true 的形状。 K.形状。计算常数上的比率可以保持为 就是这里

    NumberOfBars = len(x_true) 
    NumberOfHours = NumberOfBars/60
    

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

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

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

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

    tf.confusion_matrix

    CM = confusion_matrix(x_true, x_pred)
    

    接下来的计算是对常数的计算,因此基本上保持不变(条件为
    考虑到新的 API,必须进行任何更改)

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

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

    【讨论】:

    • 感谢您的帮助!我的预测数组是 (20000,2) 二进制数(1 和 0)。 x_true,x_pred 会是相同的格式吗?这些数字也会是二进制的吗?我检查了 x_true 的形状,它是 (2,)。
    • 是的,它们是相同的形状和二进制,不考虑示例的数量
    • 所以我尝试像这样创建我的面具:TradeIndex = K.tf.where( x_pred[:,1] == 0 ); x_true = K.tf.boolean_mask(x_true[:,0], TradeIndex) 但我收到一个错误:形状 (?,) 和 (?, 0) 不兼容
    • 查看有助于解决尺寸问题的更新示例
    • 在下面两行你不需要索引: x_true_tradeable = K.tf.boolean_mask(x_true[:,0], trade_index) x_pred_tradeable = K.tf.boolean_mask(x_pred[:,0] , trade_index)
    猜你喜欢
    • 2020-08-17
    • 2020-09-24
    • 2021-01-03
    • 1970-01-01
    • 2020-01-08
    • 2020-01-23
    • 1970-01-01
    • 2019-03-19
    • 2021-08-25
    相关资源
    最近更新 更多