我很困惑哪个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
对应axis
于NumPy术语中的名称。例如,一个简单的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
,如果输入的形状为,则本质上是在计算向量之间以及沿向量的余弦距离(然后取平均值),其中每个向量的长度在哪里(即标签/预测中的条目数)labels
predictions
dim 0
(n, )
n
但是,如果您将labels
和predictions
作为列向量传递,则tf.metrics.mean_cosine_distance
必须沿着计算dim 1
范例:
如果您输入的label
和prediction
是列向量,
# 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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句