gpt4 book ai didi

python - 将张量转换为 Numpy 数组 - keras 中的自定义损失函数

转载 作者:太空狗 更新时间:2023-10-30 01:31:47 24 4
gpt4 key购买 nike

我正在尝试在 keras 中构建自定义损失函数。不幸的是我对 tensorflow 知之甚少。有没有一种方法可以将传入的张量转换为 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))

最佳答案

编辑: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 一起使用的后端)是对 Tensors 的自动微分(例如 tf.placeholder())。这不是故事的全部,而是你在这一点上应该知道的是,tf/theano 默认为我们提供了 tf.maxtf.sum 等运算符的梯度。

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

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

请参阅 tf.round used as K.tf.round 其中 K 是对导入为的 keras 后端的引用将 keras.backend 导入为 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 必须做出的任何更改)

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

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

关于python - 将张量转换为 Numpy 数组 - keras 中的自定义损失函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49349918/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com