numpy 类型转换为 tensor

本文介绍如何在TensorFlow中计算两个张量之间的差值并求平均,通过将numpy数组转换为Tensor,利用tf.reduce_mean函数计算b*(a2-a1)的平均值,展示了tf.convert_to_tensor和tf.reduce_mean的用法。
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的数据类型

参考:

https://blog.youkuaiyun.com/ljs_a/article/details/78758116

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值