Tensorflow2学习(1)1 TensorFlow2学习1.1 张量(Tensor)1.1.1张量是多维数组(列表),用阶表示张量的维数:1.1.2创建一个Tensor1.2 常用函数1.3 简单实践(鸢尾花数据读取与神经网络分类)1.3.1 鸢尾花数据读取1.3.2 神经网络分类 1 TensorFlow2学习1.1 张量(Tensor)1.1.1张量是多维数组(列表),用阶表示张量的维数:
1.1.2创建一个Tensor1)tf.constant(张量内容,dtype=数据类型(可选)) import tensorflow as tf 注:张量的形状看shape的逗号隔开了几个数字,隔开了几个数字,张量就是几维。 2)tf.convert_to_tensor(数据名,dtype=数据类型(可选)) 将numpy的数据类型转换为tensor数据类型。 import tensorflow as tf 3)tf.fill(维度,指定值) 创建全为指定值的张量,其中指定值只能为标量。 a = tf.fill([2, 3], 9) 4)tf.random.normal(维度,mean=均值,stddev=标准差) 生成正态分布的随机数,默认均值为0,标准差为1 tf.random.truncated_normal(维度,mean=均值,stddev=标准差) 生成截断式正态分布的随机数,生成的数更向均值集中。 a = tf.random.normal([2, 2], mean=0.3, stddev=2) 4)tf.random.uniform(维度,minval=最小值,maxval=最大值) 生成均匀分布的随机数,生成数区间是前开后闭区间。 a = tf.random.uniform([2, 2], minval=-2, maxval=2) 1.2 常用函数1)tf.cast(张量名,dtype=数据类型) 强制tensor转换为该数据类型 2)tf.reduce_min(张量名) 计算张量维度上元素的最小值 3)tf.reduce_max(张量名) 计算张量维度上元素的最大值 x1 = tf.constant([1, 2, 3], dtype=tf.int64) 4)tf.reduce_mean(张量名,axis=操作轴) 计算张量沿着指定维度的平均值,其中axis为1,表示行,为0表示列,若axis没写,则对整个张量求平均,先列求,再行求。 5)tf.reduce_sum(张量名,axis=操作轴) 计算张量沿着指定维度的和。 x = tf.constant([[1, 2, 3], [3, 2, 3]], dtype=tf.float32) 6)tf.Variable(初始值) 将变量标记为“可训练”,被标记的变量会在反向传播中记录梯度信息。神经网络训练中,常用该函数标记待训练参数。 w = tf.Variable(tf.random.uniform([2, 2], minval=0, maxval=1)) 注:可以用来表示损失函数loss的参数w,即将w标记为可训练变量。 7)tensorflow中的数学运算
8)tf.data.Dataset.from_tensor_slices((输入特征,标签)) 切分传入张量的第一维度,生成输入特征/标签对,构建数据集。该方法可以读取numpy与tensor两种格式的数据。 feature = tf.constant([1, 3, 10, 24]) 9)tf.GradientTape() 用它的with结构记录计算过程,gradient求出张量的梯度,即求导。 其结构一般为: with tf.GradientTape() as tape: 下面举个例子:其中损失函数为w的平方,w=3.0 with tf.GradientTape() as tape: 10)enumerate(列表名) 是python的内建函数,它可以遍历每个元素(如列表、元组或字符串),组合形式为:索引 元素,常在for循环中使用。 seq = ['one', 'two', 'three'] 11)tf.one_hot(待转换数据,depth=几分类) 在分类问题中,用独热码,即one_hot做标签,‘1’表示是,‘0’表示非,将待转换数据,转换为one_hot形式的数据进行输出。 classes = 5 12)tf.nn.softmax(待转换数据) 使n个输出变成0~1的值,且其和为1。 y = tf.Variable([1.02, 2.30, -0.19]) 13)assign_sub(w要自减的内容) 赋值操作,更新参数的值并返回。要更新的参数的前提是,其是可训练的,即初始w值是variable构建的。 w = tf.Variable(3) 14)tf.argmax(张量名,axis=操作轴) 返回张量沿指定维度最大值的索引。 x = np.array([[1, 2, 3], [2, 3, 4], [4, 5, 6]]) 1.3 简单实践(鸢尾花数据读取与神经网络分类)1.3.1 鸢尾花数据读取from sklearn import datasets 1.3.2 神经网络分类实现该功能我们可以分三步走:
1)测试结果
2)acc/loss可视化 以下为一个神经网络实现鸢尾花分类示例: import tensorflow as tf Tensorflow2学习(1)1 TensorFlow2学习1.1 张量(Tensor)1.1.1张量是多维数组(列表),用阶表示张量的维数:
1.1.2创建一个Tensor1)tf.constant(张量内容,dtype=数据类型(可选)) import tensorflow as tf 注:张量的形状看shape的逗号隔开了几个数字,隔开了几个数字,张量就是几维。 2)tf.convert_to_tensor(数据名,dtype=数据类型(可选)) 将numpy的数据类型转换为tensor数据类型。 import tensorflow as tf 3)tf.fill(维度,指定值) 创建全为指定值的张量,其中指定值只能为标量。 a = tf.fill([2, 3], 9) 4)tf.random.normal(维度,mean=均值,stddev=标准差) 生成正态分布的随机数,默认均值为0,标准差为1 tf.random.truncated_normal(维度,mean=均值,stddev=标准差) 生成截断式正态分布的随机数,生成的数更向均值集中。 a = tf.random.normal([2, 2], mean=0.3, stddev=2) 4)tf.random.uniform(维度,minval=最小值,maxval=最大值) 生成均匀分布的随机数,生成数区间是前开后闭区间。 a = tf.random.uniform([2, 2], minval=-2, maxval=2) 1.2 常用函数1)tf.cast(张量名,dtype=数据类型) 强制tensor转换为该数据类型 2)tf.reduce_min(张量名) 计算张量维度上元素的最小值 3)tf.reduce_max(张量名) 计算张量维度上元素的最大值 x1 = tf.constant([1, 2, 3], dtype=tf.int64) 4)tf.reduce_mean(张量名,axis=操作轴) 计算张量沿着指定维度的平均值,其中axis为1,表示行,为0表示列,若axis没写,则对整个张量求平均,先列求,再行求。 5)tf.reduce_sum(张量名,axis=操作轴) 计算张量沿着指定维度的和。 x = tf.constant([[1, 2, 3], [3, 2, 3]], dtype=tf.float32) 6)tf.Variable(初始值) 将变量标记为“可训练”,被标记的变量会在反向传播中记录梯度信息。神经网络训练中,常用该函数标记待训练参数。 w = tf.Variable(tf.random.uniform([2, 2], minval=0, maxval=1)) 注:可以用来表示损失函数loss的参数w,即将w标记为可训练变量。 7)tensorflow中的数学运算
8)tf.data.Dataset.from_tensor_slices((输入特征,标签)) 切分传入张量的第一维度,生成输入特征/标签对,构建数据集。该方法可以读取numpy与tensor两种格式的数据。 feature = tf.constant([1, 3, 10, 24]) labels = tf.constant([0, 0, 1, 1]) dataset = tf.data.Dataset.from_tensor_slices((feature, labels)) print(dataset) for i in dataset: print(i) #结果显示 <TensorSliceDataset shapes: ((), ()), types: (tf.int32, tf.int32)> (<tf.Tensor: id=9, shape=(), dtype=int32, numpy=1>, <tf.Tensor: id=10, shape=(), dtype=int32, numpy=0>) (<tf.Tensor: id=11, shape=(), dtype=int32, numpy=3>, <tf.Tensor: id=12, shape=(), dtype=int32, numpy=0>) (<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=24>, <tf.Tensor: id=16, shape=(), dtype=int32, numpy=1>) 9)tf.GradientTape() 用它的with结构记录计算过程,gradient求出张量的梯度,即求导。 其结构一般为: with tf.GradientTape() as tape: 若干个计算过程 grad = tape.gradient(函数, 对谁求导) 下面举个例子:其中损失函数为w的平方,w=3.0 with tf.GradientTape() as tape: w = tf.Variable(3.0) loss = tf.pow(w, 2) grad = tape.gradient(loss, w) print(grad) #结果显示 tf.Tensor(6.0, shape=(), dtype=float32) 10)enumerate(列表名) 是python的内建函数,它可以遍历每个元素(如列表、元组或字符串),组合形式为:索引 元素,常在for循环中使用。 seq = ['one', 'two', 'three'] for i, element in enumerate(seq): print(i, element) #结果显示 0 one 1 two 2 three 11)tf.one_hot(待转换数据,depth=几分类) 在分类问题中,用独热码,即one_hot做标签,‘1’表示是,‘0’表示非,将待转换数据,转换为one_hot形式的数据进行输出。 classes = 5 labels = tf.constant([1, 2, 3]) output = tf.one_hot(labels, classes) print(output) #结果显示 tf.Tensor( [[0. 1. 0. 0. 0.] [0. 0. 1. 0. 0.] [0. 0. 0. 1. 0.]], shape=(3, 5), dtype=float32) 12)tf.nn.softmax(待转换数据) 使n个输出变成0~1的值,且其和为1。 y = tf.Variable([1.02, 2.30, -0.19]) y_pro = tf.nn.softmax(y) print("After softmax, y_pro is:", y_pro) #结果显示 After softmax, y_pro is: tf.Tensor([0.2042969 0.73478234 0.06092078], shape=(3,), dtype=float32) 13)assign_sub(w要自减的内容) 赋值操作,更新参数的值并返回。要更新的参数的前提是,其是可训练的,即初始w值是variable构建的。 w = tf.Variable(3) w.assign_sub(1) # 实现w-1功能,即自减 print(w) #结果显示 <tf.Variable 'Variable:0' shape=() dtype=int32, numpy=2> 14)tf.argmax(张量名,axis=操作轴) 返回张量沿指定维度最大值的索引。 x = np.array([[1, 2, 3], [2, 3, 4], [4, 5, 6]]) print(x) print(tf.argmax(x, axis=1)) print(tf.argmin(x, axis=0)) #结果显示 [[1 2 3] [2 3 4] [4 5 6]] tf.Tensor([2 2 2], shape=(3,), dtype=int64) tf.Tensor([0 0 0], shape=(3,), dtype=int64) 1.3 简单实践(鸢尾花数据读取与神经网络分类)1.3.1 鸢尾花数据读取from sklearn import datasets from pandas import DataFrame import pandas as pd x_data = datasets.load_iris().data y_data = datasets.load_iris().target #print('鸢尾花数据:\n', x_data) #print('鸢尾花标签:\n', y_data) x_data = DataFrame(x_data, columns=['花萼长度', '花萼宽度', '花瓣长度', '花瓣宽度'])# 将其变成表格形式,并为每一列增加中文标签 pd.set_option('display.unicode.east_asian_width', True)# 设置表格为列名对其 print('鸢尾花数据:\n', x_data) x_data['类别'] = y_data # 为x_data增加一列类别,即原来定义的y_data print('增加一列后的表格为:\n', x_data) #结果显示 鸢尾花数据: 花萼长度 花萼宽度 花瓣长度 花瓣宽度 0 5.1 3.5 1.4 0.2 .. ... ... ... ... 149 5.9 3.0 5.1 1.8 [150 rows x 4 columns] 增加一列后的表格为: 花萼长度 花萼宽度 花瓣长度 花瓣宽度 类别 0 5.1 3.5 1.4 0.2 0 .. ... ... ... ... ... 149 5.9 3.0 5.1 1.8 2 [150 rows x 5 columns] 1.3.2 神经网络分类实现该功能我们可以分三步走:
1)测试结果
2)acc/loss可视化 以下为一个神经网络实现鸢尾花分类示例: import tensorflow as tf from sklearn import datasets import matplotlib.pyplot as plt import numpy as np # 第一步-准备数据-数据读取 x_data = datasets.load_iris().data y_data = datasets.load_iris().target # 第一步-准备数据-打乱数据 np.random.seed(1) # 使用相同的seed打乱,保证输入的数据与标签一一对应 np.random.shuffle(x_data) # 生成随机列表 np.random.seed(1) np.random.shuffle(y_data) tf.random.set_seed(1) # 第一步-准备数据-分成训练集和测试集 x_train = x_data[:-30] # 由开头到倒数第30个 y_train = y_data[:-30] x_test = x_data[-30:] # 由倒数第30个到最后 y_test = y_data[-30:] # 为防止数据集出现计算上的错误,我们将数据集转换类型 x_train = tf.cast(x_train, dtype=tf.float32) x_test = tf.cast(x_test, dtype=tf.float32) # 第一步-准备数据-特征值与标签配对,并以batch形式输入 train_fl = tf.data.Dataset.from_tensor_slices((x_train, y_train)).batch(32) test_fl = tf.data.Dataset.from_tensor_slices((x_test, y_test)).batch(32) # 第二步-搭建网络-定义所有相关参数(这一步可以在训练等模型写完后再完成) 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_result = [] # 每轮的loss记录于此,为后面的loss图像提供数据 test_acc = [] # 每轮的准确率记录于此,为后面的acc图像提供数据 epoch = 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_fl): # batch级别的循环,每个step循环一次batch with tf.GradientTape() as tape: y = tf.matmul(x_train, w1) b1 # 全连接层 y = tf.nn.softmax(y) # 输出0~1的真实值 y_ = tf.one_hot(y_train, depth=3) # 预测值 loss = tf.reduce_mean(tf.square(y_ - y)) # 损失函数 loss_all = loss.numpy() # 将每个step计算出的loss累加,为后面求loss平均值提供数据 grads = tape.gradient(loss, [w1, b1]) # 实现w与b的梯度更新:w1=w1-lr*w1_grad ,b1同理 w1.assign_sub(lr * grads[0]) b1.assign_sub(lr * grads[1]) print('Epoch {}, loss: {}'.format(epoch, loss_all/4)) train_loss_result.append(loss_all / 4) # 将4个step的loss求平均记录在变量中 loss_all = 0 # 将loss_all归零,为记录下一个epoch做准备 # 第四步-预测模型部分 total_correct, total_number = 0, 0 # 前者为测试结果为正确的数量,后者为样本总数量,都初始化为0 for x_test, y_test in test_fl: # 因为我们每个step为32,而我们数据只有30个,所以这里不使用enumerate y = tf.matmul(x_test, w1) b1 y = tf.nn.softmax(y) pred = tf.argmax(y, axis=1) # 返回预测值中最大的索引,即预测的分类 pred = tf.cast(pred, dtype=y_test.dtype) correct = tf.cast(tf.equal(pred, y_test), dtype=tf.int32) # 预测正确的结果保留下来 correct = tf.reduce_sum(correct) total_correct = int(correct) total_number = x_test.shape[0] acc = total_correct / total_number test_acc.append(acc) print('Test_acc:', acc) print('---------------------------') # 第五步-acc/loss可视化 plt.title('Loss Function Curve') plt.xlabel('Epoch') plt.ylabel('loss') # plt.rcParams['font.sans-serif'] = ['FangSong'] # plt.rcParams['axes.Unicode_minus'] = False plt.plot(train_loss_result, label='$Loss$') plt.legend() plt.show() plt.title('Acc Curve') plt.xlabel('Epoch') plt.ylabel('Acc') plt.plot(test_acc, label='$Accuracy$') plt.legend() plt.show() #结果显示 --------------------------- Epoch 499, loss: 0.02722732489928603 Test_acc: 0.9666666666666667 ---------------------------来源:https://www./content-4-719751.html |
|