当前位置:网站首页>TensorFlow笔记——基本函数及概念
TensorFlow笔记——基本函数及概念
2022-07-27 10:18:00 【中意灬】
目录
TensorFlow 是一个端到端开源机器学习平台。它拥有一个全面而灵活的生态系统,其中包含各种工具、库和社区资源,可助力研究人员推动先进机器学习技术的发展,并使开发者能够轻松地构建和部署由机器学习提供支持的应用,本文基于python对其TensorFlow进行了运用。
神经网络,也称为人工神经网络 (ANN) 或模拟神经网络 (SNN),是机器学习的子集,并且是深度学习算法的核心。其名称和结构是受人类大脑的启发,模仿了生物神经元信号相互传递的方式
神经网络设计过程
- 准备数据集,数据量越大越好,要构成特征和标签对。
- 搭建神经网络结构,并通过反向传播不断优化,然后保存模型
- 用保存的模型通过前向传播进行数据预测
TensorFlow基本概念
TensorFlow中的Tensor表示张量,就是一个广义矩阵,可理解为一个多维数组或者列表,用阶表示张量的维数。0阶张量叫做标量,表示的是一个单独的数,如520;1阶张量叫做向量,即一维数组,如[5,2,0];2阶张量叫做矩阵,即二维数组,如[[1,2,3],[4,5,6]]。
TensorFlow中数据类型有32位整型(tf.int32)、32位浮点(tf.float32)、64位浮点(tf.float64)、布尔型(tf.bool)、字符串型(tf.string)
基本函数
1.创建张量的方法
(1)tf.constant(张量内容,dype=数据类型(可选))。第一个参数表示张量的内容,第二个参数表示张量的数据类型。
import tensorflow as tf
a=tf.constant([1,5],dtype=tf.int32)
print(a)
print(a.dtype)
print(a.shape)运行结果:
tf.Tensor([1 5], shape=(2,), dtype=int32)
<dtype: 'int32'>
(2,)
(2) tf.conver_to_tensor(数据名,dtype=数据类型(可选))。很多时候数据是由numpy格式给出的,此时可通过此函数将numpy格式转换成tensor格式
import numpy as np
a=np.arange(0,5)
b=tf.convert_to_tensor(a,dtype=tf.int32)
print(a)
print(b)运行结果:
[0 1 2 3 4]
tf.Tensor([0 1 2 3 4], shape=(5,), dtype=int32)
(3) 不同函数创建不同值的张量。 tf.zeros(维度) 创建全为0的张量,tf.ones(维度) 创建全为1的张量,tf.fill(维度,指定值) 创建全为指定值的张量。其中维度参数部分。如一维直接写个数,二维用[行,列]表示,多维同[n,m.....,j]表示。
a=tf.zeros([3,2])
b=tf.ones([2,3])
c=tf.fill(5,5)
print(a)
print(b)
print(c)运行结果:
tf.Tensor(
[[0. 0.]
[0. 0.]
[0. 0.]], shape=(3, 2), dtype=float32)
tf.Tensor(
[[1. 1. 1.]
[1. 1. 1.]], shape=(2, 3), dtype=float32)
tf.Tensor([5 5 5 5 5], shape=(5,), dtype=int32)
(4) 可采用不同函数创建符合不同分布的张量。 tf.random.normal(维度,mean=均值,stddev=标准差) 生成正态分布的随机数,默认均值为0,标准差为1。 tf.random.truncated_normal(维度,mean=均值,stddev=标准差) 生成截断式正太分布的随机数,能使生成的这些随机数更集中一些,如果随机生成数据的取值在(u-2δ,u+2δ)之外重新进行生成,保证了生成值在均值附近。 tf.random.uniform(维度,minval=最小值,maxval=最大值) 生成指定维度的均匀分布随机数,前闭后开。
a=tf.random.normal([2,3],mean=1,stddev=0.5)
b=tf.random.truncated_normal([3,2],mean=0.5,stddev=1)
c=tf.random.uniform([5],minval=2,maxval=5)
print(a)
print(b)
print(c)
运行结果:
tf.Tensor(
[[0.35723394 1.7715123 1.0449663 ]
[1.921211 0.81519336 1.103409 ]], shape=(2, 3), dtype=float32)
tf.Tensor(
[[ 1.159447 -1.1738222 ]
[ 1.274616 -0.376626 ]
[ 0.94688314 -0.39427286]], shape=(3, 2), dtype=float32)
tf.Tensor([2.7424078 2.5905833 2.175548 4.3003993 3.0624359], shape=(5,), dtype=float32)
2.数据类型转换
tf.cast(张量名,dtype=数据类型)强制将Tensor转换为该数据类型
x1=tf.constant([1.,2.,3.],dtype=tf.float32)
print(x1)
x2=tf.cast(x1,dtype=tf.int32)
print(x2)运行结果:
tf.Tensor([1. 2. 3.], shape=(3,), dtype=float32)
tf.Tensor([1 2 3], shape=(3,), dtype=int32)
3.取张量中最小值与最大值
tf.reduce_min(张量名)计算张量维度上元素的最小值
tf.reduce_max(张量名)计算张量维度上元素的最大值
x=tf.constant([1.,2.,3.],dtype=tf.float32)
print(tf.reduce_min(x),tf.reduce_max(x))运行结果:
tf.Tensor(1., shape=(), dtype=float32) tf.Tensor(3., shape=(), dtype=float32)
4.求和与平均值
tf.reduce_mean(张量名,axis=操作轴)计算张量沿着指定维度的平均值。 tf.reeduce_sum(张量名,axis=操作轴)计算张量沿着指定维度的和。 如不指定axis,则表示对所有元素进行操作,axis=0表示对列,axis=1表达对行。
x=tf.constant([[5,2,0],[5,2,0,]])
print(x)
print(tf.reduce_mean(x))
print(tf.reduce_sum(x))运行结果:
tf.Tensor(
[[1 2 3]
[1 2 3]], shape=(2, 3), dtype=int32)
tf.Tensor(2, shape=(), dtype=int32)tf.Tensor(12, shape=(), dtype=int32)
5.标记变量为可训练
tf.Variable(initial_value,trainable,validata_shape,name)函数可将变量标记为“可训练”的,被它标记了的变量,会在反向传播中记录自己的梯度信息。 initi_value默认为None,表示可以后期被算法优化的,如果不想该变量被优化,即改为False validate_shape=False默认为True,形状不接受更改,如果需要更改则改为False name默认为None,给变量确定名称。
w=tf.Variable(tf.random.normal([3,3],mean=1,stddev=1))
# 表示随机生成正态分布随机数,再给生成的随机数标记为可训练的,
# 这样在反向传播中就可以通过梯度下降来更新参数w6.四则运算(维度和类型应一致)
tf.add(张量1,张量2) 实现两个张量对应元素相加。
tf.subtract(张量1,张量2) 实现两个张量对应元素相减,前减后。
tf.multiply(张量1,张量2) 实现两个张量对应元素相乘。
tf.divide(张量1,张量2) 实现两个张量对应元素相除,前除后。
a=tf.ones([2,3])
b=tf.fill([2,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))运行结果:
tf.Tensor(
[[1. 1. 1.]
[1. 1. 1.]], shape=(2, 3), dtype=float32)
tf.Tensor(
[[3. 3. 3.]
[3. 3. 3.]], shape=(2, 3), dtype=float32)
tf.Tensor(
[[4. 4. 4.]
[4. 4. 4.]], shape=(2, 3), dtype=float32)
tf.Tensor(
[[-2. -2. -2.]
[-2. -2. -2.]], shape=(2, 3), dtype=float32)
tf.Tensor(
[[3. 3. 3.]
[3. 3. 3.]], shape=(2, 3), dtype=float32)
tf.Tensor(
[[0.33333334 0.33333334 0.33333334]
[0.33333334 0.33333334 0.33333334]], shape=(2, 3), dtype=float32)
7.幂次运算
tf.square(张量名) 计算某个张量的平方
tf.pow(张量名,n次方数) 计算某个张量的n次方
tf.sqrt(张量名) 计算某个张量的开方
a=tf.fill([1,2],3.)
print(a)
print(tf.square(a))
print(tf.pow(a,3))
print(tf.sqrt(a))运行结果:
tf.Tensor([[3. 3.]], shape=(1, 2), dtype=float32)
tf.Tensor([[9. 9.]], shape=(1, 2), dtype=float32)
tf.Tensor([[27. 27.]], shape=(1, 2), dtype=float32)
tf.Tensor([[1.7320508 1.7320508]], shape=(1, 2), dtype=float32)
8.矩阵相乘(数据类型应相同)
tf.matmul(矩阵1,矩阵2) 实现两个矩阵相乘
a=tf.ones([2,3])
b=tf.fill([3,1],2.)
print(a.dtype)
print(tf.matmul(a,b))运行结果:
tf.Tensor(
[[6.]
[6.]], shape=(2, 1), dtype=float32)
9.自动生成特征/标签对
tf.data.Dataset.from_tensor_slices((输入特征,标签)) 切分传入张量的第一维度,生成输入特征/标签对,构建数据集,此函数对Tensor格式与Numpy格式均适用,其切分的是第一维度,表征数据集中数据的数量,之后切分batch等操作都以第一维为基础。
features=tf.constant([12,23,10,17])
labels=tf.constant([0,1,1,0])
dataset=tf.data.Dataset.from_tensor_slices((features,labels))
print(dataset)
for element in dataset:
print(element)运行结果:
<TensorSliceDataset element_spec=(TensorSpec(shape=(), dtype=tf.int32, name=None), TensorSpec(shape=(), dtype=tf.int32, name=None))>
(<tf.Tensor: shape=(), dtype=int32, numpy=12>, <tf.Tensor: shape=(), dtype=int32, numpy=0>)
(<tf.Tensor: shape=(), dtype=int32, numpy=23>, <tf.Tensor: shape=(), dtype=int32, numpy=1>)
(<tf.Tensor: shape=(), dtype=int32, numpy=10>, <tf.Tensor: shape=(), dtype=int32, numpy=1>)
(<tf.Tensor: shape=(), dtype=int32, numpy=17>, <tf.Tensor: shape=(), dtype=int32, numpy=0>)
10.计算梯度
tf.GradientTape()搭配with结构计算损失函数在某一张量处的梯度
with tf.GradientTape() as tape:
w=tf.Variable(tf.constant(3.0))
loss=tf.pow(w,3)
grad=tape.gradient(loss,w)
print(grad)运行结果:
tf.Tensor(27.0, shape=(), dtype=float32)
11.枚举
enumerate(列表名) 枚举出每一个元素,并在元素前配上对应的索引号,常在for循环中使用
seq=['one','two','three']
for i,element in enumerate(seq):
print(i,element)运行结果:
0 one
1 two
2 three
12.独热码转换
tf.one_hot(待转换数据,depth=几分类) 实现用独热码表示标签,在分类问题中很常见(待转换的类别要小于depth)即有个三分类问题,其分类结构由0,1,2,用独热码表示就是[1,0,0],[0,1,0],[0,0,1],如[1,0,0]表示,百分之百可能是类别0,百分之零可能是类别1,百分之零可能是类别2
classes=3
labels=tf.constant([0,1,2])
output=tf.one_hot(labels,classes)
print(output)运行结果:
tf.Tensor(
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]], shape=(3, 3), dtype=float32)
13.输出值符合概率分布
tf.nn.softmax() 使前向传播的输出值符合概率分布,进而与独热码形式的标签作比较
y=tf.constant([1.31,2.13,-0.31])
y_pro=tf.nn.softmax(y)
print(y_pro)运行结果:
tf.Tensor([0.28831747 0.6546249 0.05705766], shape=(3,), dtype=float32)
14.对参数实现自更新
assign_sub (自减) assign_add (自加)对参数实现自更新.使用此函数前需利用tf.Variable定义变量w为可训练(可自更新)。
w=tf.Variable(2)
w.assign_sub(1)
print(w)
w.assign_add(2)
print(w)运行结果:
<tf.Variable 'Variable:0' shape=() dtype=int32, numpy=1>
<tf.Variable 'Variable:0' shape=() dtype=int32, numpy=3>
15.得到最大(小)值的索引
tf.argmax(张量名,axis=操作轴)axis=0->列,axis=1->行.返回张量沿指定维度最大值的索引
tf.argmin(张量名,axis=操作轴)返回指定维度最小值的索引
import numpy as np
test=np.array([[1,2,3],[3,4,5],[6,7,8]])
print(test)
print(tf.argmax(test,axis=0))
print(tf.argmax(test,axis=1))运行结果:
[[1 2 3]
[3 4 5]
[6 7 8]]
tf.Tensor([2 2 2], shape=(3,), dtype=int64)
tf.Tensor([2 2 2], shape=(3,), dtype=int64)
鸢尾花数据集分类
搭建一个简单的神经网络实现鸢尾花数据集的分类
此处构建的为一个仅包括输入输出层的简单神经网络,四个输入,三个输出,没有隐藏层
构建其函数y=x*w+b
运用梯度下降优化其参数w与b,即

lr为其学习率,是一个超参数,表征梯度下降的速度;loss为损失值,这里用均方误差来计算其损失值。
# 利用鸢尾花数据集,实现前向传播、反向传播,可视化loss曲线
# 导入所需模块
import tensorflow as tf
from sklearn import datasets
from matplotlib import pyplot as plt
from sklearn.model_selection import train_test_split
# 导入数据,分别为输入特征和标签
x_data,y_data = datasets.load_iris(return_X_y=True)
# 将打乱后的数据集分割为训练集和测试集,取百分之30为测试集
x_train,x_test,y_train,y_test=train_test_split(x_data,y_data,test_size=0.3,random_state=520)
# 转换x的数据类型,否则后面矩阵相乘时会因数据类型不一致报错
x_train = tf.cast(x_train, tf.float32)
x_test = tf.cast(x_test, tf.float32)
# from_tensor_slices函数使输入特征和标签值一一对应。(把数据集分批次,每个批次batch组数据)
train_db = tf.data.Dataset.from_tensor_slices((x_train, y_train)).batch(32)
test_db = tf.data.Dataset.from_tensor_slices((x_test, y_test)).batch(32)
# 生成神经网络的参数,4个输入特征故,输入层为4个输入节点;因为3分类,故输出层为3个神经元
# 用tf.Variable()标记参数可训练
w1 = tf.Variable(tf.random.truncated_normal([4, 3], stddev=0.1))
b1 = tf.Variable(tf.random.truncated_normal([3], stddev=0.1))
lr = 0.1 # 学习率为0.1
train_loss_results = [] # 将每轮的loss记录在此列表中,为后续画loss曲线提供数据
test_acc = [] # 将每轮的acc记录在此列表中,为后续画acc曲线提供数据
epoch = 500 # 循环500轮,可自己设置
loss_all = 0 # 每轮分4个step,loss_all记录四个step生成的4个loss的和
# 训练部分
for epoch in range(epoch): #数据集级别的循环,每个epoch循环一次数据集
for step, (x_train, y_train) in enumerate(train_db): #batch级别的循环 ,每个step循环一个batch
with tf.GradientTape() as tape: # with结构记录梯度信息
y = tf.matmul(x_train, w1) + b1 # 神经网络乘加运算
y = tf.nn.softmax(y) # 使输出y符合概率分布(此操作后与独热码同量级,可相减求loss)
y_ = tf.one_hot(y_train, depth=3) # 将标签值转换为独热码格式,方便计算loss和accuracy
loss = tf.reduce_mean(tf.square(y_ - y)) # 采用均方误差损失函数mse = mean(sum(y-out)^2)
loss_all += loss.numpy() # 将每个step计算出的loss累加,为后续求loss平均值提供数据,这样计算的loss更准确
# 计算loss对各个参数的梯度(求偏导)
grads = tape.gradient(loss, [w1, b1])
# 实现梯度更新 w1 = w1 - lr * w1_grad b = b - lr * b_grad
w1.assign_sub(lr * grads[0]) # 参数w1自更新
b1.assign_sub(lr * grads[1]) # 参数b自更新
# 每个epoch,打印loss信息
print("Epoch {}, loss: {}".format(epoch, loss_all/4))
train_loss_results.append(loss_all / 4) # 将4个step的loss求平均记录在此变量中
loss_all = 0 # loss_all归零,为记录下一个epoch的loss做准备
# 测试部分
# total_correct为预测对的样本个数, total_number为测试的总样本数,将这两个变量都初始化为0
total_correct, total_number = 0, 0
for x_test, y_test in test_db:
# 使用更新后的参数进行预测
y = tf.matmul(x_test, w1) + b1
y = tf.nn.softmax(y)
pred = tf.argmax(y, axis=1) # 返回y中最大值的索引,即预测的分类
# 将pred转换为y_test的数据类型
pred = tf.cast(pred, dtype=y_test.dtype)
# 若分类正确,则correct=1,否则为0,将bool型的结果转换为int型
correct = tf.cast(tf.equal(pred, y_test), dtype=tf.int32)
# 将每个batch的correct数加起来
correct = tf.reduce_sum(correct)
# 将所有batch中的correct数加起来
total_correct += int(correct)
# total_number为测试的总样本数,也就是x_test的行数,shape[0]返回变量的行数
total_number += x_test.shape[0]
# 总的准确率等于total_correct/total_number
acc = total_correct / total_number
test_acc.append(acc)
print("Test_acc:", acc)
print("=========================")
# 绘制 loss 曲线
plt.title('Loss Function Curve') # 图片标题
plt.xlabel('Epoch') # x轴变量名称
plt.ylabel('Loss') # y轴变量名称
plt.plot(train_loss_results, label="$Loss$") # 逐点画出trian_loss_results值并连线,连线图标是Loss
plt.legend() # 画出曲线图标
plt.show() # 画出图像
# 绘制 Accuracy 曲线
plt.title('Acc Curve') # 图片标题
plt.xlabel('Epoch') # x轴变量名称
plt.ylabel('Acc') # y轴变量名称
plt.plot(test_acc, label="$Accuracy$") # 逐点画出test_acc值并连线,连线图标是Accuracy
plt.legend()
plt.show()
运行结果:
迭代次数与损失函数值图像
迭代次数与正确率图像
本文仅作为自己学习笔记,其内容来源于mooch上的TensorFlow学习笔记课程。
边栏推荐
- [Flink] Flink builds clusters in standalone mode
- 【Liunx】MariaDB/MySQL定时全量备份脚本及数据恢复
- No Identifier specified for entity的解决办法
- MySQL log management, backup and recovery
- es6的foreach与some的循环遍历
- Shardingsphere kernel principle
- phpstudy中Apache无法启动
- Matlab low-level source code realizes the median filtering of the image (used to eliminate some miscellaneous points on the image)
- warning package.json: No license field报错
- Matlab/Simulink求解微分方程样例分享
猜你喜欢

Basic statement of database operation

搭建 Samba 服务

wind10配置adb命令

Set up Samba service

分享机器学习笔记(PDF版)+实战项目(数据集+代码)

【Liunx】MariaDB/MySQL定时全量备份脚本及数据恢复

Beijing publicized the spot check of 8 batches of children's shoes, and qierte was listed as unqualified
[email protected] @Eslint loader / index. JS) "/>Eslint's error message module error (from./node_modules/ [email protected] @Eslint loader / index. JS)

Your appearance is amazing! Two JSON visualization tools are recommended for use with swagger. It's really fragrant

Understanding and code implementation of Se (sequence and exception) module
随机推荐
Sorting out some open source projects of speech recognition
【Liunx】MariaDB/MySQL定时全量备份脚本及数据恢复
Key points of ES6 class inheritance
mount. Nfs: access denied by server while mounting
【英雄哥六月集训】第 26天: 并查集
A few simple steps to realize the sharing network for industrial raspberry pie
异构计算技术分析
gyp ERR! configure error. gyp ERR! stack Error: gyp failed with exit code: 1
File upload vulnerability related
服务器访问速度
MySQL日志管理、备份与恢复
Matlab/Simulink求解微分方程样例分享
FTP 服务器
jvm--字节码浅析
Sub query of database performance series
Ubuntu and MySQL quick start tutorial
Based on LSM tree idea Net 6.0 C # write a kV database (case version)
warning package. Json: no license field error
Matlab-绘制日期和持续时间图
【Liunx】安装Redis