我正在研究内部使用 numpy.digitize() 的自定义损失函数。一组参数的损失最小化,这些参数是数字化方法中使用的 bins 值。为了使用tensorflow 优化器,我想知道tensorflow 中是否有等效的digitize 实现?如果没有,是否有实现解决方法的好方法?
这里是一个 numpy 版本:
def fom_func(b, n):
np.where((b > 0) & (n > 0), np.sqrt(2*(n*np.log(np.divide(n,b)) + b - n)),0)
def loss(param, X, y):
param = np.sort(np.asarray(param))
nbins = param.shape[0]
score = 0
y_pred = np.digitize(X, param)
for c in np.arange(nbins):
b = np.where((y==0) & (y_pred==c), 1, 0).sum()
n = np.where((y_pred==c), 1, 0).sum()
score += fom_func(b,n)**2
return -np.sqrt(score)
请您参考如下方法:
np.digitize 方法的等价物在 TensorFlow 中称为 bucketize,引用自 this api doc :
Bucketizes 'input' based on 'boundaries'.
Summary
For example, if the inputs are boundaries = [0, 10, 100] input = [[-5, 10000] [150, 10] [5, 100]]
then the output will be output = [[0, 3] [3, 2] [1, 3]]
Arguments:
scope: A Scope object input: Any shape of Tensor contains with int or float type. boundaries: A sorted list of floats gives the boundary of the buckets. Returns:
Output: Same shape with 'input', each value of input replaced with bucket index.
(numpy) Equivalent to np.digitize.
我不确定为什么,但此方法隐藏在 TensorFlow 中(请参阅 hidden_ops.txt file)。因此,即使您可以通过以下方式导入它,我也不会指望它:
from tensorflow.python.ops import math_ops
math_ops._bucketize
