TensorFlow基础(2)创建张量

TensorFlow基础(2)创建张量

# 创建张量
tf.constant(
	value,  # 数字、list、ndarray
	dtype,  # 数据类型
	shape  # 形状
)
# 是对ndarray的封装
>>> tf.constant([[1,2], [3,4]])
<tf.Tensor: shape=(2, 2), dtype=int32, numpy=
array([[1, 2],
       [3, 4]])> 
# 可转为ndarray
>>> a = tf.constant([[1,2], [3,4]])
>>> a.numpy()
array([[1, 2],
       [3, 4]])
>>> type(a)
<class 'tensorflow.python.framework.ops.EagerTensor'>
# 转换
>>> a = tf.convert_to_tensor([[1,2], [3,4]])
>>> a.numpy()
array([[1, 2],
       [3, 4]])
>>> type(a)
<class 'tensorflow.python.framework.ops.EagerTensor'>

类型转换

# 可转为ndarray
a = tf.constant([[1, 2], [3, 4]])
b = tf.cast(a, dtype=tf.float32)
a.dtype  # tf.int32
b.dtype  # tf.float32
# 注意:高精度到低精度时会产生溢出

# 布尔 => 整型
True1
False0
# 整型 => 布尔0True 
0False 

# 判断张量
tf.is_tensor(a)  # True

自动、随机设值

tf.zeros(shape, dtype=tf.float32)  # 全0
tf.ones(shape, dtype=tf.float32)  # 全1
tf.fill(dims, value)  # 元素值都相同的tensor
tf.fill([2, 3], 9)
tf.constant(9, shape=[2,3])

# 随机张量
tf.random.normal(
	shape, 
	mean,  # 均值
	stddev,  # 标准差
	dtype
)
tf.random.normal([3, 3, 3], mean=0.0, stddev=2.0)
# 截断正态分布,2倍标准差以外的会被去掉
ft.random.truncated_normal(shape, mean, stddev, dtype)

tf.random.set_seed(8)  # 随机种子
tf.random.normal([2, 2])

# 均匀分布,前闭后开
tf.random.uniform(shape, minval, maxval, dtype)

# 随机打乱(只打乱第0维度)
tf.random.shuffle(tensor)

# range,默认从0开始,不包括结束数字,delta默认为1
tf.range(start, limit, delta=1, dtype)

属性

  • ndim
  • shape
  • dtype
a = tf.constant([[1, 2], [3, 4]])
a.ndim  # tf.rank(a)
a.shape  # tf.shape(a)
a.dtype  # 类型
tf.size(a)  # 元素总数

注意:

  • 在TensorFlow中,所有的运算都是在张量之间进行的
  • NumPy数组仅仅是作为输入和输出来使用
  • 张量可以运行于CPU,GPU
  • NumPy只能运行于CPU
  • 当Tensor在CPU中运行时,其NumPy与Tensor共用同一段内存
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值