import numpy as np
import os
import matplotlib.pyplot as plt
import lmdb
from PIL import Image
import random
import sys
# import caffe module
caffe_root = '/home/henglan/Desktop/caffe-hybridnet/'
sys.path.insert(0, caffe_root + 'python')
import caffe
# read file
train_file = open('train.txt')
inputs_data_train = train_file.readlines()
train_file.close()
print("Creating Training Data LMDB File ..... ")
in_db = lmdb.open('Train_Data_lmdb',map_size=int(1e12))
with in_db.begin(write=True) as in_txn:
for in_idx, in_ in enumerate(inputs_data_train):
# print in_idx
in_ = in_.strip()
im = np.array(Image.open(in_))
Dtype = im.dtype
if len(im.shape) == 2:
print('here')
(row, col) = im.shape
im3 = np.zeros([row, col, 3], Dtype)
for i in range(3):
im3 [:, :, i] = im
im = im3
print('here')
im = im[:,:,::-1]
im = Image.fromarray(im)
im = np.array(im,Dtype)
im = im.transpose((2,0,1))
im_dat = caffe.io.array_to_datum(im)
in_txn.put('{:0>10d}'.format(in_idx),im_dat.SerializeToString())
in_db.close()
# read file
label_file = open('label.txt')
inputs_data_label = label_file.readlines()
label_file.close()
print("Creating Training Label LMDB File ..... ")
in_db1 = lmdb.open('Label_Data_lmdb',map_size=int(1e12))
with in_db1.begin(write=True) as in_txn:
for in_idx, in_ in enumerate(inputs_data_label):
in_ = in_.strip()
Dtype = 'uint8'
L = np.array(Image.open(in_), Dtype)
Limg = Image.fromarray(L)
L = np.array(Limg,Dtype)
L = L.reshape(L.shape[0],L.shape[1],1)
L = L.transpose((2,0,1))
L_dat = caffe.io.array_to_datum(L)
in_txn.put('{:0>10d}'.format(in_idx),L_dat.SerializeToString())
in_db1.close()
print("Finish creating lmdb file ......")
Ubuntu 14.04 64位机上用Caffe+MNIST训练Lenet网络 *** 作步骤1.将终端定位到Caffe根目录;2.下载MNIST数据谈兆虚库并解压缩:$ ./data/mnist/get_mnist.sh
3.将其转换成Lmdb数据库格式:$ ./examples/mnist/create_mnist.sh
执行完此shell脚本后,会在./examples/mnist下增加两个新目录,mnist_test_lmdb和mnist_train_lmdb
4.train model:含燃$ ./examples/mnist/train_lenet.sh
(1)、使用LeNet网络(《Gradient-BasedLearning Applied to Document Recognition》);
(2)、使用./examples/mnist/lenet_train_test.prototxtmodel;
(3)、使用./examples/mnist/lenet_solver.prototxtmodel;
(4)、执行train_lenet.sh脚本,会调用./build/tools目录下的caffe执行文件,此猜孝执行文件的实现是./tools目录下的caffe.cpp文件;
(5)、执行此脚本后,会生成几个文件,其中./examples/mnist/lenet_iter_10000.caffemodel则是最终训练生成的model文件;
(6)、以上默认的是在GPU模式下运行,如果想让其在CPU模式下运行,只需将lenet_solver.prototxt文件中的solver_mode字段值由原来的GPU改为CPU即可。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)