cifar实例编译之model的生成

本教程详细介绍如何使用Caffe框架训练CIFAR-10数据集,包括数据准备、转换、计算均值、配置训练参数及模型微调等步骤。

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

转载自:http://blog.youkuaiyun.com/zb1165048017/article/details/51476516

参考:<span style="font-family: Arial, Helvetica, sans-serif;">http://blog.youkuaiyun.com/chengzhongxuyou/article/details/50715455</span>

准备工作

按照之前的教程,成功生成过caffe,并且编译整个caffe.sln项目工程,在\caffe-master\Build\x64\Debug生成了一堆exe文件,后面会使用到除了caffe.exe的另外一个exe

【PS】很多VS安装过程中出现问题的,比如XX加载失败,XX未找到等,请自行寻找问题,很可能是原来的VS没卸载干净,或者VS版本缺少一些文件等导致。正常情况下,第一次编译只有libcaffe.lib显示失败,不会出现其它error

第一步

下载cifar的数据集

官网地址:http://www.cs.toronto.edu/~kriz/cifar.html

我的百度云地址:二进制数据文件链接:http://pan.baidu.com/s/1hrRApwC 密码:1dxy

.mat格式连接:链接:http://pan.baidu.com/s/1hr6B7Xa密码:f343

多一句嘴,这个数据集是彩色图片,也即具有RGB三通道,数据存储方式是一行为一张图片,包含3*32*32=3072个像素属性,具体多少张图片,有兴趣的可以去官网看看,或者看看数据集的存储格式:样本数(图片数)*3072

与训练model无关】下面代码是用matlab写的,用于显示其中一个样本,当然你可以用reshape函数,前面我介绍过这个函数

  1. image=zeros(32,32,3);  
  2. count=0;  
  3. for i=1:3  
  4.     for j=1:32  
  5.         for k=1:32  
  6.             count=count+1;  
  7.            image(j,k,i)=data(1000,count);  
  8.         end  
  9.     end  
  10. end  
  11. imshow(uint8(image))  
image=zeros(32,32,3);
count=0;
for i=1:3
    for j=1:32
        for k=1:32
            count=count+1;
           image(j,k,i)=data(1000,count);
        end
    end
end
imshow(uint8(image))


第二步

下载完毕以后,解压得到数据,请核对是否与下图一样


按照下列路径,在自己的caffe目录下建立input_folder文件夹,并拷贝相应数据集


第三步

在input_folder的上一级目录,也就是Debug目录建立一个bat文件(名称随意,我用的是convert.bat),用于转换数据集格式,内容如下

  1. convert_cifar_data.exe  input_folder output_folders leveldb  
  2. pause  
convert_cifar_data.exe  input_folder output_folders leveldb
pause
【PS】此处的exe就是在编译caffe.sln时候生成的,如果没有,请在VS中修改生成模式为DEBUG,而非release



【PS】caffe-windows是caffe官方提供的caffe,与caffe-master差不多,我这里为了从头演示,没有在master里面操作,无视之即可

运行此bat文件,会生成一个文件夹output_folders,里面有两个文件夹,请核对路径以及文件数目





第四步

计算均值,新建另一个bat文件(本文采用mean.bat),如下图所示,请核对路径

  1. compute_image_mean.exe output_folders/cifar10_train_leveldb mean.binaryproto  
  2.   
  3. pause  
compute_image_mean.exe output_folders/cifar10_train_leveldb mean.binaryproto

pause

双击此bat文件,不出意外会出现下面问题:

解决方法有两种

第一种:打开caffe.sln,修改compute_image_mean.cpp


重新生成一下,得到新的计算均值的exe文件【电脑编译中。。。等待ing。。。。】

第二种:感谢评论区 Liz_Huang的提示,直接在bat后面添加--backend=leveldb,同时也可以换成--backend=lmdb

编译完毕,重新运行bat文件,仔细检查debug文件夹,会发现有一个文件名为:mean.binaryproto

第五步

将debug文件夹下的mean.binaryproto以及output_folders下的两个文件夹拷贝到caffe-windows\examples\cifar10

在caffe-windows也就是caffe-master(根据版本自行决定)文件夹下新建一个bat文件,用于训练模型,本文使用train.bat

  1. .\Build\x64\Debug\caffe.exe train --solver=examples/cifar10/cifar10_quick_solver.prototxt  
  2. pause  
.\Build\x64\Debug\caffe.exe train --solver=examples/cifar10/cifar10_quick_solver.prototxt
pause
在运行之前需要修改几个文件,此处截图超过2M了,传不上来,读者自己核对路径以及CPU训练设置

cifar10_quick_solver.prototxt文件:

  1. # reduce the learning rate after 8 epochs (4000 iters) by a factor of 10  
  2.   
  3. # The train/test net protocol buffer definition  
  4. net: "examples/cifar10/cifar10_quick_train_test.prototxt"  
  5. # test_iter specifies how many forward passes the test should carry out.  
  6. # In the case of MNIST, we have test batch size 100 and 100 test iterations,  
  7. # covering the full 10,000 testing images.  
  8. test_iter: 100  
  9. # Carry out testing every 500 training iterations.  
  10. test_interval: 500  
  11. # The base learning rate, momentum and the weight decay of the network.  
  12. base_lr: 0.001  
  13. momentum: 0.9  
  14. weight_decay: 0.004  
  15. # The learning rate policy  
  16. lr_policy: "fixed"  
  17. # Display every 100 iterations  
  18. display: 100  
  19. # The maximum number of iterations  
  20. max_iter: 4000  
  21. # snapshot intermediate results  
  22. snapshot: 4000  
  23. snapshot_format: HDF5  
  24. snapshot_prefix: "examples/cifar10/cifar10_quick"  
  25. # solver mode: CPU or GPU  
  26. solver_mode: CPU  
# reduce the learning rate after 8 epochs (4000 iters) by a factor of 10

# The train/test net protocol buffer definition
net: "examples/cifar10/cifar10_quick_train_test.prototxt"
# test_iter specifies how many forward passes the test should carry out.
# In the case of MNIST, we have test batch size 100 and 100 test iterations,
# covering the full 10,000 testing images.
test_iter: 100
# Carry out testing every 500 training iterations.
test_interval: 500
# The base learning rate, momentum and the weight decay of the network.
base_lr: 0.001
momentum: 0.9
weight_decay: 0.004
# The learning rate policy
lr_policy: "fixed"
# Display every 100 iterations
display: 100
# The maximum number of iterations
max_iter: 4000
# snapshot intermediate results
snapshot: 4000
snapshot_format: HDF5
snapshot_prefix: "examples/cifar10/cifar10_quick"
# solver mode: CPU or GPU
solver_mode: CPU
——————————————————————————————————————————————————————————————————————————

cifar10_quick_train_test.prototxt文件【只贴前面一部分】,需要修改的就是数据格式为leveldb,以及相关路径,自行核对

  1. name: "CIFAR10_quick"  
  2. layer {  
  3.   name: "cifar"  
  4.   type: "Data"  
  5.   top: "data"  
  6.   top: "label"  
  7.   include {  
  8.     phase: TRAIN  
  9.   }  
  10.   transform_param {  
  11.     mean_file: "examples/cifar10/mean.binaryproto"  
  12.   }  
  13.   data_param {  
  14.     source: "examples/cifar10/cifar10_train_leveldb"  
  15.     batch_size: 100  
  16.     backend: LEVELDB  
  17.   }  
  18. }  
  19. layer {  
  20.   name: "cifar"  
  21.   type: "Data"  
  22.   top: "data"  
  23.   top: "label"  
  24.   include {  
  25.     phase: TEST  
  26.   }  
  27.   transform_param {  
  28.     mean_file: "examples/cifar10/mean.binaryproto"  
  29.   }  
  30.   data_param {  
  31.     source: "examples/cifar10/cifar10_test_leveldb"  
  32.     batch_size: 100  
  33.     backend: LEVELDB  
  34.   }  
  35. }  
name: "CIFAR10_quick"
layer {
  name: "cifar"
  type: "Data"
  top: "data"
  top: "label"
  include {
    phase: TRAIN
  }
  transform_param {
    mean_file: "examples/cifar10/mean.binaryproto"
  }
  data_param {
    source: "examples/cifar10/cifar10_train_leveldb"
    batch_size: 100
    backend: LEVELDB
  }
}
layer {
  name: "cifar"
  type: "Data"
  top: "data"
  top: "label"
  include {
    phase: TEST
  }
  transform_param {
    mean_file: "examples/cifar10/mean.binaryproto"
  }
  data_param {
    source: "examples/cifar10/cifar10_test_leveldb"
    batch_size: 100
    backend: LEVELDB
  }
}
一定要核对正确,我好像在设置添加路径的时候多了一个空格,结果出现了下面问题


【PS】一定要细心

最后,运行train.bat时候出现如下界面,说明正在训练


是不是感觉和网上看到的不一样呢?网上都是各种iteration 和loss显示在命令窗口,但是这里出现了prefetch batch等。原因在于我们用的是debug模式下生成的caffe在训练,如果想看到如下情形的结果,请将caffe.sln使用release模式生成(用VS2013打卡caffe.sln以后,上方中间部分的dubug改为release,然后右键工程,重新生成)


第六步

训练完成,会得到如下文件


下面是我训练好的cifar10的model,读者可下载,可自行训练

cifar10_quick_iter_4000.caffemodel.h5的链接:http://pan.baidu.com/s/1o8xSqr4 密码:ftc5

cifar10_quick_iter_4000.solverstate.h5的链接:链接:http://pan.baidu.com/s/1eRGPlNs 密码:589n

第七步

附带说一下caffe train 的finetuning。我们在编译成功caffe以后显示的dos窗口显示的有一行是:

  1. commands:  
  2. train  train or finetune a model  
commands:
train  train or finetune a model
只要是用caffe train -solver=xxxxxxx,那就是从头开始训练

凡是遇到caffe train -solver=xxxx  -weights=xxxxxx.caffemodel(.h5),那就是用已有模型参数(权重偏置)去初始化网络,称为finetune

### TensorFlow/Keras 实战:神经网络分类模型 以下是使用 TensorFlow 和 Keras 构建一个简单的二分类问题的全连接神经网络 (FCNN) 模型的代码示例[^1]: ```python import tensorflow as tf from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Dropout from sklearn.model_selection import train_test_split from sklearn.datasets import make_classification from sklearn.preprocessing import StandardScaler # 创建合成数据集 X, y = make_classification(n_samples=1000, n_features=20, n_informative=15, n_redundant=5, random_state=42) # 数据预处理 scaler = StandardScaler() X_scaled = scaler.fit_transform(X) # 划分训练集和测试集 X_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size=0.2, random_state=42) # 构建模型 model = Sequential([ Dense(64, activation='relu', input_shape=(X_train.shape[1],)), Dropout(0.5), Dense(32, activation='relu'), Dropout(0.5), Dense(1, activation='sigmoid') ]) # 编译模型 model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy']) # 训练模型 history = model.fit(X_train, y_train, epochs=20, batch_size=32, validation_data=(X_test, y_test)) # 测试模型性能 test_loss, test_accuracy = model.evaluate(X_test, y_test) print(f"Test Accuracy: {test_accuracy:.4f}") ``` 上述代码展示了如何利用 TensorFlow 和 Keras 来解决一个二分类问题。它包括了数据生成、标准化、模型定义、编译以及评估等多个环节。 --- ### PyTorch 实战:神经网络分类模型 下面是使用 PyTorch 构建相同任务的一个实现方法[^2]: ```python import torch import torch.nn as nn import torch.optim as optim from sklearn.model_selection import train_test_split from sklearn.datasets import make_classification from sklearn.preprocessing import StandardScaler # 创建合成数据集并转换为张量 X, y = make_classification(n_samples=1000, n_features=20, n_informative=15, n_redundant=5, random_state=42) scaler = StandardScaler() X_scaled = scaler.fit_transform(X) X_tensor = torch.tensor(X_scaled, dtype=torch.float32) y_tensor = torch.tensor(y.reshape(-1, 1), dtype=torch.float32) # 划分训练集和测试集 train_X, test_X, train_y, test_y = train_test_split(X_tensor, y_tensor, test_size=0.2, random_state=42) # 定义模型 class SimpleNet(nn.Module): def __init__(self): super(SimpleNet, self).__init__() self.fc1 = nn.Linear(20, 64) self.dropout1 = nn.Dropout(0.5) self.fc2 = nn.Linear(64, 32) self.dropout2 = nn.Dropout(0.5) self.output = nn.Linear(32, 1) def forward(self, x): x = torch.relu(self.fc1(x)) x = self.dropout1(x) x = torch.relu(self.fc2(x)) x = self.dropout2(x) return torch.sigmoid(self.output(x)) model = SimpleNet() # 定义损失函数和优化器 criterion = nn.BCELoss() # 适用于二分类问题 optimizer = optim.Adam(model.parameters(), lr=0.001) # 训练模型 for epoch in range(20): # 设置迭代次数 optimizer.zero_grad() outputs = model(train_X) loss = criterion(outputs, train_y) loss.backward() optimizer.step() print(f'Epoch [{epoch+1}/20], Loss: {loss.item():.4f}') # 测试模型性能 with torch.no_grad(): predictions = model(test_X).round() accuracy = (predictions == test_y).float().mean() print(f'Test Accuracy: {accuracy.item():.4f}') ``` 这段代码实现了与前面相同的二分类任务,但采用了 PyTorch 的方式来完成模型的设计和训练过程。 --- ### 使用 Keras 进行图像分类的任务实例 下面是一个基于 CIFAR-10 数据集的卷积神经网络 (CNN) 图像分类任务的代码示例[^3]: ```python import tensorflow as tf from tensorflow.keras import datasets, layers, models # 加载 CIFAR-10 数据集 (train_images, train_labels), (test_images, test_labels) = datasets.cifar10.load_data() # 归一化像素值到 [0, 1] 范围 train_images, test_images = train_images / 255.0, test_images / 255.0 # 构建 CNN 模型 model = models.Sequential([ layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)), layers.MaxPooling2D((2, 2)), layers.Conv2D(64, (3, 3), activation='relu'), layers.MaxPooling2D((2, 2)), layers.Conv2D(64, (3, 3), activation='relu'), layers.Flatten(), layers.Dense(64, activation='relu'), layers.Dense(10, activation='softmax') # 输出层有 10 类 ]) # 编译模型 model.compile(optimizer='adam', loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=['accuracy']) # 训练模型 history = model.fit(train_images, train_labels, epochs=10, validation_data=(test_images, test_labels)) # 测试模型性能 test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2) print(f"Test Accuracy: {test_acc:.4f}") ``` 该代码展示了一个典型的卷积神经网络用于图像分类的应用场景。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值