tensorflow漫漫学习之路自此开始。
学习tensorflow之前,需要了解tensorflow内部数据的表现形式,tensorflow采用张量(Tensor)作为数据的基本单位,tensorflow中的张量可以表示为标量、一维数组、二维矩阵等。如下所示:
import tensorflow as tf #定义一个标量 random_float=tf.random.uniform(shape=()) print('标量',random_float) #定义一个有两个元素的零向量 zero_vec=tf.zeros(shape=(2)) print('向量',zero_vec) #定义两个2*2的常量矩阵 A=tf.constant([[2.,4.],[1.,3.]]) B=tf.constant([[2.3,4.1],[1.3,3.5]]) print('矩阵',A)
输出如下所示:
标量 tf.Tensor(0.031272292, shape=(), dtype=float32)
向量 tf.Tensor([0. 0.], shape=(2,), dtype=float32)
矩阵 tf.Tensor([[2. 4.],[1. 3.]], shape=(2, 2), dtype=float32)
其中,tf.random.uniform(shape,minval=0,maxval=None,dtype=float32,seed=None,name=None)从均匀分布中输出值,该值在[minval,maxval)区间内遵循均匀分布。
shape:张量的形状即维度
minval:生成的随机值范围的下限,默认为0.
maxval:要生成的随机值范围的上限,如果 dtype 是浮点,则默认为1.
dtype:输出的类型有float16、float32、float64、int32、int64
seed:一个 Python 整数,用于为分布创建一个随机种子,查看 tf.set_random_seed 行为
name:操作的名称(可选)
tf.zeros(shape,dtype,name)输出全零值的张量。
shape:张量的形状
dtype:输出的类型,如上
name:操作的名称
tf.constant(value,shape,dtype,name) 输出指定维度(shape)与值(value)的张量。
在tensorflow中可以通过shape、dtype、numpy获得张量的形状、类型以及值,若是没有指定值的类型,系统一般默认为floa32,也可以自己通过dtype指定类型。
tensorflow中对已有张量有大量的操作得到新的张量,如下所示:
add_c=tf.add(A,B) matmul_c=tf.matmul(A,B) print('和',add_c) print('积',matmul_c)
和 tf.Tensor(
[[4.3 8.1]
[2.3 6.5]], shape=(2, 2), dtype=float32)
积 tf.Tensor(
[[ 9.799999 22.2 ]
[ 6.2 14.6 ]], shape=(2, 2), dtype=float32)
从上可以看出,tf.add()只能对两个形状一样的张量进行操作,如 。tf.matmul()可以对两个形状不一致的张量进行操作,但必须符合A.shape为n*m,B.shape为m*k这样得出的张量形状为n*k,如。
在机器学习中,我们通常需要求导,tensorFlow中提供了强大的求导机制。
import tensorflow as tf x = tf.Variable(initial_value=3.) with tf.GradientTape() as tape: # 在 tf.GradientTape() 的上下文内,所有计算步骤 都会被记录以用于求导 y = tf.square(x) y_grad = tape.gradient(y, x) # 计算y关于x的导数 print([y, y_grad])
参考文献
https://blog.csdn.net/qq_36512295/article/details/100600001
https://blog.csdn.net/weixin_36670529/article/details/93470877
简单粗暴的tensorflow2.0