版本:Tensorflow 2.0
Tensorflow——深度学习框架,其他深度学习框架:PyTorch、Caffe
Tensor(张量)+flow(流动)
张量:多维的数组或列表,0阶(维)张量是标量(scalar)、1阶向量(vector)、2阶矩阵(matrix)、3阶张量、n阶张量...
导入框架:import tensorflow as tf
tensor数据类型:浮点型(tf.float16, tf.float32, tf.float64)、整型(tf.int16, tf.int32, tf.int64)、字符串(tf.string)、布尔型(tf.bool)
常量的创建:tf.constant(value, dtype=None, shape=None, name='')
import tensorflow as tf
string = tf.constant(value="Hello TensorFlow2", dtype=tf.string)
print(string)
判断是否为张量:tf.is_tensor()
张量的一些属性: 维度(ndim)、 形状(shape)
张量的类型转换:tf.cast(x, dtype name=None) # cast 铸造,变换形态
张量的形状转换:tf.reshape(tensor, shape, name=None)
变量的创建:tf.Variable(initial_value=None, trainable=True)
trainable:是否可以更新
神经网络中大部分数据是不需要变化的,只需要使用tf.constant()创建,只有少数参数需要改变需使用tf.Variable()创建
创建随机正态分布张量:tf.random.normal()
创建全零张量:tf.zeros(shape, dtype, name)
创建全1张量:tf.ones(shape, dtype, name)
创建指定数值填充的张量:tf.fill(dims, value, name)
操作
tf.math.add(x,y) 求x+y,可用于多维张量
tf.math.multiply(x,y) 乘
其他:substract 减、divide 除、square 平方、pow 幂、sqrt 开方、matmul 矩阵相乘
自动求导:tf.GradientTape()
import tensorflow as tf
x = Variable(initial_value=3.)
with tf.GradientTape() as tape:
y = 4 * tf.pow(x=x, y=3)
y_grad = tape.gradient(y, x)
print(y, y_grad)