tf.nn.dropout讲解

本文阐述了TensorFlow中tf.nn.dropout函数的工作原理,用于在训练神经网络时防止过拟合。通过随机丢弃部分神经元,即以一定概率使神经元在当前训练周期内不参与计算和权值更新,从而提升模型泛化能力。

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

Dropout原理简述:

来自这位大佬

tf.nn.dropout是TensorFlow里面为了防止或减轻过拟合而使用的函数,它一般用在全连接层

Dropout就是在不同的训练过程中随机扔掉一部分神经元。也就是让某个神经元的激活值以一定的概率p,让其停止工作,这次训练过程中不更新权值,也不参加神经网络的计算。但是它的权重得保留下来(只是暂时不更新而已),因为下次样本输入时它可能又得工作了。 示意图如下:
在这里插入图片描述

tf.nn.dropout

tf.nn.dropout(
    x,
    keep_prob,
    noise_shape=None,
    seed=None,
    name=None
)
'''
Args:
	x: A floating point tensor.
	keep_prob: A scalar Tensor with the same type as x. The probability that each element is kept.
	noise_shape: A 1-D Tensor of type int32, representing the shape for randomly generated keep/drop flags.
	seed: A Python integer. Used to create random seeds. See tf.set_random_seed for behavior.
	name: A name for this operation (optional).
Returns:
    A Tensor of the same shape of x.
'''

说明

实现dropout,使用概率keep_prob,输出按1/keep_prob放大的输入元素,否则输出0。缩放使得预期的总和不变。

x:输入,一般是全连接网络的输出
keep_prob: 设置神经元被选中的概率,在初始化时keep_prob是一个占位符, keep_prob =tf.placeholder(tf.float32) 。tensorflow在run时设置keep_prob具体的值,例如keep_prob: 0.5
注意:train的时候才是dropout起作用的时候,设置0<keep_prob<1,
dev和test的时候不应该让dropout起作用,设置 keep_prob=1.0

我用的是MobileNetv2 模型训练了一个番茄叶片分类模型,可以分类四种叶片但是精度不太好,如果我把叶片如果离镜头比较远或比较近的话,它都会识别不出来,非得用摄像头把整个叶片的边缘正好框住才可以识别出来。怎么可以让它对距离要求没那么苛刻就可以识别出来 应该怎么做,给我最切实可行的方法, 下面是我的训练代码文件,帮我修改代码,细致讲解,并添加详细注释,我是初学者,要让我看懂 """ @File : MobileNetTrain.py @Author : GiperHsiue @Time : 2023/5/29 18:18 """ import tensorflow as tf import matplotlib.pyplot as plt from time import * import os # 数据集加载函数,指明数据集的位置并统一处理为imgheight*imgwidth的大小,同时设置batch def data_load(data_dir, test_data_dir, img_height, img_width, batch_size): # 加载训练集 train_ds = tf.keras.preprocessing.image_dataset_from_directory( data_dir, label_mode='categorical', seed=123, image_size=(img_height, img_width), batch_size=batch_size) # 加载测试集 val_ds = tf.keras.preprocessing.image_dataset_from_directory( test_data_dir, label_mode='categorical', seed=123, image_size=(img_height, img_width), batch_size=batch_size) class_names = train_ds.class_names # 返回处理之后的训练集、验证集和类名 return train_ds, val_ds, class_names # 构建mobilenet模型 # 模型加载,指定图片处理的大小和是否进行迁移学习 def model_load(IMG_SHAPE=(128, 128, 3), class_num=3,alpha=0.35): # 微调的过程中不需要进行归一化的处理 # 加载预训练的mobilenet模型 base_model = tf.keras.applications.MobileNetV2(input_shape=IMG_SHAPE, include_top=False, weights='imagenet', alpha=alpha ) # 将模型的主干参数进行冻结 base_model.trainable = False model = tf.keras.models.Sequential([ # 进行归一化的处理 tf.keras.layers.experimental.preprocessing.Rescaling(1. / 127.5, offset=-1, input_shape=IMG_SHAPE), # 设置主干模型 base_model, # 对主干模型的输出进行全局平均池化 tf.keras.layers.GlobalAveragePooling2D(), # 通过全连接层映射到最后的分类数目上 tf.keras.layers.Dense(class_num, activation='softmax') ]) model.summary() # 模型训练的优化器为adam优化器,模型的损失函数为交叉熵损失函数 model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) return model # 展示训练过程的曲线 def showAccuracyAndLoss(history): # 从history中提取模型训练集和验证集准确率信息和误差信息 acc = history.history['accuracy'] val_acc = history.history['val_accuracy'] loss = history.history['loss'] val_loss = history.history['val_loss'] # 按照上下结构将图画输出 plt.figure(figsize=(8, 8)) plt.subplot(2, 1, 1) plt.plot(acc, label='Training Accuracy') plt.plot(val_acc, label='Validation Accuracy') plt.legend(loc='lower right') plt.ylabel('Accuracy') plt.ylim([min(plt.ylim()), 1]) plt.title('Training and Validation Accuracy') plt.subplot(2, 1, 2) plt.plot(loss, label='Training Loss') plt.plot(val_loss, label='Validation Loss') plt.legend(loc='upper right') plt.ylabel('Cross Entropy') plt.title('Training and Validation Loss') plt.xlabel('epoch') # plt.savefig('results/results_mobilenet.png', dpi=100) filename = 'results_mobilenet.png' index = 1 while os.path.isfile(os.path.join('resultsPng', filename)): filename = 'results_mobilenet' + str(index) + '.png' index += 1 filename = 'resultsPng/' + filename plt.savefig(filename, dpi=100) def train(epochs): # 开始训练 begin_time = time() train_ds, val_ds, class_names = data_load("G:/tomatoMobilenet/split_data/train", "G:/tomatoMobilenet/split_data/test", 128, 128, 16) print(class_names) # 加载模型 model = model_load(class_num=len(class_names)) # 指明训练的轮数epoch,开始训练 history = model.fit(train_ds, validation_data=val_ds, epochs=epochs) model.save("G:/tomatoMobilenet/TomatoRecognition/models/mobilenet_fv.h5") # 记录结束时间 end_time = time() run_time = end_time - begin_time print('该循环程序运行时间:', run_time, "s") # 该循环程序运行时间: 1.4201874732 showAccuracyAndLoss(history) if __name__ == '__main__': train(epochs=30)
最新发布
07-31
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值