2017-04-11       个评论
我要投稿

1，Euclidean distance

```import tensorflow as tf

x3 = tf.constant([[[[1], [2], [3], [4]],

[[5], [6], [7], [8]],

[[9], [10], [11], [12]]],

[[[1], [2], [3], [4]],

[[5], [6], [7], [8]],

[[9], [10], [11], [12]]]], tf.float32)

x4 = tf.constant([[[[3], [4], [1], [2]],

[[5], [7], [8], [6]],

[[9], [12], [11], [10]]],

[[[1], [2], [3], [4]],

[[5], [6], [7], [8]],

[[9], [10], [11], [12]]]], tf.float32)

with tf.Session() as sess:

dis = sess.run(tf.square(x3-x4))

dis1 = sess.run(tf.reduce_sum(tf.square(x3-x4), 2))

euclidean = sess.run(tf.sqrt(tf.reduce_sum(tf.square(x3-x4), 2)))

print dis, dis1, euclidean```

```dis：

[[[[ 4.]

[ 4.]

[ 4.]

[ 4.]]

[[ 0.]

[ 1.]

[ 1.]

[ 4.]]

[[ 0.]

[ 4.]

[ 0.]

[ 4.]]]

[[[ 0.]

[ 0.]

[ 0.]

[ 0.]]

[[ 0.]

[ 0.]

[ 0.]

[ 0.]]

[[ 0.]

[ 0.]

[ 0.]

[ 0.]]]]

dis1：

[[[ 16.]

[ 6.]

[ 8.]]

[[ 0.]

[ 0.]

[ 0.]]]

Euclidean：

[[[ 3.99999976]

[ 2.44948959]

[ 2.82842684]]

[[ 0. ]

[ 0. ]

[ 0. ]]]```

`euclidean = tf.sqrt(tf.reduce_sum(tf.square(x3-x4), 2))`

```with tf.Session() as sess:

#求模

x3_norm = tf.sqrt(tf.reduce_sum(tf.square(x3), axis=2))

x4_norm = tf.sqrt(tf.reduce_sum(tf.square(x4), axis=2))

#内积

x3_x4 = tf.reduce_sum(tf.multiply(x3, x4), axis=2)

cosin = x3_x4 / (x3_norm * x4_norm)

cosin1 = tf.divide(x3_x4, tf.multiply(x3_norm, x4_norm))

a, b, c, d, e = sess.run([x3_norm, x4_norm, x3_x4, cosin, cosin1])

print a, b, c, d, e
```

x3_norm:

```[[[ 5.47722483]

[ 13.19090366]

[ 21.11871338]]

[[ 5.47722483]

[ 13.19090557]

[ 21.11871147]]]

x4_norm:

[[[ 5.47722483]

[ 13.19090366]

[ 21.11871338]]

[[ 5.47722483]

[ 13.19090557]

[ 21.11871147]]]

x3_x4:

[[[ 22.]

[ 171.]

[ 442.]]

[[ 30.]

[ 174.]

[ 446.]]]

cosin:

[[[ 0.73333353]

[ 0.98275894]

[ 0.99103123]]

[[ 1.00000024]

[ 1.00000012]

[ 1.00000012]]]

cosin1:

[[[ 0.73333353]

[ 0.98275894]

[ 0.99103123]]

[[ 1.00000024]

[ 1.00000012]

[ 1.00000012]]]```

Attention矩阵计算

`def input_attention(x1, x2):`

#将每个句子按单词进行切分

```x1_unstack = tf.unstack(x1, axis=1)

x2_unstack = tf.unstack(x2, axis=1)

D = []

for i in range(len(x1_unstack)):

d = []

for j in range(len(x2_unstack)):

#计算两个单词之间的相似度距离

dis = tf.sqrt(tf.reduce_sum(tf.square(x1_unstack[i]- x2_unstack[j]), axis=1))

d.append(dis)

D.append(d)

D1 = tf.reshape(D, [2, 3, 3])

D2 = tf.reshape(tf.transpose(D, perm=[2, 0, 1, 3]), [2,3,3])

return D1, D2

with tf.Session() as sess:

A, A1 = input_attention(x3, x4)

a, a1 = sess.run([A, A1])

print a, a1```

`x1_unstack = tf.unstack(x1, axis=1)`

```dis = tf.sqrt(tf.reduce_sum(tf.square(x1_unstack[i]- x2_unstack[j]), axis=1))

A:

[[[ 4. 0. 8.36660004]

[ 8. 16.24807739 16. ]

[ 8.94427204 8. 2.44948983]]

[[ 0. 8.48528099 8. ]

[ 16.4924221 16. 8.36660004]

[ 8. 2.82842708 0. ]]]

A1:

[[[ 4. 8.36660004 16.24807739]

[ 8.94427204 2.44948983 8.48528099]

[ 16.4924221 8.36660004 2.82842708]]

[[ 0. 8. 16. ]

[ 8. 0. 8. ]

[ 16. 8. 0. ]]]```