tensorflow-CIFAR-10实例-代码解读

简单做一个记录吧

纸质的写起来太费劲了,效率不高。

把一些函数揉在一起了,只能算伪代码了,因为是给人看的嘛。


最近看到cifar10.py中的

def train():

interence构建模型,最主要的是第一层定义


衰减系数wd 用于向 losses 添加L2正则化,可以防止过拟合,提高泛化能力:

def inference(images):
# conv1
  with tf.variable_scope('conv1') as scope:
    kernel = _variable_with_weight_decay('weights', #初始化weights
                                         shape=[5, 5, 3, 64],
                                         stddev=5e-2,
                                         wd=None)
        dtyoe=tf.float32    #或者64
        var = tf.get_variable(name,shape,tf.truncated_name_initializer)  #初始化最实质性的一步
    conv = tf.nn.conv2d(images, kernel, [1, 1, 1, 1], padding='SAME')  #tf标准的一步
    biases = _variable_on_cpu('biases', [64], tf.constant_initializer(0.0))    #以0初始化biases
    pre_activation = tf.nn.bias_add(conv, biases)   #标准步骤,将一维的biases加入N 维的conv
    conv1 = tf.nn.relu(pre_activation, name=scope.name)  #relu
    _activation_summary(conv1) #生成一个汇总,具体操作是下面三行
        tensor_name = re.sub('%s_[0-9]*/' % TOWER_NAME, '', x.op.name) #字符的匹配替换进行 【还不理解】
        tf.summary.histogram(tensor_name + '/activations', x)    #生成一个汇总直方图
        tf.summary.scalar(tensor_name + '/sparsity',    #先是归零,然后进行求和
                                       tf.nn.zero_fraction(x))
  # pool1
  pool1 = tf.nn.max_pool(conv1, ksize=[1, 3, 3, 1], strides=[1, 2, 2, 1],
                         padding='SAME', name='pool1')
  # norm1
  norm1 = tf.nn.lrn(pool1, 4, bias=1.0, alpha=0.001 / 9.0, beta=0.75,
                    name='norm1')
  #conv2
  #norm2
  #pool2
  #local3
  #local4
 with tf.variable_scope('local4') as scope:
    weights = _variable_with_weight_decay('weights', shape=[384, 192],
                                          stddev=0.04, wd=0.004)
    biases = _variable_on_cpu('biases', [192], tf.constant_initializer(0.1))
    local4 = tf.nn.relu(tf.matmul(local3, weights) + biases, name=scope.name)
    _activation_summary(local4)


  # laner layer(WX+b)  为提高效率,在logits层中内置了softmax层,因而没有显示的用softmax
  with tf.variable_scope('softmax_linear') as scope:
    weights = _variable_with_weight_decay('weights', [192, NUM_CLASSES],
                                          stddev=1/192.0, wd=None)
    biases = _variable_on_cpu('biases', [NUM_CLASSES],
                              tf.constant_initializer(0.0))
    softmax_linear = tf.add(tf.matmul(local4, weights), biases, name=scope.name)
    _activation_summary(softmax_linear)
return softmax_linear

模型构建完毕

视线回到train()函数中,计算loss

loss = cifar10.loss(logits,labels) #计算loss
    #返回float型的tensor
   labels = tf.cast(labels, tf.int64)    #转换类型,将labels投影到tf的格式中
   cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(
labels=labels, logits=logits, name='cross_entropy_per_example') #softmsx标签要求是一个目标一定只有一个标签,而不是多个
 cross_entropy_mean = tf.reduce_mean(cross_entropy, name='cross_entropy') #按照这个维度来计算平均值
 tf.add_to_collection('losses', cross_entropy_mean) 【还不理解】
 # 按照L2来衰减,以loss之和、所有的权重而这作为总的loss  
 # decay terms (L2 loss).
return tf.add_n(tf.get_collection('losses'), name='total_loss') # get_collection返回一系列的值 由add加到tf中

得到loss之后,进行训练,更新一次模型的参数

train_op = cifar10.train(loss, global_step)

train_op = cifar10.train(loss, global_step)
    #
        num_batches_per_epoch = NUM_EXAMPLES_PER_EPOCH_FOR_TRAIN / FLAGS.batch_size 
            #NUM——EXAMPLE是全局,50000个训练样本,剩余为测试样本,F.batch_size是人工输入的参数可以是128
        decay_steps = int(num_batches_per_epoch * NUM_EPOCHS_PER_DECAY) # 后者为全局变量,程序中写的350
            # 不断衰减学习率,指数衰减
            lr = tf.train.exponential_decay(INITIAL_LEARNING_RATE,
                                  global_step,  # learning_rate=decay rete^(globle_step/decay_steps)
                                  decay_steps,
                                  LEARNING_RATE_DECAY_FACTOR,
                                  staircase=True) #True时,为整数的变化,因此就会是阶梯状衰减
tf.summary.scalar('learning_rate',lr)    #输出包含单个标量值的摘要协议缓冲区。

生成所有损失和相关总和的 移动平均值 【还不理解】

loss_averages_op = _add_loss_summaries(total_loss)  #输入总的loss   返回用于生成移动均线的损失    
# 训练时保持参数的移动平均值通常是有益的, 加入0.9的衰减,使用# shadow_variable -= (1 - decay) * (shadow_variable - variable)来进行参数更新
loss_averages = tf.train.ExponentialMovingAverage(0.9, name='avg') # 训练时保持参数的移动平均值 
losses = tf.get_collection('losses') #将Graph.get_collection()使用默认gragh进行包装,返回一系列统一名字的列表
loss_averages_op = loss_averages.apply(losses + [total_loss])

计算梯度

  with tf.control_dependencies([loss_averages_op]): # 将Graph.control_dependencies()使用默认gragh进行包装
    opt = tf.train.GradientDescentOptimizer(lr) # 梯度下降算法的优化器
    grads = opt.compute_gradients(total_loss)    #计算梯度

# 将梯度应用与各个变量之中,
apply_gradient_op = opt.apply_gradients(grads, global_step=global_step)

在可训练参数以及梯度中 , 增加直方图,为可视化做准备

 for var in tf.trainable_variables():    #如果trainable被pass掉时,将新的变量增加到Gragh图中,返回变量Variable Objects的一个列表
    tf.summary.histogram(var.op.name, var) # 用于直方图输出摘要协议缓冲区。可以使数据在TendorBoard中可视化
  # Add histograms for gradients.  为梯度增加直方图
  for grad, var in grads:
    if grad is not None:
      tf.summary.histogram(var.op.name + '/gradients', grad)

跟踪所有变量的移动平均值

  # 更新后变量称为影子变量,采用滑动平均的方法更新参数
  variable_averages = tf.train.ExponentialMovingAverage(
      MOVING_AVERAGE_DECAY, global_step)
  variables_averages_op = variable_averages.apply(tf.trainable_variables())# trainable_variables上段有

将变量的依赖关系放在一起,返回一个整体

with tf.control_dependencies([apply_gradient_op, variables_averages_op]):#将一系列已经执行过的Tensor算子返回依赖关系【还不理解】
  train_op = tf.no_op(name='train') #op获得x,y,z的依赖关系,放在一个集合中一块进行操作
return train_op

跳出cifar10.py   

回到cifar10_train.py文件中,计算完train_op = cifar10.train(loss, global_step)  获得了有依赖关系的变量

#创建检查点与汇总保存的Hook, 
with tf.train.MonitoredTrainingSession(
        checkpoint_dir=FLAGS.train_dir, # 字符串,保存变量的位置
        hooks=[tf.train.StopAtStepHook(last_step=FLAGS.max_steps), # 参数1 设定停止训练的step
               tf.train.NanTensorHook(loss),    # 参数2 监控loss不出问题,否则报错
               _LoggerHook()],      #参数3   是一个类,记录log,包括loss和运行时间
                                其中tf.train.SessionRunHook用来最终确定graph,ops不再进行修改
        config=tf.ConfigProto(      #是tf.ConfigProto的一个实例,用来配置session
            log_device_placement=FLAGS.log_device_placement)) as mon_sess:
      while not mon_sess.should_stop():
        mon_sess.run(train_op)







几个不错的前辈的代码解读

https://blog.csdn.net/diamonjoy_zone/article/details/64905516


https://blog.csdn.net/hensonwells/article/details/75041175


https://blog.csdn.net/margretwg/article/details/70196001


https://zhuanlan.zhihu.com/p/25646408

anyway,宏观围观都要有


mnist很全的一个

https://blog.csdn.net/briblue/article/details/80398369

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
CIFAR-10代码解释需要结合具体的实现方式进行说明,以下是一个简单的CIFAR-10分类器的Python代码示例及解释: ```python # 导入必要的库 import torch import torchvision import torchvision.transforms as transforms import torch.nn as nn import torch.optim as optim # 定义transform,用于对CIFAR-10数据集进行预处理 transform = transforms.Compose( [transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]) # 加载训练集和测试集 trainset = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transform) trainloader = torch.utils.data.DataLoader(trainset, batch_size=4, shuffle=True, num_workers=2) testset = torchvision.datasets.CIFAR10(root='./data', train=False, download=True, transform=transform) testloader = torch.utils.data.DataLoader(testset, batch_size=4, shuffle=False, num_workers=2) # 定义分类器的类别 classes = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck') # 定义神经网络模型 class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(3, 6, 5) self.pool = nn.MaxPool2d(2, 2) self.conv2 = nn.Conv2d(6, 16, 5) self.fc1 = nn.Linear(16 * 5 * 5, 120) self.fc2 = nn.Linear(120, 84) self.fc3 = nn.Linear(84, 10) def forward(self, x): x = self.pool(torch.relu(self.conv1(x))) x = self.pool(torch.relu(self.conv2(x))) x = x.view(-1, 16 * 5 * 5) x = torch.relu(self.fc1(x)) x = torch.relu(self.fc2(x)) x = self.fc3(x) return x # 实例化神经网络模型 net = Net() # 定义损失函数和优化器 criterion = nn.CrossEntropyLoss() optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9) # 训练神经网络模型 for epoch in range(2): running_loss = 0.0 for i, data in enumerate(trainloader, 0): inputs, labels = data optimizer.zero_grad() outputs = net(inputs) loss = criterion(outputs, labels) loss.backward() optimizer.step() running_loss += loss.item() if i % 2000 == 1999: # 每2000个batch输出一次loss print('[%d, %5d] loss: %.3f' % (epoch + 1, i + 1, running_loss / 2000)) running_loss = 0.0 print('Finished Training') # 在测试集上测试神经网络模型 correct = 0 total = 0 with torch.no_grad(): for data in testloader: images, labels = data outputs = net(images) _, predicted = torch.max(outputs.data, 1) total += labels.size(0) correct += (predicted == labels).sum().item() print('Accuracy of the network on the 10000 test images: %d %%' % ( 100 * correct / total)) ``` 代码解释如下: 1. 导入必要的库,包括PyTorch、torchvision等。 2. 定义transform,用于对CIFAR-10数据集进行预处理。这里的transform包括将图像转换为Tensor格式并进行归一化处理。 3. 加载训练集和测试集。这里使用torchvision.datasets.CIFAR10方法从本地文件或网络中加载CIFAR-10数据集。 4. 定义分类器的类别,共10个类别。 5. 定义神经网络模型。这里使用卷积神经网络(Convolutional Neural Network, CNN)实现CIFAR-10分类器,包括两个卷积层、三个全连接层和ReLU激活函数。 6. 实例化神经网络模型。 7. 定义损失函数和优化器。这里使用交叉熵损失函数和随机梯度下降(SGD)优化器,其中学习率为0.001,动量为0.9。 8. 训练神经网络模型。这里使用两个epoch来训练神经网络模型,每个epoch包括多个batch的训练,其中每个batch的大小为4。在训练过程中,每2000个batch输出一次loss。 9. 在测试集上测试神经网络模型。这里使用测试集对训练好的神经网络模型进行测试,并计算模型的准确率。 以上就是一个简单的CIFAR-10分类器的Python代码示例及解释。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值