python - 如何使用 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''
我该如何解决这个问题?
解决方案
您不能直接在 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 目前没有,所以不可能为所有后端实现它)。
推荐阅读
- react-native - 文本和切换按钮的位置
- javascript - 请求队列
- swift - 如何在 ImagePicker 控制器的单元格类中设置图像
- azure-functions - 服务总线触发 Azure 功能 .net core 3.1
- ssl-certificate - 在防火墙后运行的 Ant Media Server 的代理设置
- ios - 如何在 Slider 中禁用最小值 0?
- c - 为什么只在声明后才为变量赋值
- office-js - Microsoft Teams 应用在发布时通过认证步骤需要多长时间?
- javascript - 如何自动关注列表的第一个元素
- c++ - std::decay 在 std::is_convertible 中是多余的吗?