python -caffe1-Netspec 使得用户可以定义python脚本用以定义网络结构

netspe可以通過輸入直接創建網絡結構,其中包含了全連接層,數據層,標籤層,激活層,softmax交叉商损失层面,可以简化网络模型的构造方式。

#!/usr/bin/env python
# coding: utf-8
#copyRight by heibanke 
#如需转载请注明出处
#<<用Python做深度学习2-caffe>>
#http://study.163.com/course/courseMain.htm?courseId=1003491001


import caffe
from caffe import layers as L

def net():
    #  Netspec  使得用户可以定义python脚本用以定义网络结构
    # net实例化  dictionary与net 结构类似,python中dictionary其中包含多个鍵值對
    n = caffe.NetSpec()
    #net中創建不同的層
    # data layer創建
    n.data=L.layers(dummy_data_param=dict(num=10, channels=1, height=28, width=28, data_filler=dict(type='gaussian')))
    #label layer創建
    n.label=L.DummyData(dummy_data_param=dict(num=10, channels=1, height=1, width=1, data_filler=dict(type='gaussian')))
    # 創建ip1 並將data作爲輸入 InnerProduct全連接層
    n.ip1 = L.InnerProduct(n.data, num_output=50, weight_filler=dict(type='xavier'))
    #創建relu1並將ip1作爲輸入,ReLU爲激活層
    n.relu1 = L.ReLU(n.ip1, in_place=True)
    #創建ip2並將ip2作爲輸入
    n.ip2 = L.InnerProduct(n.relu1, num_output=4, weight_filler=dict(type='xavier'))
    # 創建loss ,ip2作爲輸入,    SoftmaxWithLoss Softmax函数和交叉熵误差
    n.loss = L.SoftmaxWithLoss(n.ip2, n.label)

    return n.to_proto()



with open('dm_py.prototxt', 'w') as f:
    f.write(str(net()))


#载入solver文件
solver = caffe.SGDSolver('dm_solver.prototxt')

#solver.net.forward()caff
#solver.step(1)
#solver.solve()

print solver.net.blobs['data'].data.shape
print solver.net.blobs['label'].data.shape

 

posted @ 2022-04-21 11:57  ID是菜鸟  阅读(24)  评论(0编辑  收藏  举报