在 tf.metrics.mean_cosine_distance 上使用哪个暗淡?

Which dim to use on tf.metrics.mean_cosine_distance?

我很困惑 dim 通常指的是 Tensorflow 中的哪个实际维度,但具体来说,在使用 tf.metrics.mean_cosine_distance

给出

x = [
   [1, 2, 3, 4, 5],
   [0, 2, 3, 4, 5],
]

我想按列计算距离。也就是说,哪个维度解析为(伪代码):

mean([
    cosine_distance(x[0][0], x[1][0]),
    cosine_distance(x[0][1], x[1][1]),
    cosine_distance(x[0][2], x[1][2]),
    cosine_distance(x[0][3], x[1][3]),
    cosine_distance(x[0][4], x[1][4]),
])

它在 dim 0 旁边供您输入 x。将输入 x 构建为 numpy 数组后,很直观地看到这一点。

In [49]: x_arr = np.array(x, dtype=np.float32)

In [50]: x_arr
Out[50]: 
array([[ 1.,  2.,  3.,  4.,  5.],
       [ 0.,  2.,  3.,  4.,  5.]], dtype=float32)


# compute (mean) cosine distance between `x[0]` & `x[1]`
# where `x[0]` can be considered as `labels`
# while `x[1]` can be considered as `predictions`
In [51]: cosine_dist_axis0 = tf.metrics.mean_cosine_distance(x_arr[0], x_arr[1], 0)

这个dim对应于NumPy术语中的名字axis。例如,一个简单的 sum 操作可以沿着 axis 0 完成,例如:

In [52]: x_arr
Out[52]: 
array([[ 1.,  2.,  3.,  4.,  5.],
       [ 0.,  2.,  3.,  4.,  5.]], dtype=float32)

In [53]: np.sum(x_arr, axis=0)
Out[53]: array([  1.,   4.,   6.,   8.,  10.], dtype=float32)

当您计算 tf.metrics.mean_cosine_distance 时,您实际上是在计算向量 labelspredictions 沿 [=] 的 余弦 距离15=] (然后取平均值)如果你的输入是 (n, ) 的形状,其中 n 是每个向量的长度(即 labels/prediction 中的条目数)

但是,如果您将 labelspredictions 作为 列向量 传递,则tf.metrics.mean_cosine_distance 必须沿 dim 1

计算

示例:

如果您的输入 labelprediction 是列向量,

# if your `label` is a column vector
In [66]: (x_arr[0])[:, None]
Out[66]: 
array([[ 1.],
       [ 2.],
       [ 3.],
       [ 4.],
       [ 5.]], dtype=float32)

# if your `prediction` is a column vector
In [67]: (x_arr[1])[:, None]
Out[67]: 
array([[ 0.],
       [ 2.],
       [ 3.],
       [ 4.],
       [ 5.]], dtype=float32)

然后,tf.metrics.mean_cosine_distance 必须沿着 dim 1

计算
# inputs
In [68]: labels = (x_arr[0])[:, None]
In [69]: predictions = (x_arr[1])[:, None]

# compute mean cosine distance between them
In [70]: cosine_dist_dim1 = tf.metrics.mean_cosine_distance(labels, predictions, 1)

这个tf.metrics.mean_cosine_distance或多或少与scipy.spatial.distance.cosine做同样的事情,但它也需要mean

对于您的示例案例:

In [77]: x
Out[77]: [[1, 2, 3, 4, 5], [0, 2, 3, 4, 5]]

In [78]: import scipy

In [79]: scipy.spatial.distance.cosine(x[0], x[1])
Out[79]: 0.009132