tf.argmax()函数 tf.equal()函数 tf.cast()函数 tf.truncated_normal()

本文详细介绍了TensorFlow中常用的四个函数:tf.argmax用于寻找最大值索引;tf.equal用于比较两个张量是否相等;tf.cast用于转换数据类型;tf.truncated_normal用于生成截断正态分布的随机数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. tf.argmax()函数

tf.argmax可以认为就是np.argmax。tensorflow使用numpy实现的这个API。 
   简单的说,tf.argmax就是返回最大的那个数值所在的下标。tf.argmax(array,axis)

    当axis=1时返回每列最大值的下标,当axis=0时返回每行最大值的下班。

2. tf.equal()函数

tf.equal(A,B)是对比这两个矩阵或者向量的相等的元素,如果是相等的那就返回True,反正返回False,返回的值的矩阵维度和A是一样的

[python]  view plain  copy
  1. A = [[1,3,4,5,6]]    
  2. B = [[1,3,4,3,2]]  
  3.   
  4.   
  5. with tf.Session() as sess:    
  6.     print(sess.run(tf.equal(A, B)))  
  7.       
  8. [[ True  True  True False False]]  

3. tf.cast()函数

tf.cast(x, dtype)将x的数据格式转化成dtype.

[python]  view plain  copy
  1. a = tf.Variable([1,0,0,1,1])  
  2. b = tf.cast(a,dtype=tf.bool)  
  3. sess = tf.Session()  
  4.   
  5.   
  6. a = tf.Variable([1,0,0,1,1])  
  7. b = tf.cast(a,dtype=tf.bool)  
  8. sess = tf.Session()  
  9. sess.run(tf.global_variables_initializer())  
  10. print(sess.run(b))  
  11.   
  12. True False False  True  True]  

4. tf.truncated_normal()

tf.truncated_normal(shape, mean, stddev):shape表示生成张量的维度,mean是均值,stddev是标准差。这个函数产生正太分布,均值和标准差自己设定。这是一个截断的产生正太分布的函数,就是说产生正太分布的值如果与均值的差值大于两倍的标准差,那就重新生成。和一般的正太分布的产生随机数据比起来,这个函数产生的随机数与均值的差距不会超过两倍的标准差,但是一般的别的函数是可能的。

[python]  view plain  copy
  1. import tensorflow as tf;    
  2. import numpy as np;    
  3. import matplotlib.pyplot as plt;    
  4.   
  5. c = tf.truncated_normal(shape=[10,10], mean=0, stddev=1)    
  6.   
  7. with tf.Session() as sess:    
  8.     print(sess.run(c))  
  9.       
  10. [[ 0.56077307  1.74287605 -0.15655719  0.87136668 -0.4219175   0.94079614  
  11.   -1.31186545  1.94287431  0.70748854  1.15509737]  
  12.  [ 0.32469562 -0.91890186 -0.44398952  1.25986481 -1.07295966  0.21889997  
  13.    0.19389877 -1.22909117  1.34865403  0.87812191]  
  14.  [-0.83542323 -0.05598836 -1.05256093 -1.16475403 -0.17121609 -0.55075479  
  15.   -0.37847248  0.14151201  0.36596569  0.55171227]  
  16.  [ 0.45216689  0.12429248 -0.4333829  -0.00368057 -0.20933141  0.5465408  
  17.    1.06096387  1.47238612 -1.99268937  1.28203201]  
  18.  [ 0.36932501  0.30012983  1.94679129  0.59601396 -0.16721351 -0.42786792  
  19.    0.917597   -1.6504811  -0.81060582 -0.35126168]  
  20.  [-1.48954999 -0.42889833  0.31517059  1.00009787  0.26073182  1.26285052  
  21.   -1.80997884  0.51399821 -0.27673215  0.15389352]  
  22.  [ 0.8669793  -0.28650126  1.39484227 -0.4041909  -1.70028269  0.58513969  
  23.    0.75772232 -0.47386578 -0.34529254 -0.71658897]  
  24.  [ 0.74709773 -0.0835886   1.14453304  0.70367438  0.07037418 -0.15808868  
  25.    0.23158503 -0.67268801  0.55869597  0.12777361]  
  26.  [-0.52604282  0.64181858 -0.04147881  0.78596973  0.69087744  0.56500375  
  27.   -1.12409449 -0.42864376  0.30804652  1.33116138]  
  28.  [-1.36940789 -0.4526186  -0.87445366  0.19748467 -0.06541829 -0.2672275  
  29.    0.63084471  0.76155263  0.83874393  0.91775542]]  
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("--------------------------") 帮我看看这段代码,我主要是想知道“correct = tf.cast(tf.equal(pred, y_test), dtype=tf.int32) correct = tf.reduce_sum(correct)”这段的correct是怎么做到累积的,不是每次循环都变成0或1了吗
最新发布
03-08
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值