TensorFlow2.1入门笔记1
基础知识
张量(Tensor):多维数组(列表) 阶:张量的维数
0阶张量表示标量,例:a=1 2 3
1阶张量表示向量(一维数组),例:a=[1,2,3]
2阶张量表示矩阵(二维数组)可以有i行j列,每个元素可以用行号和列号共同索引到,例:a=[[1,2,3],[4,5,6],[7,8,9]]
判断张量是几阶的,看t=[[[[[…的括号有多少个
张量表示0阶到n阶的数组
TensorFlow的数据类型
tf.int,tf.float
tf.int32,tf.float32,tf.float64
tf.bool
tf.string
等
如何创建一个Tensor
直接创建
tf.constant(张量内容,dtype=数据类型(可选,本机默认是tf.int32))
例:
import tensorflow as tf
a = tf.constant([1, 5], dtype=tf.int64)
print("a:", a)
print("a.dtype:", a.dtype)
#运行结果
#a: tf.Tensor([1 5], shape=(2,), dtype=int64)
#a.dtype: <dtype: 'int64'>
#a.shape: (2,)
将numpy的数据类型转换为Tensor
tf.convert_to_tensor(数据名,dtype=数据类型(可选,本机默认是tf.int32))
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)
#运行结果:
# a: [0 1 2 3 4]
# # b: tf.Tensor([0 1 2 3 4], shape=(5,), dtype=int64)
创建全为某个值的张量:
全为0:tf.zeros(维度)
全为1:tf.ones(维度)
维度:一维直接写个数,二维[行,列],多维[n,m,j,k…]
全为指定值的张量:tf.fill(维度,指定值)
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)
#运行结果
# a: tf.Tensor([[0. 0. 0.][0. 0. 0.]], shape=(2, 3), dtype=float32)
# b: tf.Tensor([1. 1. 1. 1.], shape=(4,), dtype=float32)
# c: tf.Tensor([[9 9][9 9]], shape=(2, 2), dtype=int32)
生成指定维度符合正态分布的张量
tf.random.normal(维度,mean=均值,stddev=标准差)(默认mean=0,stddev=1)
要想数据更加集中可以生成截断式正态分布的随机数:
tf.random.truncated_normal(维度,mean=均值,stddev=标准差)
可以让数据在(μ-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