首页 > 解决方案 > 如何使用 Keras 在张量的每个元素上使用 scipy 函数?

问题描述

我是 tensorflow 的新手,我希望将 scipy gamma 函数应用于现有的张量。当我尝试这个

from scipy.special import gamma
gamma_t = K.map_fn(lambda x:gamma(1.0 + 1.0 / x) ,b)

其中 b 是我得到的现有张量

TypeError: ufunc 'gamma' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

我该如何解决这个问题?

标签: pythontensorflowscipy

解决方案


您不能直接在 TensorFlow 张量上使用 SciPy 函数(或通常基于 NumPy 的函数)。您可以使用 来做到这一点tf.py_func,但通常最好的选择是仅使用 TensorFlow 操作。在这种情况下,Keras 后端抽象和 TensorFlow 都没有 gamma 函数,但 TensorFlow 有tf.lgamma,这是它的对数(准确地说,是绝对值的对数)。然后你可以得到你想要的:

gamma_t = K.map_fn(lambda x: K.exp(tf.lgamma(1.0 + 1.0 / x)), b)

PS:请注意,通常建议在操作 Keras 张量时仅使用后端函数,但由于这是一个相当具体的功能并且没有公开(另外,虽然 Theano 确实有 gamma 函数实现,但 CNTK 目前没有,所以不可能为所有后端实现它)。


推荐阅读