申请免费网站多少钱,网站云主机吗,wordpress如何添加视频,数据库工程师DAY 52 神经网络调参指南 知识点回顾#xff1a; 随机种子内参的初始化神经网络调参指南 参数的分类调参的顺序各部分参数的调整心得 一.随机种子 import torch
import torch.nn as nn# 定义简单的线性模型#xff08;无隐藏层#xff09;
# 输入2个纬度的数据#xff0c;… DAY 52 神经网络调参指南 知识点回顾 随机种子内参的初始化神经网络调参指南 参数的分类调参的顺序各部分参数的调整心得 一.随机种子 import torch
import torch.nn as nn# 定义简单的线性模型无隐藏层
# 输入2个纬度的数据得到1个纬度的输出
class SimpleNet(nn.Module):def __init__(self):super(SimpleNet, self).__init__()# 线性层2个输入特征1个输出特征self.linear nn.Linear(2, 1)def forward(self, x):# 前向传播y w1*x1 w2*x2 breturn self.linear(x)# 创建模型实例
model SimpleNet()# 查看模型参数
print(模型参数:)
for name, param in model.named_parameters():print(f{name}: {param.data}) 之前我们说过torch中很多场景都会存在随机数 1. 权重、偏置的随机初始化 2. 数据加载shuffling打乱与批次加载随机批次加载的随机化 3. 数据增强的随机化随机旋转、缩放、平移、裁剪等 4. 随机正则化dropout 5. 优化器中的随机性 import torch
import numpy as np
import os
import random# 全局随机函数
def set_seed(seed42, deterministicTrue):设置全局随机种子确保实验可重复性参数:seed: 随机种子值默认为42deterministic: 是否启用确定性模式默认为True# 设置Python的随机种子random.seed(seed) os.environ[PYTHONHASHSEED] str(seed) # 确保Python哈希函数的随机性一致比如字典、集合等无序# 设置NumPy的随机种子np.random.seed(seed)# 设置PyTorch的随机种子torch.manual_seed(seed) # 设置CPU上的随机种子torch.cuda.manual_seed(seed) # 设置GPU上的随机种子torch.cuda.manual_seed_all(seed) # 如果使用多GPU# 配置cuDNN以确保结果可重复if deterministic:torch.backends.cudnn.deterministic Truetorch.backends.cudnn.benchmark False# 设置随机种子
set_seed(42) 介绍一下这个随机函数的几个部分 1. python的随机种子需要确保random模块、以及一些无序数据结构的一致性 2. numpy的随机种子控制数组的随机性 3. torch的随机种子控制张量的随机性在cpu和gpu上均适用 4. cuDNNCUDA Deep Neural Network library CUDA 深度神经网络库的随机性针对cuda的优化算法的随机性 上述种子可以处理大部分场景实际上还有少部分场景具体的函数可能需要自行设置其对应的随机种子。 二.内参的初始化 我们都知道神经网络的权重需要通过反向传播来实现更新那么最开始肯定需要一个值才可以更新参数。 这个最开始的值是什么样子的呢如果恰好他们就是那一组最佳的参数附近的数那么可能我训练的速度会快很多。为了搞懂这个问题帮助我们真正理解神经网络参数的本质我们需要深入剖析一下关注以下几个问题 1. 初始值的区间 2. 初始值的分布 3. 初始值是多少 我们来观察下pytorch默认初始化的权重 import torch
import torch.nn as nn
import matplotlib.pyplot as plt
import numpy as np# 设置设备
device torch.device(cuda:0 if torch.cuda.is_available() else cpu)# 定义极简CNN模型仅1个卷积层1个全连接层
class SimpleCNN(nn.Module):def __init__(self):super(SimpleCNN, self).__init__()# 卷积层输入3通道输出16通道卷积核3x3self.conv1 nn.Conv2d(3, 16, kernel_size3, padding1)# 池化层2x2窗口尺寸减半self.pool nn.MaxPool2d(kernel_size2)# 全连接层展平后连接到10个输出对应10个类别# 输入尺寸16通道 × 16x16特征图 16×16×164096self.fc nn.Linear(16 * 16 * 16, 10)def forward(self, x):# 卷积池化x self.pool(self.conv1(x)) # 输出尺寸: [batch, 16, 16, 16]# 展平x x.view(-1, 16 * 16 * 16) # 展平为: [batch, 4096]# 全连接x self.fc(x) # 输出尺寸: [batch, 10]return x# 初始化模型
model SimpleCNN()
model model.to(device)# 查看模型结构
print(model)# 查看初始权重统计信息
def print_weight_stats(model):# 卷积层conv_weights model.conv1.weight.dataprint(\n卷积层 权重统计:)print(f 均值: {conv_weights.mean().item():.6f})print(f 标准差: {conv_weights.std().item():.6f})print(f 理论标准差 (Kaiming): {np.sqrt(2/3):.6f}) # 输入通道数为3# 全连接层fc_weights model.fc.weight.dataprint(\n全连接层 权重统计:)print(f 均值: {fc_weights.mean().item():.6f})print(f 标准差: {fc_weights.std().item():.6f})print(f 理论标准差 (Kaiming): {np.sqrt(2/(16*16*16)):.6f})# 改进的可视化权重分布函数
def visualize_weights(model, layer_name, weights, save_pathNone):plt.figure(figsize(12, 5))# 权重直方图plt.subplot(1, 2, 1)plt.hist(weights.cpu().numpy().flatten(), bins50)plt.title(f{layer_name} 权重分布)plt.xlabel(权重值)plt.ylabel(频次)# 权重热图plt.subplot(1, 2, 2)if len(weights.shape) 4: # 卷积层权重 [out_channels, in_channels, kernel_size, kernel_size]# 只显示第一个输入通道的前10个滤波器w weights[:10, 0].cpu().numpy()plt.imshow(w.reshape(-1, weights.shape[2]), cmapviridis)else: # 全连接层权重 [out_features, in_features]# 只显示前10个神经元的权重重塑为更合理的矩形w weights[:10].cpu().numpy()# 计算更合理的二维形状尝试接近正方形n_features w.shape[1]side_length int(np.sqrt(n_features))# 如果不能完美整除添加零填充使能重塑if n_features % side_length ! 0:new_size (side_length 1) * side_lengthw_padded np.zeros((w.shape[0], new_size))w_padded[:, :n_features] ww w_padded# 重塑并显示plt.imshow(w.reshape(w.shape[0] * side_length, -1), cmapviridis)plt.colorbar()plt.title(f{layer_name} 权重热图)plt.tight_layout()if save_path:plt.savefig(f{save_path}_{layer_name}.png)plt.show()# 打印权重统计
print_weight_stats(model)# 可视化各层权重
visualize_weights(model, Conv1, model.conv1.weight.data, initial_weights)
visualize_weights(model, FC, model.fc.weight.data, initial_weights)# 可视化偏置
plt.figure(figsize(12, 5))# 卷积层偏置
conv_bias model.conv1.bias.data
plt.subplot(1, 2, 1)
plt.bar(range(len(conv_bias)), conv_bias.cpu().numpy())
plt.title(卷积层 偏置)# 全连接层偏置
fc_bias model.fc.bias.data
plt.subplot(1, 2, 2)
plt.bar(range(len(fc_bias)), fc_bias.cpu().numpy())
plt.title(全连接层 偏置)plt.tight_layout()
plt.savefig(biases_initial.png)
plt.show()print(\n偏置统计:)
print(f卷积层偏置 均值: {conv_bias.mean().item():.6f})
print(f卷积层偏置 标准差: {conv_bias.std().item():.6f})
print(f全连接层偏置 均值: {fc_bias.mean().item():.6f})
print(f全连接层偏置 标准差: {fc_bias.std().item():.6f}) 那我们监控权重图的目的是什么呢 训练时权重会随反向传播迭代更新。通过权重分布图能直观看到其从初始化如随机分布到逐渐收敛、形成规律模式的动态变化理解模型如何一步步 “学习” 特征 。比如卷积层权重初期杂乱训练后可能聚焦于边缘、纹理等特定模式。 识别梯度异常 1. 梯度消失若权重分布越来越集中在 0 附近且更新幅度极小可能是梯度消失模型难学到有效特征比如深层网络用 Sigmoid 激活易出现 。 2. 梯度爆炸权重值突然大幅震荡、超出合理范围比如从 [-0.1, 0.1] 跳到 [-10, 10] 要警惕梯度爆炸可能让训练崩溃。 借助tensorboard可以看到训练过程中权重图的变化。 三.神经网络调参指南 1.参数的分类 2.调参顺序 作业对于day 41的简单cnn看看是否可以借助调参指南进一步提高精度。 基础CNN模型代码 import tensorflow as tf
from tensorflow.keras import layers, models
from tensorflow.keras.datasets import cifar10
from tensorflow.keras.utils import to_categorical# 加载数据
(train_images, train_labels), (test_images, test_labels) cifar10.load_data()# 数据预处理
train_images train_images.astype(float32) / 255
test_images test_images.astype(float32) / 255
train_labels to_categorical(train_labels)
test_labels to_categorical(test_labels)# 基础CNN模型
model models.Sequential([layers.Conv2D(32, (3, 3), activationrelu, input_shape(32, 32, 3)),layers.MaxPooling2D((2, 2)),layers.Conv2D(64, (3, 3), activationrelu),layers.MaxPooling2D((2, 2)),layers.Conv2D(64, (3, 3), activationrelu),layers.Flatten(),layers.Dense(64, activationrelu),layers.Dense(10, activationsoftmax)
])model.compile(optimizeradam,losscategorical_crossentropy,metrics[accuracy])history model.fit(train_images, train_labels, epochs10, batch_size64,validation_data(test_images, test_labels)) 增加模型复杂度 model models.Sequential([layers.Conv2D(64, (3, 3), activationrelu, input_shape(32, 32, 3), paddingsame),layers.BatchNormalization(),layers.Conv2D(64, (3, 3), activationrelu, paddingsame),layers.BatchNormalization(),layers.MaxPooling2D((2, 2)),layers.Dropout(0.25),layers.Conv2D(128, (3, 3), activationrelu, paddingsame),layers.BatchNormalization(),layers.Conv2D(128, (3, 3), activationrelu, paddingsame),layers.BatchNormalization(),layers.MaxPooling2D((2, 2)),layers.Dropout(0.25),layers.Conv2D(256, (3, 3), activationrelu, paddingsame),layers.BatchNormalization(),layers.Conv2D(256, (3, 3), activationrelu, paddingsame),layers.BatchNormalization(),layers.MaxPooling2D((2, 2)),layers.Dropout(0.25),layers.Flatten(),layers.Dense(512, activationrelu),layers.BatchNormalization(),layers.Dropout(0.5),layers.Dense(10, activationsoftmax)
]) 优化器调参 from tensorflow.keras.optimizers import Adamoptimizer Adam(learning_rate0.001, beta_10.9, beta_20.999, epsilon1e-07)
model.compile(optimizeroptimizer,losscategorical_crossentropy,metrics[accuracy]) 数据增强 from tensorflow.keras.preprocessing.image import ImageDataGeneratordatagen ImageDataGenerator(rotation_range15,width_shift_range0.1,height_shift_range0.1,horizontal_flipTrue,zoom_range0.1
)
datagen.fit(train_images)history model.fit(datagen.flow(train_images, train_labels, batch_size64),epochs50,validation_data(test_images, test_labels)) 早停和模型检查点 from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpointcallbacks [EarlyStopping(monitorval_loss, patience10, restore_best_weightsTrue),ModelCheckpoint(best_model.h5, monitorval_accuracy, save_best_onlyTrue)
]history model.fit(..., callbackscallbacks, epochs100) 浙大疏锦行
文章转载自: http://www.morning.mlwhd.cn.gov.cn.mlwhd.cn http://www.morning.xhrws.cn.gov.cn.xhrws.cn http://www.morning.ydxg.cn.gov.cn.ydxg.cn http://www.morning.tjjkn.cn.gov.cn.tjjkn.cn http://www.morning.kmrgl.cn.gov.cn.kmrgl.cn http://www.morning.nhgfz.cn.gov.cn.nhgfz.cn http://www.morning.gthwr.cn.gov.cn.gthwr.cn http://www.morning.qdlr.cn.gov.cn.qdlr.cn http://www.morning.dtrz.cn.gov.cn.dtrz.cn http://www.morning.tcpnp.cn.gov.cn.tcpnp.cn http://www.morning.jbztm.cn.gov.cn.jbztm.cn http://www.morning.pclgj.cn.gov.cn.pclgj.cn http://www.morning.ltffk.cn.gov.cn.ltffk.cn http://www.morning.wwklf.cn.gov.cn.wwklf.cn http://www.morning.jtybl.cn.gov.cn.jtybl.cn http://www.morning.fdlyh.cn.gov.cn.fdlyh.cn http://www.morning.wyzby.cn.gov.cn.wyzby.cn http://www.morning.gbfck.cn.gov.cn.gbfck.cn http://www.morning.xkgyh.cn.gov.cn.xkgyh.cn http://www.morning.gycyt.cn.gov.cn.gycyt.cn http://www.morning.csdgt.cn.gov.cn.csdgt.cn http://www.morning.wqtzs.cn.gov.cn.wqtzs.cn http://www.morning.ltqzq.cn.gov.cn.ltqzq.cn http://www.morning.rlns.cn.gov.cn.rlns.cn http://www.morning.lkjzz.cn.gov.cn.lkjzz.cn http://www.morning.kgjyy.cn.gov.cn.kgjyy.cn http://www.morning.xesrd.com.gov.cn.xesrd.com http://www.morning.dhqg.cn.gov.cn.dhqg.cn http://www.morning.wnhml.cn.gov.cn.wnhml.cn http://www.morning.djxnw.cn.gov.cn.djxnw.cn http://www.morning.bcngs.cn.gov.cn.bcngs.cn http://www.morning.fsjcn.cn.gov.cn.fsjcn.cn http://www.morning.jkbqs.cn.gov.cn.jkbqs.cn http://www.morning.tpps.cn.gov.cn.tpps.cn http://www.morning.ktntj.cn.gov.cn.ktntj.cn http://www.morning.hlrtzcj.cn.gov.cn.hlrtzcj.cn http://www.morning.wypyl.cn.gov.cn.wypyl.cn http://www.morning.xstfp.cn.gov.cn.xstfp.cn http://www.morning.pxtgf.cn.gov.cn.pxtgf.cn http://www.morning.nlgmr.cn.gov.cn.nlgmr.cn http://www.morning.rqbkc.cn.gov.cn.rqbkc.cn http://www.morning.bnkcl.cn.gov.cn.bnkcl.cn http://www.morning.knzdt.cn.gov.cn.knzdt.cn http://www.morning.xjwtq.cn.gov.cn.xjwtq.cn http://www.morning.wnnfh.cn.gov.cn.wnnfh.cn http://www.morning.sqmbb.cn.gov.cn.sqmbb.cn http://www.morning.qmncj.cn.gov.cn.qmncj.cn http://www.morning.xtrzh.cn.gov.cn.xtrzh.cn http://www.morning.hfxks.cn.gov.cn.hfxks.cn http://www.morning.ztdlp.cn.gov.cn.ztdlp.cn http://www.morning.kdnrc.cn.gov.cn.kdnrc.cn http://www.morning.qwqzk.cn.gov.cn.qwqzk.cn http://www.morning.jwskq.cn.gov.cn.jwskq.cn http://www.morning.lfbzg.cn.gov.cn.lfbzg.cn http://www.morning.kdbcx.cn.gov.cn.kdbcx.cn http://www.morning.gkgr.cn.gov.cn.gkgr.cn http://www.morning.wdykx.cn.gov.cn.wdykx.cn http://www.morning.bpmtr.cn.gov.cn.bpmtr.cn http://www.morning.zdsdn.cn.gov.cn.zdsdn.cn http://www.morning.ltpph.cn.gov.cn.ltpph.cn http://www.morning.ypktc.cn.gov.cn.ypktc.cn http://www.morning.fllfz.cn.gov.cn.fllfz.cn http://www.morning.clfct.cn.gov.cn.clfct.cn http://www.morning.hhkzl.cn.gov.cn.hhkzl.cn http://www.morning.nlbhj.cn.gov.cn.nlbhj.cn http://www.morning.yybcx.cn.gov.cn.yybcx.cn http://www.morning.nzcys.cn.gov.cn.nzcys.cn http://www.morning.csnmd.cn.gov.cn.csnmd.cn http://www.morning.kxypt.cn.gov.cn.kxypt.cn http://www.morning.wtxdp.cn.gov.cn.wtxdp.cn http://www.morning.deupp.com.gov.cn.deupp.com http://www.morning.trrd.cn.gov.cn.trrd.cn http://www.morning.seoqun.com.gov.cn.seoqun.com http://www.morning.kqbzy.cn.gov.cn.kqbzy.cn http://www.morning.zgdnd.cn.gov.cn.zgdnd.cn http://www.morning.pjtw.cn.gov.cn.pjtw.cn http://www.morning.nkiqixr.cn.gov.cn.nkiqixr.cn http://www.morning.dlwzm.cn.gov.cn.dlwzm.cn http://www.morning.srgnd.cn.gov.cn.srgnd.cn http://www.morning.mpnff.cn.gov.cn.mpnff.cn