Tensoflow常用函数
本文记录的是TensorFlow中常用的函数
- tf.cast:强制数据类型转换
- tf.reduct_mean/sum:求和或均值
- tf.reduce_max/min:求最值
- tf.Variable:标记变量
- 四则运算
- tf.data.Dataset.from_tensor_slices:特征和标签配对
1 | import tensorflow as tf |
理解axis
在一个二维张量或者数组中,通过改变axis=0或1来控制执行的维度
- 0:表示经度,跨行,down
- 1:表示纬度,跨列,across
如果不指定的话,则全员参与计算
tf.cast
强制tensor转换为该数据类型
1 | tf.cast(张量名, dtype=数据类型) |
In [2]:
1 | x1 = tf.constant([1,2,3],dtype=tf.float64) |
Out[2]:
1 | <tf.Tensor: shape=(3,), dtype=float64, numpy=array([1., 2., 3.])> |
In [3]:
1 | x2 = tf.cast(x1, dtype=tf.int64) # 转换数据类型 |
Out[3]:
1 | <tf.Tensor: shape=(3,), dtype=int64, numpy=array([1, 2, 3])> |
tf.reduce_max/min
计算张量维度上的最值
In [4]:
1 | print(tf.reduce_max(x2)) |
In [5]:
1 | print(tf.reduce_min(x2)) |
tf.reduct_mean/sum
计算张量沿着指定维度的平均值或者和
In [6]:
1 | i = tf.constant([[1,2,3], |
Out[6]:
1 | <tf.Tensor: shape=(2, 3), dtype=float64, numpy= |
In [7]:
1 | tf.reduce_mean(i) # 默认是全部数值的均值 |
Out[7]:
1 | <tf.Tensor: shape=(), dtype=float64, numpy=3.5> |
In [8]:
1 | tf.reduce_mean(i, axis=0) |
Out[8]:
1 | <tf.Tensor: shape=(3,), dtype=float64, numpy=array([2.5, 3.5, 4.5])> |
In [9]:
1 | tf.reduce_mean(i, axis=1) |
Out[9]:
1 | <tf.Tensor: shape=(2,), dtype=float64, numpy=array([2., 5.])> |
In [10]:
1 | tf.reduce_sum(i) # 1+2+3+4+5+6 |
Out[10]:
1 | <tf.Tensor: shape=(), dtype=float64, numpy=21.0> |
In [11]:
1 | tf.reduce_sum(i, axis=0) |
Out[11]:
1 | <tf.Tensor: shape=(3,), dtype=float64, numpy=array([5., 7., 9.])> |
In [12]:
1 | tf.reduce_sum(i, axis=1) |
Out[12]:
1 | <tf.Tensor: shape=(2,), dtype=float64, numpy=array([ 6., 15.])> |
tf.Variable
tf.Variable()将函数标记为可训练,被标记的变量会在反向传播中记录梯度信息。
神经网络中常用该函数来标记待训练的参数。
In [13]:
1 | w = tf.Variable(tf.random.normal([2,2], mean=0, stddev=1)) |
Out[13]:
1 | <tf.Variable 'Variable:0' shape=(2, 2) dtype=float32, numpy= |
上面变量w的解释:
- 先生成正态分布的随机数
- 再将随机数标记为可训练,这样在神经网络的反向传播中就可以通过梯度下降更新参数w了
数学运算
- 四则运算:tf.add(t1,t2)、tf.subtract、tf.multiply、tf.divide
- 平方、次方与开方:tf.square、tf.pow(t,n次方)、tf.sqrt
- 矩阵乘:tf.matmul
注意:只有维度相同的两个张量才能进行四则运算
tf.data.Dataset.from_tensor_slices
切分传入张量的第一维度,生成输入特征和标签对,构建数据集:特征和标签配对
Numpy和Tensor格式都可以使用该语句读入数据
1 | data = tf.data.Dataset.from_tensor_slices((输入特征,标签)) |
In [14]:
1 | features = tf.constant([12,15,20,27]) |
In [15]:
1 | for element in dataset: |