# 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.