二.Tensorflow2之常用函数

强制类型转换

强制tensor转换为该数据类型
tf.cast(张量名, dtype=数据类型)

计算张量维度上元素的最大最小值

tf.reduce_max(张量名)
tf.reduce_min(张量名)

import tensorflow as tf
x1 = tf.constant([1, 2, 3], dtype=tf.float64)
print(x1)

x2 = tf.cast(x1, tf.int32)
print(x2)

print(tf.reduce_min(x2), tf.reduce_max(x2))

结果如下:
tf.Tensor([1. 2. 3.], shape=(3,), dtype=float64)
tf.Tensor([1 2 3], shape=(3,), dtype=int32)
tf.Tensor(1, shape=(), dtype=int32) tf.Tensor(3, shape=(), dtype=int32)

理解axis

axis可以指定操作的方向
对于一个二维张量,如果axis=0,表示对第一个维度进行操作,axis=1,表示对第二个维度进行操作。axis=0表示纵向操作,沿经度方向,axis=0表示横向操作,沿纬度方向
在这里插入图片描述
不指定axis则对所有元素进行操作

计算张量沿着指定维度的平均值

tf.reduce_mean(张量名, axis=操作轴)

计算张量沿着指定维度的和

tf.reduce_sum(张量名, axis=操作轴)

import tensorflow as tf
x = tf.constant([[1, 2, 3],
                  [2, 2, 3]])
print(x)
print(tf.reduce_mean(x))
print(tf.reduce_sum(x, axis=1))

结果如下:
tf.Tensor(
[[1 2 3]
 [2 2 3]], shape=(2, 3), dtype=int32)
tf.Tensor(2, shape=(), dtype=int32)
tf.Tensor([6 7], shape=(2,), dtype=int32)

标记可训练

tf.Variable()将变量标记为“可训练”,被标记的变量会在反向传播中记录梯度信息。神经网络训练中,常用该函数标记待训练参数
tf.Variable(初始值)

w = tf.Variable(tf.random.normal([2, 2], mean=0, stddev=1))

随机生成正态分布随机数,再给生成的随机数标记为可训练,这样在反向传播中就可以通过梯度下降更新参数w了

Tensorflow中的数学运算

对应元素的四则运算:tf.add, tf.subtract, tf.multiply, tf.divide
平方、次方与开方:tf.square, tf.pow, tf.sqrt
矩阵乘:tf.matmul
只有维度相同的张量才可以做四则运算

import tensorflow as tf
a = tf.ones([1, 3])
b = tf.fill([1, 3], 3.)
print(a)
print(b)
print(tf.add(a, b))
print(tf.subtract(a, b))
print(tf.multiply(a, b))
print(tf.divide(a, b))

a = tf.fill([1, 2], 3.)
print(a)
print(tf.pow(a, 3))
print(tf.square(a))
print(tf.sqrt(a))

a = tf.ones([3, 2])
b = tf.fill([2, 3], 3.)
print(tf.matmul(a, b))

结果如下:
tf.Tensor([[1. 1. 1.]], shape=(1, 3), dtype=float32)
tf.Tensor([[3. 3. 3.]], shape=(1, 3), dtype=float32)
tf.Tensor([[4. 4. 4.]], shape=(1, 3), dtype=float32)
tf.Tensor([[-2. -2. -2.]], shape=(1, 3), dtype=float32)
tf.Tensor([[3. 3. 3.]], shape=(1, 3), dtype=float32)
tf.Tensor([[0.33333334 0.33333334 0.33333334]], shape=(1, 3), dtype=float32)

tf.Tensor([[3. 3.]], shape=(1, 2), dtype=float32)
tf.Tensor([[27. 27.]], shape=(1, 2), dtype=float32)
tf.Tensor([[9. 9.]], shape=(1, 2), dtype=float32)
tf.Tensor([[1.7320508 1.7320508]], shape=(1, 2), dtype=float32)

tf.Tensor(
[[6. 6. 6.]
 [6. 6. 6.]
 [6. 6. 6.]], shape=(3, 3), dtype=float32)

配对特征和标签

切分传入张量的第一维度,生成输入特征/标签对,构建数据集
data = tf.data.Dataset.from_tensor_slices((输入特征, 标签))
Numpy和Tensor格式都可用该语句读入数据

import tensorflow as tf
feature = tf.constant([12, 23, 10, 17])
labels = tf.constant([0, 1, 1, 0])
dataset = tf.data.Dataset.from_tensor_slices((feature, labels))
print(dataset)
for element in dataset:
    print(element)
    
结果如下:
<TensorSliceDataset shapes: ((), ()), types: (tf.int32, tf.int32)>
(<tf.Tensor: id=9, shape=(), dtype=int32, numpy=12>, <tf.Tensor: id=10, shape=(), dtype=int32, numpy=0>)
(<tf.Tensor: id=11, shape=(), dtype=int32, numpy=23>, <tf.Tensor: id=12, shape=(), dtype=int32, numpy=1>)
(<tf.Tensor: id=13, shape=(), dtype=int32, numpy=10>, <tf.Tensor: id=14, shape=(), dtype=int32, numpy=1>)
(<tf.Tensor: id=15, shape=(), dtype=int32, numpy=17>, <tf.Tensor: id=16, shape=(), dtype=int32, numpy=0>)

某个函数对指定参数的求导

在这里插入图片描述

import tensorflow as tf
with tf.GradientTape() as tape:
    w = tf.Variable(tf.constant(3.0))
    loss = tf.pow(w, 2)
grad = tape.gradient(loss, w)
print(grad)

结果如下:
tf.Tensor(6.0, shape=(), dtype=float32)

枚举enumerate

它是python的内建函数,可遍历每个元素(如列表、元组或字符串),并在元素前配上对应的索引号,组合为:索引 元素,常在for循环中使用

seq = ['one', 'two', 'three']
for i, element in enumerate(seq):
    print(i, element)

结果如下:
0 one
1 two
2 three

分类问题常用独热码表示标签

tf.one_hot()函数将待转换数据,转换为one-hot形式的数据输出
tf.one_hot(待转换数据, depth=几分类)

import tensorflow as tf
classes = 3
labels = tf.constant([1, 0, 2])
output = tf.one_hot(labels, depth=classes)
print(output)

结果如下:
tf.Tensor(
[[0. 1. 0.]
 [1. 0. 0.]
 [0. 0. 1.]], shape=(3, 3), dtype=float32)

分类问题softmax

使输出符合概率分布
在这里插入图片描述

import tensorflow as tf

y = tf.constant([1.01, 2.01, -0.66])
y_pro = tf.nn.softmax(y)
print("After softmax, y_pro is:", y_pro)  # y_pro 符合概率分布
print("The sum of y_pro:", tf.reduce_sum(y_pro))  # 通过softmax后,所有概率加起来和为1

结果如下:
After softmax, y_pro is: tf.Tensor([0.25598174 0.69583046 0.04818781], shape=(3,), dtype=float32)
The sum of y_pro: tf.Tensor(1.0, shape=(), dtype=float32)

参数的自更新

assign_sub函数常用于参数的自更新,等待自更新的参数w要先被指定为可更新可训练,也就是Variable类型
w.assign_sub(w要自减的内容)

import tensorflow as tf

x = tf.Variable(4)
x.assign_sub(1)
print("x:", x)  # 4-1=3

结果如下:
x: <tf.Variable 'Variable:0' shape=() dtype=int32, numpy=3>

指定操作轴方向最大值的索引

tf.argmax(张量名, axis=操作轴)
在这里插入图片描述

import numpy as np
import tensorflow as tf

test = np.array([[1, 2, 3], [2, 3, 4], [5, 4, 3], [8, 7, 2]])
print("test:\n", test)
print("每一列的最大值的索引:", tf.argmax(test, axis=0))  # 返回每一列最大值的索引
print("每一行的最大值的索引", tf.argmax(test, axis=1))  # 返回每一行最大值的索引

结果如下:
test:
 [[1 2 3]
 [2 3 4]
 [5 4 3]
 [8 7 2]]
每一列的最大值的索引: tf.Tensor([3 3 1], shape=(3,), dtype=int64)
每一行的最大值的索引 tf.Tensor([2 2 0 0], shape=(4,), dtype=int64)

tf.where()

条件语句真返回A,假返回B
tf.where(条件语句, 真返回A, 假返回B)

import tensorflow as tf

a = tf.constant([1,2,3,1,1])
b = tf.constant([0,1,3,4,5])
c = tf.where(tf.greater(a, b), a, b)  # greater()判断a是否大于b
print("c:", c)

结果如下:
c: tf.Tensor([1 2 3 4 5], shape=(5,), dtype=int32)

np.random.RandomState.rand()

返回一个[0, 1)之间的随机数
np.random.RandomState.rand(维度) # 维度若为空,返回标量

import numpy as np

rdm = np.random.RandomState(seed=1)  # seed=常数,每次生成随机数都相同
a = rdm.rand()  # 返回一个随机标量
b = rdm.rand(2, 3)  # 返回维度为2行3列随机数矩阵

print("a:", a)
print("b:", b)

结果如下:
a: 0.417022004702574
b: [[7.20324493e-01 1.14374817e-04 3.02332573e-01]
 [1.46755891e-01 9.23385948e-02 1.86260211e-01]]

np.vstack()

将两个数组按垂直方向叠加
np.vstack(数组1, 数组2)

import numpy as np

a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
c = np.vstack((a, b))
print("c:\n", c)

结果如下:
c:
 [[1 2 3]
 [4 5 6]]

np.mgrid[]、np.ravel()、np.c_[]

这三个函数经常一起使用,可以生成网格坐标点
1.np.mgrid[起始值:结束值:步长,起始值:结束值:步长,…]
返回若干组维度相同的等差数组,[起始值,结束值)前闭后开
2.x.ravel() 把多维数组变成一维数组,把x变量拉直
3.np.c_[] 把数组配对后输出

import numpy as np

# 生成等间隔数值点
x, y = np.mgrid[1:3:1, 2:4:0.5]
# 将x, y拉直,并合并配对为二维张量,生成二维坐标点
grid = np.c_[x.ravel(), y.ravel()]
print("x:\n", x)
print("y:\n", y)
print("x.ravel():\n", x.ravel())
print("y.ravel():\n", y.ravel())
print('grid:\n', grid)

结果如下:
x:
 [[1. 1. 1. 1.]
 [2. 2. 2. 2.]]
y:
 [[2.  2.5 3.  3.5]
 [2.  2.5 3.  3.5]]
x.ravel():
 [1. 1. 1. 1. 2. 2. 2. 2.]
y.ravel():
 [2.  2.5 3.  3.5 2.  2.5 3.  3.5]
grid:
 [[1.  2. ]
 [1.  2.5]
 [1.  3. ]
 [1.  3.5]
 [2.  2. ]
 [2.  2.5]
 [2.  3. ]
 [2.  3.5]]

学完了常用函数,接下来就可以愉快的自己敲代码啦!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值