【TensorFlow】常见处理tensor类型的数据的方法

import tensorflow as tf

创建tensor:

tensor数据类型包括int(整型),float(单精度浮点型),double(双精度浮点型),bool(布尔型),string(字符串)。

创建tensor数据:

tf.constant(data,dtype= )

data:上述数据类型的数据.

dtype:包括但不限于tf.float32,tf.int32,tf.double,tf.bool,string.

 转化数据类型(tensor->tensor):

tf.cast(tensor,dtype)

tensor:tensor类型的数据.

dtype:同上.

 将numpy或list类型的数据转化为tensor类型数据:

tf.convert_to_tensor(data,dtype)

data:numpy或list类型的数据.

dtype:同上.

 新建内容初始化成0的tensor类型数据:

tf.zeros(shape)

shape:数据形状.

例如:tf.zeros([2,2])

######

[ [ 0 , 0 ]

  [ 0 , 0 ] ]

######

 新建内容初始化成1的tensor类型数据:

tf.ones(shape)

用法同上tf.zeros.

 新建内容初始化成指定内容的tensor类型数据:

tf.fill(shape,data)

建立一个形状为shape,内容为data的tensor.

例如:tf.fill([2,2],3)

######

[ [ 3 , 3 ]

  [ 3,  3 ] ]

######

 将tensor转化为可求导对象:

tf.Variable(tensor)

tensor:tensor类型对象.

用于TensorFlow深度学习计算梯度时使用.

新建初始化内容为随机数的tensor(正态分布):

tf.random.normal(shape,mean=,stddev=)

shape:形状.

mean:均值.默认为0.

stddev:方差.默认为1.

 新建初始化内容为随机数的tensor(均匀分布):

tf.random.uniform(shape,minval=,maxval,dtype=)

shape:形状.

minval:最小值.

maxval:最大值.

dtype:数据类型,同上.

 随机打散内容:

tf.random.shuffle(data)

将data的内容打乱顺序.

tensor的属性: 

tensor.device

返回当前所在设备(cpu,gpu)的名字.

---------------------------------

tensor.gpu()

tensor.cpu()

返回一个与当前tensor值相同,但是是在 gpu(cpu)的tensor(即新建一个内容一样的tensor并指定所在的设备)

----------------------------------

tensor.numpy()

将当前tensor转化为numpy类型.

----------------------------------

tensor.shape

返回当前tensor的形状.

----------------------------------

tensor.ndim

返回当前tensor的维度.

-----------------------------------

tensor.rank

以tensor类型返回当前tensor的维度.

 tf.is_tensor(data):判断data是否为tensor类型,返回布尔型.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值