Matlab doesn't import standard python modules, when importing a custom python module
1 view (last 30 days)
Show older comments
I'm importing a python module by using py.importlib.import_modulndule). Now at the top of my my_module.py I'm importing a few python modules necessary for my functions. Despite having changed my default python version within Matlab to the correct virtual environment, Matlab fails to import the modules. Here is my python script
__future__ import print_function, division
import os
import sys
import time
import argparse
import numpy as np
import torch
import torchvision
import random
import itertools
import torchvision.models as models
import matplotlib
matplotlib.use('agg')
from matplotlib.pyplot import imread
from torchvision import datasets, transforms
def get_patch(img, x_center, y_centre, legth):
#Load image
image=imread(img)
return image[x_center:x_center+legth,y_centre:y_centre+legth,:]
model_path='./PytorchModel/checkpoint_epoch_60.pt'
model=Encoder('resnet18',False)
model.load_state_dict(torch.load(model_path,map_location='cpu'))
Transform = transforms.Compose([transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])])
image1=get_patch(im1, center1[0], center1[1], 100)
image1=Transform(image1)
image2=get_patch(im2, center2[0], center2[1], 100)
image2=Transform(image2)
data=torch.stack((image1,image2),dim=0)
model.eval()
with torch.no_grad():
vectors=model(data)
y_coord= vectors[:,1] #Extract y coordinates
x_coord = vectors[:,0] #Extract x coordinates
angles=np.degrees(torch.atan2(y_coord,x_coord).numpy())
relative_angle=convert_to_convetion(angles[1]-angles[0])
return relative_angle
def convert_to_convetion(input):
"""
Coverts all anlges to convecntion used by atan2
"""
input[input<180]=input[input<180]+360
input[input>180]=input[input>180]-360
return input
class Encoder(nn.Module):
"""
Encoder to 2-dimnesional space
"""
def __init__(self,model_type,pretrained):
super(Encoder, self).__init__()
if model_type=='resnet18':
pretrained=models.resnet18(pretrained=pretrained)
elif model_type=='resnet34':
pretrained=models.resnet34(pretrained=pretrained)
elif model_type=='resnet50':
pretrained=models.resnet50(pretrained=pretrained)
#Replace maxpool layer with convolutional layers
pretrained.maxpool=nn.Conv2d(64, 64, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False)
#Replace AvgPool2d witth AdaptiveAvgPool2d
pretrained.avgpool=nn.AdaptiveAvgPool2d(1)
#Remove the last fc layer anx call in encoder
self.encoder= nn.Sequential(*list(pretrained.children())[:-1],
nn.ReLU(),
nn.Conv2d(512,256,1),
nn.ReLU(),
nn.Conv2d(256,2,1))
def forward(self,x):
return self.encoder(x)
And here is the error I get:
Error using _init_><module> (line 80) Python Error: RuntimeError: stoi: no conversion
Error in alexnet><module> (line 1) import torch.nn as nn
Error in _init_><module> (line 1) from .alexnet import *
Error in _init_><module> (line 1) from torchvision import models
Error in my_module><module> (line 10) import torchvision
Error in <frozen importlib>exec_module (line 678)
Error in _init_>import_module (line 126) return _bootstrap._gcd_import(name[level:], package, level)
1 Comment
Sachin Meena
on 10 Sep 2018
Edited: Sachin Meena
on 10 Sep 2018
Which system are you using? I am working on Windows 10, MATLAB R2018a, Python 3.7 64 bit. I had to make a few changes to your imports, but I am able to import this module in MATLAB. I had to change the following 2 import statements.
from __future__ import print_fucntion, division
import torch.nn as nn
Answers (1)
Sean de Wolski
on 10 Sep 2018
Please also note that the ability to use resnet and train/transfer deep networks is available in MATLAB in the Neural Network/Deep Learning Toolbox.
This could save you from having to interact with any of the python pieces.
0 Comments
See Also
Categories
Find more on Call Python from MATLAB in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!