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

时间:2018-01-30 19:32:30

标签: python tensorflow machine-learning deep-learning linear-algebra

我很困惑哪个<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="root"></div>一般指的是Tensorflow中的哪个实际维度,但具体来说,当使用tf.metrics.mean_cosine_distance

鉴于

dim

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

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

1 个答案:

答案 0 :(得分:3)

您的输入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时,你实际上是计算labels之间的向量predictionsdim 0之间的余弦距离(和如果您的输入形状为(n, ),其中n是每个向量的长度(即标签/预测中的条目数),则采用均值)

但是,如果您将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