tensorflow2.0 常用API

一、创建变(常)量

 1,tf.constant()

1 import tensorflow as tf
2 tf.constant(
3     value,    #表示一个值或一个列表
4     dtype=None,    #数据类型  tf.int32, tf.int64,tf.float32, tf.float64
5     shape=None,   #量的“形状”,即维数以及每一维的大小
6     name='Const',   #任何内容
7     verify_shape=False  #verify_shape默认为False
8 )
 1 import tensorflow as tf
 2 a = tf.constant([1, 5], dtype=tf.int64)
 3 b= tf.constant(3, dtype=tf.int64)
 4 print("a:", a)
 5 print("a.dtype:", a.dtype)
 6 print("a.shape:", a.shape)
 7 print("*"*100)
 8 print("b:", b)
 9 print("b.dtype:", b.dtype)
10 print("b.shape:", b.shape)
a: tf.Tensor([1 5], shape=(2,), dtype=int64)
a.dtype: <dtype: 'int64'>
a.shape: (2,)
****************************************************************************************************
b: tf.Tensor(3, shape=(), dtype=int64)
b.dtype: <dtype: 'int64'>
b.shape: ()

2,常量

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

3,tf.truncated_normal和tf.random_noraml的区别 

tf.truncated_normal(shape, mean=0.0, stddev=1.0, dtype=tf.float32, seed=None, name=None) 

shape是张量维度,mean是正态分布是均值,stddev是正态分布的标准差;

它是从截断的正态分布中输出随机值,虽然同样是输出正态分布,但是它生成的值是在距离均值两个标准差范围之内的,也就是说,在tf.truncated_normal中如果x的取值在区间(μ-2σ,μ+2σ)之外则重新进行选择。这样保证了生成的值都在均值附近。

tf.random_normal(shape, mean=0.0, stddev=1.0, dtype=tf.float32, seed=None, name=None)

参数设置和上一个函数是一样的;而tf.random_normal是没有要求一定在(μ-2σ,μ+2σ)之内的

 

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

 tf.random.uniform()

1 import tensorflow as tf
2 #返回2*2的矩阵,产生于min和max之间,产生的值是均匀分布的。
3 f = tf.random.uniform([2, 2], minval=0, maxval=1)
4 print("f:", f)

变量转换 

1 import tensorflow as tf
2 import numpy as np
3 
4 a = np.arange(0, 5)
5 a_=(1,2,3,4,5)
6 #数组转换为张量
7 b = tf.convert_to_tensor(a, dtype=tf.int64)#a_也可以
8 print("a:", a)
9 print("b:", b) 
a: [0 1 2 3 4]
b: tf.Tensor([0 1 2 3 4], shape=(5,), dtype=int64)

tf.cast()函数的作用是张量数据类型的转换

cast(x, dtype, name=None)

第一个参数 x:   待转换的数据(张量)

第二个参数 dtype: 目标数据类型

第三个参数 name: 可选参数,定义操作的名称

1 x1 = tf.constant([1., 2., 3.], dtype=tf.float64)
2 print("x1:", x1)
3 x2 = tf.cast(x1, tf.int32)
4 print("x2", x2)
5 print("minimum of x2:", tf.reduce_min(x2))
6 print("maxmum of x2:", tf.reduce_max(x2))
原文地址:https://www.cnblogs.com/hsy1941/p/13801670.html