本文记录的是TensorFlow中常用的函数
import tensorflow as tf
import numpy as np
在一个二维张量或者数组中,通过改变axis=0或1来控制执行的维度
如果不指定的话,则全员参与计算
强制tensor转换为该数据类型
tf.cast(张量名, dtype=数据类型)
In [2]:
x1 = tf.constant([1,2,3],dtype=tf.float64)
x1
Out[2]:
<tf.Tensor: shape=(3,), dtype=float64, numpy=array([1., 2., 3.])>
In [3]:
x2 = tf.cast(x1, dtype=tf.int64) # 转换数据类型
x2
Out[3]:
<tf.Tensor: shape=(3,), dtype=int64, numpy=array([1, 2, 3])>
计算张量维度上的最值
In [4]:
print(tf.reduce_max(x2))
tf.Tensor(3, shape=(), dtype=int64)
In [5]:
print(tf.reduce_min(x2))
tf.Tensor(1, shape=(), dtype=int64)
计算张量沿着指定维度的平均值或者和
In [6]:
i = tf.constant([[1,2,3],
[4,5,6]
],dtype=tf.float64)
i
Out[6]:
<tf.Tensor: shape=(2, 3), dtype=float64, numpy=
array([[1., 2., 3.],
[4., 5., 6.]])>
In [7]:
tf.reduce_mean(i) # 默认是全部数值的均值
Out[7]:
<tf.Tensor: shape=(), dtype=float64, numpy=3.5>
In [8]:
tf.reduce_mean(i, axis=0)
Out[8]:
<tf.Tensor: shape=(3,), dtype=float64, numpy=array([2.5, 3.5, 4.5])>
In [9]:
tf.reduce_mean(i, axis=1)
Out[9]:
<tf.Tensor: shape=(2,), dtype=float64, numpy=array([2., 5.])>
In [10]:
tf.reduce_sum(i) # 1+2+3+4+5+6
Out[10]:
<tf.Tensor: shape=(), dtype=float64, numpy=21.0>
In [11]:
tf.reduce_sum(i, axis=0)
Out[11]:
<tf.Tensor: shape=(3,), dtype=float64, numpy=array([5., 7., 9.])>
In [12]:
tf.reduce_sum(i, axis=1)
Out[12]:
<tf.Tensor: shape=(2,), dtype=float64, numpy=array([ 6., 15.])>
tf.Variable()将函数标记为可训练,被标记的变量会在反向传播中记录梯度信息。
神经网络中常用该函数来标记待训练的参数。
In [13]:
w = tf.Variable(tf.random.normal([2,2], mean=0, stddev=1))
w
Out[13]:
<tf.Variable 'Variable:0' shape=(2, 2) dtype=float32, numpy=
array([[-1.3200597 , 1.123157 ],
[ 0.4855043 , -0.06241844]], dtype=float32)>
上面变量w的解释:
注意:只有维度相同的两个张量才能进行四则运算
切分传入张量的第一维度,生成输入特征和标签对,构建数据集:特征和标签配对
Numpy和Tensor格式都可以使用该语句读入数据
data = tf.data.Dataset.from_tensor_slices((输入特征,标签))
In [14]:
features = tf.constant([12,15,20,27])
labels = tf.constant([0,1,0,1])
dataset = tf.data.Dataset.from_tensor_slices((features,labels))
print(dataset)
<TensorSliceDataset element_spec=(TensorSpec(shape=(), dtype=tf.int32, name=None), TensorSpec(shape=(), dtype=tf.int32, name=None))>
In [15]:
for element in dataset:
print(element)
(<tf.Tensor: shape=(), dtype=int32, numpy=12>, <tf.Tensor: shape=(), dtype=int32, numpy=0>)
(<tf.Tensor: shape=(), dtype=int32, numpy=15>, <tf.Tensor: shape=(), dtype=int32, numpy=1>)
(<tf.Tensor: shape=(), dtype=int32, numpy=20>, <tf.Tensor: shape=(), dtype=int32, numpy=0>)
(<tf.Tensor: shape=(), dtype=int32, numpy=27>, <tf.Tensor: shape=(), dtype=int32, numpy=1>)