四时宝库

程序员的知识宝库

生成张量(Tensor)(张量转换)

1.3 生成张量

张量就是多维数组,张量的阶就是张量的维度。标量就是0阶张量,例如 s=1, s=2 and s=3. 它代表一个单独的数字。向量就是1阶张量。比如v=[1,2,3]。显而易见,2阶张量就是矩阵例如m=[[1,2,3],[4,5,6],[7,8,9]]。当张量的维度大于2时我们没有特意地取名而是直呼n维张量。我们可以判断张量的维度通过数' = '后面有多少个' [ '。TensorFlow有tf.int, tf.float, tf.bool 以及tf.string等数据类型。我们将编码演示如何生成张量。

import tensorflow as tf
a = tf.constant([1, 5], dtype=tf.int64)
print("a:", a)# 输出张量的所有信息
print("a.dtype:", a.dtype)#输出数据类型
print("a.shape:", a.shape)#多少个数字被','分开代表多少维张量

Most of the time the data information is given by numpy. We can use tf.convert_to_tensor change it into tensor.

import tensorflow as tf
import numpy as np
a = np.arange(0, 5)
b = tf.convert_to_tensor(a, dtype=tf.int64)
print("a:", a)
print("b:", b)

使用tf.zero(维度)生成一个全为0的张量,用tf.one(维度)生成全为1的张量。用tf.fill(维度,n)生成全为n的张量。如果维度唯一,只需要在维度位置输入个数,否则用[n,m,...]填入维度。

import tensorflow as tf
a = tf.zeros([2, 3])
b = tf.ones(4)
c = tf.fill([2, 2], 9)
print("a:", a)
print("b:", b)
print("c:", c)

tf.random.normal(维度, 均值 , 标准差)可以用来生成符合正态分布的随机数。函数tf.random.truncated_normal(维度,均值,标准差)可以生成取值在μ-2σ之间μ+2σ的随机数

import tensorflow as tf
d = tf.random.normal([2, 2], mean=0.5, stddev=1)
print("d:", d)
e = tf.random.truncated_normal([2, 2], mean=0.5, stddev=1)
print("e:", e)

tf.random.uniform(维度,最小值,最大值) 可以生成符合均匀分布的随机数。

import tensorflow as tf
f = tf.random.uniform([2, 2], minval=0, maxval=1)
print("f:", f)

发表评论:

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言
    友情链接