首页 > 解决方案 > 使用 TensorFlow 之类的 Keras 进行 gpu 计算

问题描述

我想知道 Keras 是否可以用作 TensoFlow 的接口,仅在我的 GPU 上进行计算。

我直接在我的 GPU 上测试了 TF。但出于 ML 的目的,我开始使用 Keras,包括后端。我会发现在 Keras 中完成所有工作而不是使用两个工具会“很舒服”。

这也是一个好奇的问题。

我发现了一些像这样的例子:

http://christopher5106.github.io/deep/learning/2018/10/28/understand-batch-matrix-multiplication.html

然而,这个例子实际上并没有进行计算。它也没有得到输入数据。我在这里复制片段:'''

from keras import backend as K
a = K.ones((3,4))
b = K.ones((4,5))
c = K.dot(a, b)
print(c.shape)

'''

我只是想知道我是否可以从上面的这段代码中获得结果数字,以及如何获得?

谢谢,

米歇尔

标签: keras

解决方案


Keras 没有 Tensorflow 那样的渴望模式,它依赖于带有“占位符”的模型或函数来接收和输出数据。

所以,做这样的基本计算比 Tensorflow 稍微复杂一点。

因此,最用户友好的解决方案是创建一个具有Lambda一层的虚拟模型。(注意 Keras 坚持理解为批次维度的第一个维度,并要求输入和输出具有相同的批次大小)

def your_function_here(inputs):

    #if you have more than one tensor for the inputs, it's a list:
    input1, input2, input3 = inputs

    #if you don't have a batch, you should probably have a first dimension = 1 and get
    input1 = input1[0]

    #do your calculations here

    #if you used the batch_size=1 workaround as above, add this dimension again:
    output = K.expand_dims(output,0)

    return output

创建您的模型:

inputs = Input(input_shape)
#maybe inputs2 ....

outputs = Lambda(your_function_here)(list_of_inputs)
#maybe outputs2

model = Model(inputs, outputs)

并用它来预测结果:

print(model.predict(input_data))

推荐阅读