Caffe's model and prototxt are converted to pytorch's model.

Source: Internet
Author: User
Tags pytorch
# Because caffe and pytorch are not installed in the system at the same time, a conda in the system should be an isolated Python environment, which is generally unavailable.
# Therefore, numpy can only be used as an intermediate medium. The following code is the Caffe network stored in numpy and converts it to pytorch.
# I didn't automate the conversion of the prototxt. It's not necessary. I wrote the same pytorch network myself.
Def net_from_caffe (n, RE): # N is the pytorch model, and RE is the caffemodel I =-1 for name, L1 in N. named_children (): Try: L2 = getattr (n, name) l2.weight # Skip Relu/dropout failed t exception: continue I + = 1 while Len (Re [I] ['weight']) = 0 and I <Len (re ): # In numpy, The Conv and fully connected layer do not have weights. Only the two layers are aligned and I + = 1 W = torch. from_numpy (Re [I] ['weight'] [0]) # B = torch. from_numpy (Re [I] ['weight'] [1]) assert W. size () = l2.weight. size () assert B. size () = l2.bias. size () l2.weight. data. copy _ (w) l2.bias. data. copy _ (B)

Pitfalls:

1. When you open an image, Pil defaults to RGB and ranges from 0 to 1. We need to create a multiplication by ourselves from 0.

2. note that pytorch performs an expansion operation when con is connected to the full link for the first time, directly H = H. view (H. size (0),-1) can correspond to Caffe one by one

3. Convert RGB to BGR: Im = Im [[2, 0, 1],...]

 

 

Two Methods of torch. Load:

1. Store the model directly.

However, the data type of this model is fixed. You must make this data type visible only when it is called.

2. Store state_dict

It is more flexible, and the parameter value is assigned directly. There is no data type for the outside package, which means a little more trouble.

Caffe's model and prototxt are converted to pytorch's model.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.