哪一个更有效:tf.where或逐元素乘法?

时间:2017-10-09 10:56:39

标签: python tensorflow deep-learning keras loss

我实现了一个损失函数,该函数将使用由(M)组成的掩码张量0s and 1s来消除某些损失值,并给出预测(P)和地面真值{{1}张量。

所以,我有两种可能的方式:

元素乘法:

(G)

条件选择:

loss = K.sum(M * K.binary_crossentropy(G, P))

那么,在运行时间方面会更有效率吗?

1 个答案:

答案 0 :(得分:1)

我做了基准测试,很明显乘法比条件选择要好得多。

结果如下:

A chart is worth a thousand words..

一张图表胜过千言万语。

基准代码:

import keras.backend as K
import tensorflow as tf
import numpy as np
import sys
import time
import matplotlib.pyplot as plt


def elm(G, P, M):
        return K.sum(M * K.binary_crossentropy(G, P))

def cond(G, P, M, t):
        C = K.variable(np.zeros((t, t)))
        bin_ce = K.binary_crossentropy(G, P)
        return K.sum(tf.where(tf.equal(M, 1), bin_ce, C))


s = [100, 1000, 10000, 100000]
elms = []
conds = []

for t in s:
        print t
        t = int(t)
        # number of 1s in mask
        n = int(t/2)

        M = np.zeros((t,t))
        P = np.random.rand(t, t)
        G = np.random.rand(t, t)

        for i in range(n):
                r = np.random.randint(0, t)
                c = np.random.randint(0, t)
                M[r,c] = 1

        M = K.variable(M)
        P = K.variable(P)
        G = K.variable(G)

        start_time = time.time()
        elm(G, P, M)
        elms.append(time.time() - start_time)

        start_time = time.time()
        cond(G, P, M, t)
        conds.append(time.time() - start_time)

print elms
print conds

# create plot
fig, ax = plt.subplots()
index = np.arange(n_groups)
bar_width = 0.35
opacity = 0.8

rects1 = plt.bar(index, elms, bar_width,
                 alpha=opacity,
                 color='b',
                 label='Element-wise')

rects2 = plt.bar(index + bar_width, conds, bar_width,
                 alpha=opacity,
                 color='g',
                 label='Conditional')

plt.xlabel('Input tensor size')
plt.ylabel('Execution time (s)')
plt.title('')
plt.xticks(index + bar_width, ('100', '10e3', '10e4', '10e5'))
plt.legend()

plt.tight_layout()
plt.show()
相关问题