用pycaffe训练人工神经网络步骤
from:http://blog.****.net/leo_is_ant/article/details/50506256
Caffe 是一个做CNN的工具。但是如果我只想搭建一套普通的神经网络,那么应该怎么做呢?这篇文章参考了一下两篇文章来一发CNN搭建神经网络的实验。
https://github.com/Franck-Dernoncourt/caffe_demos
第一步构建我们的feature,label。我们可以把feature,与label整理成sklearn类似的数据格式。具体格式如下(featureMat是一个list1[list2] list2 是特征向量label是list 表征每个label 当然转换成 numpy.array()好像也可以)总之下如图:
第二步我们需要转换成caffe需要的数据格式,一开始想转换成HDF5格式,后来train这一步出现错误,error提示信息为numberof labels must match number of predictions;查看代码发现之前demo是做多标签的。但是这里需求是一个但标签多类分类(loss为softmax而非cross-entropy)所以我将数据按照lmdb格式组织了起来。
第三步写solver和train_val的prototxt。与model里的prototxt一样,只不过这里没有卷积层,是一个全连接加上tanh的传统神经网络结构。网络结构图奉上:
第四步训练测试。至此完成了caffe普通神经网络的训练…..貌似把人家搞退化了。
最后相关代码奉上:
lmdb生成代码
- def load_data_into_lmdb(lmdb_name, features, labels=None):
- env = lmdb.open(lmdb_name, map_size=features.nbytes*2)
- features = features[:,:,None,None]
- for i in range(features.shape[0]):
- datum = caffe.proto.caffe_pb2.Datum()
- datum.channels = features.shape[1]
- datum.height = 1
- datum.width = 1
- if features.dtype == np.int:
- datum.data = features[i].tostring()
- elif features.dtype == np.float:
- datum.float_data.extend(features[i].flat)
- else:
- raise Exception("features.dtype unknown.")
- if labels is not None:
- datum.label = int(labels[i])
- str_id = '{:08}'.format(i)
- with env.begin(write=True) as txn:
- txn.put(str_id, datum.SerializeToString())
训练代码
- def train(solver_prototxt_filename):
- '''''
- Train the ANN
- '''
- caffe.set_mode_cpu()
- solver = caffe.get_solver(solver_prototxt_filename)
- solver.solve()
预测代码
- def get_predicted_output(deploy_prototxt_filename, caffemodel_filename, input, net = None):
- '''''
- Get the predicted output, i.e. perform a forward pass
- '''
- if net is None:
- net = caffe.Net(deploy_prototxt_filename,caffemodel_filename, caffe.TEST)
- out = net.forward(data=input)
- return out[net.outputs[0]]