Tensorflow2.0学习笔记

目录

目录

一、Tensorflow2.0基本概念与常见函数

1.1 基本概念

1.2 常用函数

1.3 第一个Tensorflow程序——鸢尾花分类

二、神经网络优化

2.1 学习率策略


 

一、Tensorflow2.0基本概念与常见函数

1.1 基本概念

Tensorflow中的数据类型包括:32位整型(tf.int32)、32位浮点(tf.float32)、64位浮点(tf.float64)、布尔型(tf.bool)、字符串型(tf.string)。

0阶张量叫做标量,表示的是单独的一个数,比如:510;1阶张量叫做向量,表示的是一个一维数组,比如:[1,2,3,4];2阶张量叫做矩阵,表示的是一个二维数组,比如:[[1,2,3],[4,5,6]]。张量的阶数与方括号的数量相同,0个方括号即为0阶张量,1个方括号即为1阶张量,以此类推。可通过reshape获得更高维度数组,如:

A = np.range(24).reshape(2,4,3)
print(A)
>>> [[[0 1 2] [3 4 5] [6 7 8] [9 10 11]]
     [12 13 14] [15 16 17] [18 19 20] [21 22 23]]

创建张量包括如下几种方法:

(1)利用 tf.constant(张量内容, dtype=数据类型(可选)),如:

import tensorflow as tf
a = tf.constant([1,2,3],dtype=tf.int64)
print(a)
>>> tf.Tensor([1 2 3], shape=(3,), dtype=int64)
print(a.dtype)
>>> <dtype: 'int64'>
print(a.shape)
>>> (3,)

shape中有几个数字,就表示是几维张量。

(2)通过 tf.convert_to_tensor(数据名, dtype=数据类型(可选)) 将numpy格式转化为Tensor格式,如:

import tensorflow as tf
import numpy as np
a = np.arange(0,5)
b = tf.convert_to_tensor(a,dtype=tf.int64)
print(a)
>>> [0 1 2 3 4]
print(b)
>>> tf.Tensor([0 1 2 3 4], shape=(5,), dtype=int64)

(3)采用不同函数创建不同值的张量。

如用 tf.zeros(维度) 创建全为0的张量,tf.ones(维度) 创建全为1的张量,tf.fill(维度, 指定值) 创建全为指定值的张量。一维直接写个数,二维用 [行, 列] 表示,多维用 [n, m, j..] 表示。如:

a = tf.zeros([2,3])
b = tf.ones(4)
c = tf.fill([2,2],9)
print(a)
>>> tf.Tensor(
    [[0. 0. 0.]
     [0. 0. 0.]], shape=(2, 3), dtype=float32)
print(b)
>>> tf.Tensor([1. 1. 1. 1.], shape=(4,), dtype=float32)
print(c)
>>> tf.Tensor(
    [[9 9]
     [9 9]], shape=(2, 2), dtype=int32)

(4)采用不同函数创建符合不同分布的张量。

如用 tf.random.normal(维度, mean=均值, stddev=标准差) 生成正态分布的随机数,默认均值为0,标注差为1;

tf.random.truncated_normal(维度, mean=均值, stddev=标准差) 生成截断式正态分布的随机数,能使生成的这些随机数更集中些,如果随机生成数据的取值在(\mu - 2\sigma, \mu + 2\sigma)之外则重新生成,保证了生成值在均值附近;

tf.random.uniform(维度, minval=最小值, maxval=最大值),生成指定纬度的均匀分布随机数,用minval给定随机数的最小值,用maxval给定随机数的最大值,最小、最大值是前闭后开区间。如:

d = tf.random.normal([2,2],mean=0.5,stddev=1)
print(d)
>>> tf.Tensor(
    [[ 1.2841269  -0.18747222]
     [ 0.93886095  1.1705294 ]], shape=(2, 2), dtype=float32)
e = tf.random.truncated_normal([2,2],mean=0.5,stddev=1)
print(e)
>>> tf.Tensor(
    [[ 0.14397079 -0.28171962]
     [-0.02594137  1.439899  ]], shape=(2, 2), dtype=float32)
f = tf.random.uniform([2,2],minval=0,maxval=1)
print(f)
>>> tf.Tensor(
    [[0.5723102  0.34628367]
     [0.20671642 0.932477  ]], shape=(2, 2), dtype=float32)

1.2 常用函数

  • 强制将Tensor转换为特定数据类型:tf.cast(张量名, dtype=数据类型)
  • 计算张量维度上元素的最小值: tf.reduce_min(张量名)
  • 计算张量维度上元素的最大值: tf.reduce_min(张量名)
x1 = tf.constant([1.,2.,3.],dtype=tf.float64)
print(x1)
>>> tf.Tensor([1. 2. 3.], shape=(3,), dtype=float64)
x2 = tf.cast(x1,tf.int32)
print(x2)
>>> tf.Tensor([1 2 3], shape=(3,), dtype=int32)
print(tf.reduce_min(x2),tf.reduce_max(x2))
>>> tf.Tensor(1, shape=(), dtype=int32) tf.Tensor(3, shape=(), dtype=int32)
  • 计算张量沿着指定维度的平均值: tf.reduce_mean(张量名, axis=操作轴),如不指定axis,则表示对所有元素进行操作,对于一个二维矩阵,axis=1 表示沿着横向方向进行计算,axis=0 表示沿着纵向方向进行计算。
  • 计算张量沿着指定维度的和: tf.reduce_sum(张量名, axis=操作轴)
x1 = tf.constant([[1,2,3],[2,2,3]])
print(x1)
>>> tf.Tensor(
    [[1 2 3]
     [2 2 3]], shape=(2, 3), dtype=int32)
print(tf.reduce_mean(x1))
>>> tf.Tensor(2, shape=(), dtype=int32)
print(tf.reduce_sum(x1,axis=1))
>>> tf.Tensor([6 7], shape=(2,), dtype=int32)
  • 将变量标记为“可训练”的:tf.Variable(initial_value, trainable, validate_shpae, name),被该函数标记了的变量,会在反向传播中记录自己的梯度信息。其中 initial_value 默认为 None,可以搭配tensorflow随机生成函数来初始化参数;trainable 默认为True,表示可以后期被算法优化的,如果不想该变量被优化,则改为False;validate_shape 默认为True,形状不接受更改,反之则为False;name 默认为 None,给变量确定名称。例:
w = tf.Variable(tf.random.normal([2,2],mean=0,stddev=1))
# 首先随机生成正态分布随机数,再给生成的随机数标记为可训练,在方向传播中可更新参数w
  • 两个张量的对应元素相加: tf.add(张量1, 张量2)
  • 两个张量的对应元素相减: tf.subtract(张量1, 张量2)
  • 两个张量的对应元素相乘: tf.multiply(张量1, 张量2)
  • 两个张量的对应元素相除: tf.divide(张量1, 张量2),只有维度相同的张量才可以做四则运算
  • 计算某个张量的平方:tf.square(张量名, n次方数)
  • 计算某个张量的n次方: tf.pow(张量名, n次方数)
  • 计算某个张量的开方: tf.sqrt(张量名)
  • 两个矩阵的相乘: tf.matmul(矩阵1, 矩阵2)
a = tf.ones([3,2])
b = tf.fill([2,3],3.)
print(tf.matmul(a,b))
>>> tf.Tensor(
    [[6. 6. 6.]
     [6. 6. 6.]
     [6. 6. 6.]], shape=(3, 3), dtype=float32)
  • 利用 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)
>>> <TensorSliceDataset shapes: ((), ()), types: (tf.int32, tf.int32)>
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=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>)
  • 利用 tf.GradientTape() 函数搭配 with 结构计算损失函数在某一张量处的梯度。
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)
# 损失函数为w^2,w=3,计算结果为6
  • 利用 enumerate(列表名) 函数枚举出每一个元素,并在元素钱配上对应的索引号,常在for循环中使用。
seq = ['one','two','three']
for i,element in enumerate(seq):
    print(i,element)
>>> 0 one
    1 two
    2 three
  • 利用 tf.one_hot(待转换数据, depth=几分类) 函数实现用独热码表示标签,标记类别为1和0,其中1表示是,0表示非。
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)

索引从0开始,待转换数据中各元素值应小于 depth,若待转换元素值大于等于 depth,则该元素输出编码为 [0,0…,0,0]。即 depth 确定列数,待转换元素的个数确定行数。

  • 利用 tf.nn.softmax() 函数使前向传播的输出值符合概率分布,进而与独热码形式的标签作比较,其计算公式为\frac{e^{y_{i}}}{\sum_{j=0}^{n} e^{y_{i}}},其中 y_{i} 是前向传播的输出。
y = tf.constant([1.01,2.01,-0.66])
y_pro = tf.nn.softmax(y)
print("After softmax, y_pro is:",y_pro)
>>> After softmax, y_pro is: tf.Tensor([0.25598174 0.69583046 0.04818781], shape=(3,), dtype=float32)
  • 利用 assign_sub 对参数实现自更新,使用此函数前需利用 tf.Variable 定义变量 w 为可训练(可自更新)。

w = tf.Variable(4)
w.assign_sub(1)
print(w)
>>> <tf.Variable 'Variable:0' shape=() dtype=int32, numpy=3>
  • 利用 tf.argmax(张量名, axis=操作轴) 返回张量沿指定维度最大值的索引。
import numpy as np
test = np.array([[1,2,3],[2,3,4],[5,4,3],[8,7,2]])
print(test)
>>> [[1 2 3]
     [2 3 4]
     [5 4 3]
     [8 7 2]]
print(tf.argmax(test,axis=0))    # 返回每一列最大值的索引
>>> tf.Tensor([3 3 1], shape=(3,), dtype=int64)
print(tf.argmax(test,axis=1))    # 返回每一行最大值的索引
>>> tf.Tensor([2 2 0 0], shape=(4,), dtype=int64)
  • 比较函数: 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)  # 若a>b,返回a对应位置的元素,否则返回b对应位置的元素
print("c:", c)
>>> tf.Tensor([1 2 3 4 5], shape=(5,), dtype=int32)
  • 将两个数组按垂直方向叠加: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(起始值: 结束值: 步长, 起始值: 结束值: 步长)x.ravel() 将x变为一维数组,“把.前变量拉直”;np.c_[数组1, 数组2, ...]使返回的间隔数值点配对。
import numpy as np
import tensorflow as tf

# 生成等间隔数值点
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]]

 

1.3 第一个Tensorflow程序——鸢尾花分类

# -*- coding: UTF-8 -*-

# 导入所需模块
import tensorflow as tf
from sklearn import datasets
from matplotlib import pyplot as plt
import numpy as np

# 导入数据,分别为输入特征和标签
x_data = datasets.load_iris().data
y_data = datasets.load_iris().target

# 随机打乱数据(因为原始数据是顺序的,顺序不打乱会影响准确率)
# seed: 随机数种子,是一个整数,当设置之后,每次生成的随机数都一样
np.random.seed(116)  # 使用相同的seed,保证输入特征和标签一一对应
np.random.shuffle(x_data)
np.random.seed(116)
np.random.shuffle(y_data)
tf.random.set_seed(116)

# 将打乱后的数据集分割为训练集和测试集,训练集为前120行,测试集为后30行
x_train = x_data[:-30]
y_train = y_data[:-30]
x_test = x_data[-30:]
y_test = y_data[-30:]

# 转换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()标记参数可训练
# 使用seed使每次生成的随机数相同(现实使用时不写seed)
w1 = tf.Variable(tf.random.truncated_normal([4, 3], stddev=0.1, seed=1))
b1 = tf.Variable(tf.random.truncated_normal([3], stddev=0.1, seed=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()

二、神经网络优化

2.1 学习率策略

(1)指数衰减学习率

先用较大的学习率,快速得到较优解,然后逐步减小学习率,使模型在训练后期稳定。

d_lr = lr * dr^{gs/ds},d_lr表示指数衰减学习率,lr表示初始学习率,dr表示衰减率,gs表示从0到当前的训练次数,ds表示用来控制衰减速度(即多少轮衰减一次)。

epoch = 40
LR_BASE = 0.2
LR_DECAY = 0.99
LR_STEP = 1
for epoch in range(epoch):
    lr = LR_BASE * LR_DECAY ** (epoch/LR_STEP)
    with tf.GradientTape() as tape:
        loss = tf.square(w+1)
    grads = tape.gradient(loss, w)
    w.assign_sub(lr * grads)
    print("After %s epoch, w is %f, loss is %f, lr is %f"
        %(epoch, w.numpy(),loss,lr))

(2)分段常数衰减

2.2 激活函数

常见的激活函数:sigmoid,tanh,ReLU,LeakyReLU,RReLU,ELU(Exponential Linear Units),softplus,softsign,softmax等。

对应的函数有:tf.nn.sigmoid(x)tf.math.tanh(x)tf.nn.relu(x)tf.nn.leaky_relu(x)tf.nn.softmax(x)

小建议:(1)首选ReLU函数;(2)学习率设置较小值;(3)输入特征标准化,即让输入特征满足以0为均值,1为标准差的正态分布;(4)初始化问题,初始参数中心化,即让随机生成的参数满足以0为均值,(根号下2除以当前层输入特征个数)为标准差的正态分布。

 

 

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在conda中配置Tensorflow 2.0,可以按照以下步骤进行: 1. 首先,确保已经安装了conda和相应的Python版本。如果没有安装,可以从Anaconda官网下载和安装。 2. 打开Anaconda Prompt或者终端,并创建一个新的conda环境,可以使用命令:conda create -n tf2.0 python=3.7 3. 激活新创建的环境,可以使用命令:conda activate tf2.0 4. 使用conda安装Tensorflow 2.0,可以使用命令:conda install tensorflow-gpu=2.0.0 5. 等待安装完成后,就成功配置了conda中的Tensorflow 2.0环境。 另外,如果你想使用pip进行安装,也可以按照以下步骤进行: 1. 激活你的conda环境,可以使用命令:conda activate tf2.0 2. 使用pip安装Tensorflow 2.0,可以使用命令:pip install tensorflow==2.0.0 -i https://pypi.tuna.tsinghua.edu.cn/simple 这样你就成功配置了conda中的Tensorflow 2.0环境。希望对你有帮助!<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [深度学习(基于Tensorflow2.0学习笔记——Day2](https://download.csdn.net/download/weixin_38747211/14884742)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [Conda安装Tensorflow2.0](https://blog.csdn.net/u010442263/article/details/125567460)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [Anaconda安装+Tensorflow2.0安装配置+Pycharm安装+GCN调试(Window 10)](https://blog.csdn.net/adreammaker/article/details/125506038)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值