寒假学习进度4:tensorflow2.0张量的创建

tensor(张量):

数据类型:

1.直接创建向量:
tf.constant(张量内容,dtype=数据类型)
import tensorflow as tf
t=tf.constant([2,3],dtype=tf.int64)#创建一个一阶张量,dtype表示类型,为int64
print(t)
>>tf.Tensor([2 3], shape=(2,), dtype=int64)#shape中有几个数就代表几阶

2.用numpy数据类型转换为tensor类型

import tensorflow as tf
import numpy as np
a=np.arange(0,5)
t=tf.convert_to_tensor(a,dtype=tf.int64)#将一维数组转化为一维张量,a为
print(a,t)
>>[0 1 2 3 4] tf.Tensor([0 1 2 3 4], shape=(5,), dtype=int64)

3.创建特殊的张量。

(1)全为0的张量:维度如何表示:一维直接填一个数字,二维用[行,列],多维用[n,m,j,k……]

tf.zeros(3)#创建一维零张量:只需要指定张量内容中0的个数
tf.zeros([2,3])#二维
>><tf.Tensor: shape=(3,), dtype=float32, numpy=array([0., 0., 0.], dtype=float32)>
  <tf.Tensor: shape=(2, 3), dtype=float32, numpy=array([[0., 0., 0.],
                                                        [0., 0., 0.]], dtype=float32)>

(2)全为1的张量:维度同上

tf.ones(3)
>><tf.Tensor: shape=(3,), dtype=float32, numpy=array([1., 1., 1.], dtype=float32)>

(3)全为指定值的张量

tf.fill([2,3],1)
>><tf.Tensor: shape=(2, 3), dtype=int32, numpy=array([[1, 1, 1],
                                                      [1, 1, 1]])>

(4)生成正态分布随机数:tf.random.normal(维度,mean=均值,stddev=标准差)(默认均值为0,标准差为1)

tf.random.normal([3,3],mean=1,stddev=0.5)
>><tf.Tensor: shape=(3, 3), dtype=float32, numpy=array([[0.5939642 , 0.7801706 , 0.73448145],
                                                        [0.07946539, 1.8461295 , 1.7190137 ],
                                                        [0.7935035 , 1.1642232 , 0.63996214]], dtype=float32)>

(5)生成截断式正态分布的随机数(即生成的随机数位于(均值-2标准差,均值+2标准差)范围):tf.random.truncated_normal(维度,mean=均值,stddev=标准差)

tf.random.truncated_normal([3,3],mean=1,stddev=0.5)
>><tf.Tensor: shape=(3, 3), dtype=float32, numpy=array([[1.3027463 , 1.8570051 , 1.3586129 ],
                                                        [1.5800164 , 1.2975678 , 0.7345885 ],
                                                        [1.7934418 , 0.97875464, 1.0045136 ]], dtype=float32)>

(6)生成均匀分布的随机数:tf.random.uniform(维度,minval=最小值,maxval=最大值)

tf.random.uniform([3,3],minval=0,maxval=1)
>><tf.Tensor: shape=(3, 3), dtype=float32, numpy=array([[0.8119303 , 0.97470737, 0.5821942 ],
                                                        [0.07488775, 0.375291  , 0.68286586],
                                                        [0.23914921, 0.16803873, 0.78797734]], dtype=float32)>

 

 

 

 

 

 

 

 

 

 
 
 
 
 
 
 
 

posted @ 2021-01-08 11:11  yangqqq  阅读(214)  评论(0编辑  收藏  举报