Directorio de artículos
Prefacio
Cifar-10 es un conjunto de datos recopilados por los dos grandes discípulos de Hinton, Alex Krizhevsky e Ilya Sutskever, para el reconocimiento de objetos ordinarios. Los dos núcleos de DL: datos + modelo.
CIFAR-10 (DataSet) Este conjunto de datos contiene un total de: 60000 imágenes
1 — Tamaño de la imagen: 32 píxeles * 32 píxeles
2 — Profundidad de imagen: imagen en color RGB de tres canales
2: estas 60.000 imágenes se dividen en 10 categorías y las clasificaciones específicas se muestran en la siguiente figura:
Hay: 1 a
50 000 muestras de formación en las 60000 imágenes 2 a 10
000 muestras de prueba (conjunto de verificación)
Observaciones:
1 — CIFAR-10: Es un conjunto de datos para [Objeto ordinario] Reconocimiento
2 — Por lo tanto, la característica más importante de este conjunto de datos y modelo de red es que puede migrar fácilmente [Reconocimiento de objetos] a otros objetos ordinarios
3— Además, el problema de la clasificación de 10 se puede extender a la clasificación de 100 categorías de objetos, e incluso a la clasificación de objetos de 1000 categorías y más.
Una cosa a tener en cuenta es:
El conjunto de datos del ejemplo tiene una L
1-10000 matriz numpy de 3072 ------ matriz de píxeles de 10000 imágenes de cada imagen
2: la unidad es uint8s
3-3072 almacena una imagen de 32 32 colores (3 32 32 == 3 1024 == 3072)
4: los primeros 1024 bits de numpy son el valor de píxel del componente R en RGB, los 1024 bits del medio son el valor de píxel del componente G y los últimos 1024 son el valor de píxel del componente B
5 — El último punto a tener en cuenta es: El
ejemplo CIFAR-10 solo se puede usar para la clasificación de [imágenes pequeñas], al igual que el ejemplo Mnist mencionado anteriormente, se usa principalmente para el reconocimiento de números escritos a mano.
Descargar datos
Primero, hay un archivo de script en el directorio data / cifar10: get_cifar10.sh, el código fuente es el siguiente
#!/usr/bin/env sh
# This scripts downloads the CIFAR10 (binary version) data and unzips it.
DIR="$( cd "$(dirname "$0")" ; pwd -P )"
cd "$DIR"
echo "Downloading..."
wget --no-check-certificate http://www.cs.toronto.edu/~kriz/cifar-10-binary.tar.gz
echo "Unzipping..."
tar -xf cifar-10-binary.tar.gz && rm -f cifar-10-binary.tar.gz
mv cifar-10-batches-bin/* . && rm -rf cifar-10-batches-bin
# Creation is split out because leveldb sometimes causes segfault
# and needs to be re-created.
echo "Done."
Donde -no-check-certificate es utilizar la opción "No verificar certificado".
La descarga se completa de la siguiente manera:
procesamiento de datos
Hay un script create_cifar10.sh en el directorio raíz de Caffe examples / cifar10 /, que es un script para la conversión de datos:
#!/usr/bin/env sh
# This script converts the cifar data into leveldb format.
set -e
EXAMPLE=examples/cifar10
DATA=data/cifar10
DBTYPE=lmdb
echo "Creating $DBTYPE..."
rm -rf $EXAMPLE/cifar10_train_$DBTYPE $EXAMPLE/cifar10_test_$DBTYPE
./build/examples/cifar10/convert_cifar_data.bin $DATA $EXAMPLE $DBTYPE
echo "Computing image mean..."
./build/tools/compute_image_mean -backend=$DBTYPE \
$EXAMPLE/cifar10_train_$DBTYPE $EXAMPLE/mean.binaryproto
echo "Done."
En el script anterior, use el programa ejecutable convert_cifar_data.bin para convertir los datos en formato LMDB, y use el programa compute_image_mean para generar el archivo mean.
/examples/cifar10/create_cifar10.sh
Entrenar
Hay archivos rápidos en el archivo cifar10, y también hay un montón de archivos completos. La principal diferencia es que rápido solo entrena 5000, y completo es todo entrenado, 50000.
Como estoy entrenando en una máquina virtual, es muy lento, aquí estoy haciendo un entrenamiento rápido.
Si usa Gpu, también puede realizar un entrenamiento completo.
vim train_quick.sh
#!/usr/bin/env sh
set -e
TOOLS=./build/tools
$TOOLS/caffe train \
--solver=examples/cifar10/cifar10_quick_solver.prototxt $@
# reduce learning rate by factor of 10 after 8 epochs
$TOOLS/caffe train \
--solver=examples/cifar10/cifar10_quick_solver_lr1.prototxt \
--snapshot=examples/cifar10/cifar10_quick_iter_4000.solverstate $@
Continúe viendo el archivo cifar10_quick_solver.prototxt en el script,
# 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 #4000样本以下学习率是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_prefix: "examples/cifar10/cifar10_quick"
# solver mode: CPU or GPU
solver_mode: CPU
Continúe viendo el archivo cifar10_quick_solver_lr1.prototxt en el script,
# 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.0001 #4000-5000样本学习率是0.0001,降成原来的十分之一了
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: 5000
# snapshot intermediate results
snapshot: 5000
snapshot_format: HDF5
snapshot_prefix: "examples/cifar10/cifar10_quick"
# solver mode: CPU or GPU
solver_mode: CPU
Continúe para ver el archivo cifar10_quick_train_test.prototxt
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_lmdb"
batch_size: 100
backend: LMDB
}
}
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_lmdb"
batch_size: 100
backend: LMDB
}
}
layer {
name: "conv1"
type: "Convolution"
bottom: "data"
top: "conv1"
param {
lr_mult: 1
}
param {
lr_mult: 2
}
convolution_param {
num_output: 32
pad: 2
kernel_size: 5
stride: 1
weight_filler {
type: "gaussian"
std: 0.0001
}
bias_filler {
type: "constant"
}
}
}
layer {
name: "pool1"
type: "Pooling"
bottom: "conv1"
top: "pool1"
pooling_param {
pool: MAX
kernel_size: 3
stride: 2
}
}
layer {
name: "relu1"
type: "ReLU"
bottom: "pool1"
top: "pool1"
}
layer {
name: "conv2"
type: "Convolution"
bottom: "pool1"
top: "conv2"
param {
lr_mult: 1
}
param {
lr_mult: 2
}
convolution_param {
num_output: 32
pad: 2
kernel_size: 5
stride: 1
weight_filler {
type: "gaussian"
std: 0.01
}
bias_filler {
type: "constant"
}
}
}
layer {
name: "relu2"
type: "ReLU"
bottom: "conv2"
top: "conv2"
}
layer {
name: "pool2"
type: "Pooling"
bottom: "conv2"
top: "pool2"
pooling_param {
pool: AVE
kernel_size: 3
stride: 2
}
}
layer {
name: "conv3"
type: "Convolution"
bottom: "pool2"
top: "conv3"
param {
lr_mult: 1
}
param {
lr_mult: 2
}
convolution_param {
num_output: 64
pad: 2
kernel_size: 5
stride: 1
weight_filler {
type: "gaussian"
std: 0.01
}
bias_filler {
type: "constant"
}
}
}
layer {
name: "relu3"
type: "ReLU"
bottom: "conv3"
top: "conv3"
}
layer {
name: "pool3"
type: "Pooling"
bottom: "conv3"
top: "pool3"
pooling_param {
pool: AVE
kernel_size: 3
stride: 2
}
}
layer {
name: "ip1"
type: "InnerProduct"
bottom: "pool3"
top: "ip1"
param {
lr_mult: 1
}
param {
lr_mult: 2
}
inner_product_param {
num_output: 64
weight_filler {
type: "gaussian"
std: 0.1
}
bias_filler {
type: "constant"
}
}
}
layer {
name: "ip2"
type: "InnerProduct"
bottom: "ip1"
top: "ip2"
param {
lr_mult: 1
}
param {
lr_mult: 2
}
inner_product_param {
num_output: 10
weight_filler {
type: "gaussian"
std: 0.1
}
bias_filler {
type: "constant"
}
}
}
layer {
name: "accuracy"
type: "Accuracy"
bottom: "ip2"
bottom: "label"
top: "accuracy"
include {
phase: TEST
}
}
layer {
name: "loss"
type: "SoftmaxWithLoss"
bottom: "ip2"
bottom: "label"
top: "loss"
}
Para conocer el significado de los archivos de red anteriores, consulte el artículo anterior: Portal .
Para analizar más a fondo la estructura de la red, dibuje un diagrama de red, que es más conveniente para el análisis.
python ./python/draw_net.py ./examples/cifar10/cifar10_quick_train_test.prototxt ./examples/cifar10/cifar10_quick.png --rankdir=LR
eog /examples/cifar10/cifar10_quick.png
De la siguiente manera:
comience a entrenar, el entrenamiento con cpu es demasiado lento. . . . . . .
./train_quick.sh
De los resultados del entrenamiento, precisión = 0,7595 y pérdida = 0,72916 después de entrenar 5000 veces.
Prueba o razonamiento
La prueba se puede clasificar usando el programa Classify.bin que viene con caffe, o puede usar el programa Python de Ppython / classify.py para probar y
preparar imágenes de prueba. Hay imágenes como cat.jpg en CAFFE_ROOT / examples / images, o puede agregar otras usted mismo categoría.
(1) Utilice el programa Classification.bin para la prueba de clasificación
Usage: ./build/examples/cpp_classification/classification.bin deploy.prototxt network.caffemodel mean.binaryproto labels.txt img.jpg
./build/examples/cpp_classification/classification.bin \
examples/cifar10/cifar10_quick.prototxt \
examples/cifar10/cifar10_quick_iter_5000.caffemodel.h5 \
examples/cifar10/mean.binaryproto \
data/cifar10/batches.meta.txt \
examples/images/cat.jpg
Error de ejecución: la etiqueta de salida es 11, lo cual es inconsistente con la salida 10 de la red.
Modifique el archivo batches.meta.txt y elimine el espacio en la última línea de batches.meta.txt. Vuelva a ejecutar bien. El
resultado de la prueba resultó ser la probabilidad más alta de ciervos, y la probabilidad de gatito es 0.0261. ¡Esta tasa de precisión es demasiado baja, sudor! ! ! !
(2) Use el programa python de python / classify.py para probar
Ver el código fuente del archivo classify.py
#!/usr/bin/env python
"""
classify.py is an out-of-the-box image classifer callable from the command line.
By default it configures and runs the Caffe reference ImageNet model.
"""
import numpy as np
import os
import sys
import argparse
#argparse是python标准库里面用来处理命令行参数的库
#使用步骤:
#(1)import argparse 首先导入模块
#(2)parser = argparse.ArgumentParser() 创建一个解析对象
#(3)parser.add_argument() 向该对象中添加你要关注的命令行参数和选项
#(4)parser.parse_args() 进行解析
import glob
import time
import caffe
def main(argv):
pycaffe_dir = os.path.dirname(__file__)
parser = argparse.ArgumentParser()
# Required arguments: input and output files.
parser.add_argument(
"input_file",
help="Input image, directory, or npy."
)
parser.add_argument(
"output_file",
help="Output npy filename."
)
# Optional arguments.
parser.add_argument(
"--model_def",
default=os.path.join(pycaffe_dir,
"../models/bvlc_reference_caffenet/deploy.prototxt"),
help="Model definition file."
)
parser.add_argument(
"--pretrained_model",
default=os.path.join(pycaffe_dir,
"../models/bvlc_reference_caffenet/bvlc_reference_caffenet.caffemodel"),
help="Trained model weights file."
)
parser.add_argument(
"--gpu",
action='store_true',
help="Switch for gpu computation."
)
parser.add_argument(
"--center_only",
action='store_true',
help="Switch for prediction from center crop alone instead of " +
"averaging predictions across crops (default)."
)
parser.add_argument(
"--images_dim",
default='256,256',
help="Canonical 'height,width' dimensions of input images."
)
parser.add_argument(
"--mean_file",
default=os.path.join(pycaffe_dir,
'caffe/imagenet/ilsvrc_2012_mean.npy'),
help="Data set image mean of [Channels x Height x Width] dimensions " +
"(numpy array). Set to '' for no mean subtraction."
)
parser.add_argument(
"--input_scale",
type=float,
help="Multiply input features by this scale to finish preprocessing."
)
parser.add_argument(
"--raw_scale",
type=float,
default=255.0,
help="Multiply raw input by this scale before preprocessing."
)
parser.add_argument(
"--channel_swap",
default='2,1,0',
help="Order to permute input channels. The default converts " +
"RGB -> BGR since BGR is the Caffe default by way of OpenCV."
)
parser.add_argument(
"--ext",
default='jpg',
help="Image file extension to take as input when a directory " +
"is given as the input file."
)
args = parser.parse_args()
image_dims = [int(s) for s in args.images_dim.split(',')]
mean, channel_swap = None, None
if args.mean_file:
mean = np.load(args.mean_file)
if args.channel_swap:
channel_swap = [int(s) for s in args.channel_swap.split(',')]
if args.gpu:
caffe.set_mode_gpu()
print("GPU mode")
else:
caffe.set_mode_cpu()
print("CPU mode")
# Make classifier.
classifier = caffe.Classifier(args.model_def, args.pretrained_model,
image_dims=image_dims, mean=mean,
input_scale=args.input_scale, raw_scale=args.raw_scale,
channel_swap=channel_swap)
# Load numpy array (.npy), directory glob (*.jpg), or image file.
args.input_file = os.path.expanduser(args.input_file)
if args.input_file.endswith('npy'):
print("Loading file: %s" % args.input_file)
inputs = np.load(args.input_file)
elif os.path.isdir(args.input_file):
print("Loading folder: %s" % args.input_file)
inputs =[caffe.io.load_image(im_f)
for im_f in glob.glob(args.input_file + '/*.' + args.ext)]
else:
print("Loading file: %s" % args.input_file)
inputs = [caffe.io.load_image(args.input_file)]
print("Classifying %d inputs." % len(inputs))
# Classify.
start = time.time()
predictions = classifier.predict(inputs, not args.center_only)
print("Done in %.2f s." % (time.time() - start))
# Save
print("Saving results into %s" % args.output_file)
np.save(args.output_file, predictions)
if __name__ == '__main__':
main(sys.argv)
Es necesario modificar el cálculo de la media, este cálculo de la media es incorrecto.
Encontrado en el archivo classify.py
mean = np.load(args.mean_file)
Agrega una línea a continuación:
mean=mean.mean(1).mean(1)
Agregue print para imprimir los resultados de la prueba, agregue en python / classify.py:
print("Predictions:%s" % predictions)
Ejecutar prueba
python python/classify.py \
--model_def examples/cifar10/cifar10_quick.prototxt \
--pretrained_model examples/cifar10/cifar10_quick_iter_5000.caffemodel.h5 \
examples/images/cat.jpg save.file
La cuarta categoría prevista tiene la probabilidad más alta, 0,243992. Verifique el archivo data / cifar10 / batches.meta.txt. La cuarta categoría es cat. De los
resultados anteriores, la precisión de los resultados de predicción del conjunto de datos cifar10 es muy baja. Esto es solo para pruebas experimentales.