计算公式
需要计算:平方 矩阵内部和, 开方
# -*- coding: utf-8 -*-
import tensorflow as tf
import numpy as np
#两种定义初始数组的方法,但是注意一定用float,因为最后一步是开平方,整型会报错
# x1 = tf.constant([[1,2,3,4],[5,6,7,8],[9,10,11,12]],tf.float32)
# x2 = tf.constant([[5,6,7,8],[9,10,11,12],[1,2,3,4]],tf.float32)
x1 = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]],float)
x2 = np.array([[5,6,7,8],[9,10,11,12],[1,2,3,4]],float)
with tf.Session() as sess:
di = x2 - x1;
di1 = sess.run(tf.square(di))
print(di1)
di2 = sess.run(tf.reduce_sum(di1,1))
print(di2)
di3 = sess.run(tf.sqrt(di2))
print(di3)
输出:
dis:
[[16. 16. 16. 16.]
[16. 16. 16. 16.]
[64. 64. 64. 64.]]
dis1
[ 64. 64. 256.]
euclidean
[ 8. 8. 16.]
练手:余弦距离
# -*- coding: utf-8 -*-
import tensorflow as tf
x1 = 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)
x2 = 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:
di = tf.reduce_sum(tf.mul(x1, x2))
di1 = tf.reduce_sum(tf.mul(x1,x2),2)
di2 = tf.sqrt(tf.reduce_sum(tf.square(x1),2))#---------------
di3 = tf.sqrt(tf.reduce_sum(tf.square(x2), 2)) # ---------------
di4 = tf.div(tf.div(di1,di2),di3) # 除数的维度一定要一致,否则出错
a,b,c,d,e = sess.run([di1,di2,di3,di4,di])#----sess.run([])
print('a:', a) #可以看一下有个参数2是啥意思
print('e:', e) # 可以和上面比较一下(没有参数)
print('b:', b)
print('c:', c)
print('d:', d)
答案:
(‘a:’, array([[[ 22.],
[171.],
[442.]],
[[ 30.],
[174.],
[446.]]], dtype=float32))
(‘e:’, 1285.0)
(‘b:’, array([[[ 5.477225],
[13.190904],
[21.118713]],
[[ 5.477225],
[13.190906],
[21.118711]]], dtype=float32))
(‘c:’, array([[[ 5.477225],
[13.190904],
[21.118713]],
[[ 5.477225],
[13.190906],
[21.118711]]], dtype=float32))
(‘d:’, array([[[0.7333335],
[0.982759 ],
[0.9910313]],
[[1.0000002],
[1.0000001],
[1.0000001]]], dtype=float32))