import tensorflow as tf
import numpy as np
a1 = np.array([[1,2,3,4,5],[2,3,4,5,6]])
a2 = np.array([[3,4,5,6,7],[3,4,5,8,9]])
b = np.array([[0,1,1,0,0],[1,0,1,0,1]])
a1 = tf.convert_to_tensor(a1, dtype = tf.float32)
a2 = tf.convert_to_tensor(a2, dtype = tf.float32)
b = tf.convert_to_tensor(b, dtype = tf.float32)
loss = tf.reduce_mean(b*tf.subtract(a2, a1))
with tf.Session() as sess:
t = sess.run(loss)
print(t)
上面的代码是计算b*(a2-a1)的结果的平均值。其中将numpy类型转换为 tensor需要用到tf.convert_to_tensor(),需要在括号里写上转换的类型,否则会默认为int64型,当然也可以使用tf.cast(x,tf.float32)来进行数据的转换。
tf.reduce_mean()#计算平均值
tf.reduce_sum()#计算总值
tf.convert_to_tensor()#转换数据到tensor
tf.cast(x, dtype)#转换tensor的数据类型
参考: