I have a problem with load trained SVM from file. I use Python and OpenCv 3.1.0. I create svm object by:
svm = cv2.ml.SVM_create()
Next, I train svm and save to file by:
svm.save('data.xml')
Now i want to load this file in other Python script. In docs i can't find any methods to do it.
Is there a trick to load svm from file? Thanks for any responses.
I think it's a litte bit confusing that there is no svm.load(filepath) method as a counterpart of svm.save(filepath), but when I read the module help it makes sense to me that SVM_load is a child of cv2.ml (sibling of SVM_create).
Be sure that your opencv master branch is up-to-date (currently version 3.1.0-dev)
>>> import cv2
>>> cv2.__version__
'3.1.0-dev'
>>> help(cv2.ml)
returns
SVM_create(...)
SVM_create() -> retval
SVM_load(...)
SVM_load(filepath) -> retval
so you can simply use something like:
if not os.path.isfile('svm.dat'):
svm = cv2.ml.SVM_create()
...
svm.save('svm.dat')
else:
svm = cv2.ml.SVM_load('svm.dat')
Related
I have this model: https://github.com/williamyang1991/DualStyleGAN and try to convert it to CoreML. So far I create copy of original Colab notebook and append at the end two blocks:
!pip install coremltools
import coremltools as ct
and
##title Convert inverted image.
inverted_latent = torch.Tensor(result_latents[0][4]).cuda().unsqueeze(0).unsqueeze(1)
with torch.no_grad():
net.eval()
[sampled_src, sampled_dst] = net(inverted_latent, input_is_latent=True)[0]
traced_model = torch.jit.trace(net, inverted_latent)
mlmodel = ct.convert(traced_model, inputs=[ct.ImageType(name="input", shape=inverted_latent.shape,bias=[-1,-1,-1],scale=2.0/255.0)])
mlmodel.save("modelsaved.mlmodel")
To run it, you should put any image with face to /content and in /usr/local/lib/python3.7/dist-packages/torchvision/transforms/functional.py
replace round method at 545, 546 lines with np.round
But then it fails at
mlmodel = ct.convert(...
with:
RuntimeError: PyTorch convert function for op 'pythonop' not implemented.
I suggest that there the way to rewrite this module with methods that could be convert, am I right? But I can't to figure out how to find the source of this module.
So my question is:
If I think in a right way, how I can find the source of module?
And if I wrong, please advise me the right way to do it.
The code starts by loading the model into PyTorch.
The code then converts the model into CoreML format and saves it to a .mlmodel file.The code below will take the existing PyTorch model and convert it into a CoreML model with input and output features.
The outputs are saved in the file example.mlmodel which can be opened in Xcode or any other development environment that supports CoreML models.
import torch
import coremltools
model = torch.load('MyPyTorchModel.pt')
coreml_model = coremltools.converters.pytorch.from_pytorch(model,
input_features=
['input'],
output_features=
['output'])
coreml_model.save('MyCoreMLModel.mlmodel')
cv2.error: OpenCV(4.2.0) C:\projects\opencv-python\opencv\modules\dnn\src\darknet\darknet_io.cpp:677: error: (-212:Parsing error) Unknown layer type: in function 'cv::dnn::darknet::ReadDarknetFromCfgStream
Code:
import cv2
import numpy as np
# Load Yolo
path =r"D:\yolov3-coco"
weight = path+r"\yolov3.weights"
cfg = path+r"\yolov3.cfg"
net = cv2.dnn.readNetFromDarknet(weight ,cfg )
classes = []
with open(path+"\coco.txt", "r") as f:
classes = [line.strip() for line in f.readlines()]
print(cfg)
print(weight)
print(classes)
cv2.destroyAllWindows()
I have already used the command net= cv2.dnn.readNet(weights,cfg) but it did not work i have also gone to https://pjreddie.com/media/files/yolov3.weights and downloaded the weights and config files and have put them in a folder called yolov3-coco.
You seem to be passing *.weights first and *.cfg later. If takes *.cfg first, then the darknet weights file. Reference for readNetFromDarknet,
https://docs.opencv.org/master/d6/d0f/group__dnn.html#gafde362956af949cce087f3f25c6aff0d
This problem is similar to,
YOLO V3 Video Stream Object Detection
Maybe yolo3-coco cfg and weight do not match so Unknown layer type error.
Path for yolov3.weights,yolov3.cfg is not proper so you can pass path directly where they are stored
net = cv.dnn.readNetFromDarknet("yolov3-coco/yolov3.cfg", "yolov3-coco/yolov3.weights")
For me it were the wrong files. I was trying it in google colab with version 2.5.0 of tensorflow. The following files worked:
!wget "https://pjreddie.com/media/files/yolov3.weights"
!wget "https://raw.githubusercontent.com/pjreddie/darknet/master/cfg/yolov3.cfg"
!wget "https://raw.githubusercontent.com/pjreddie/darknet/master/data/coco.names"
try to use OpenCV --version 5. My error was solved with this.
ı had trouble problem like this. Just check your code path and make sure where cfg,weights are,open main folder and work under the main folder.
I'm trying to learn how to use pydicom for reading and processing dicom images. I'm using Python 3.
import dicom
import numpy
ds = pydicom.read_file(lstFilesDCM[0])
print(ds.pixel_array)`
I get an error NameError: name 'pydicom' is not defined. If I change
ds = pydicom.read_file(lstFilesDCM[0])
to
ds = dicom.read_file(lstFilesDCM[0])
(using dicom.read_file instead), I get the following error:
NotImplementedError: Pixel Data is compressed in a format
pydicom does not yet handle. Cannot return array
I also verified that pydicom is properly installed and updated.
How do i fix this?
You are trying to call a class that you have not imported before:
Use:
import pydicom
import numpy
ds = pydicom.read_file(lstFilesDCM[0])
print(ds.pixel_array)
or
import dicom
ds = dicom.read_file("the_name_of_file.dcm")
Documentation: http://pydicom.readthedocs.io/en/stable/pydicom_user_guide.html
If you want to get your hands on the pixel data, I suggest to use the convert program from the ImageMagick suite. You can either call this program from Python using the subprocess module. (See this example, where I convert them to JPEG format), or you can use one of the Python bindings.
If you want to manipulate the images, using the bindings might be preferable. But note that not all the bindings have been converted to ImageMagick version 7.
Please forgive my newbness here, but fasttext is not working for me on python. I am using anaconda running python 3.6. My code is as follows(just an example):
import fasttext
model = fasttext.load_model('/home/sproc/share/fastText/model.bin')
print(model.words)
This returns the following error:
Traceback (most recent call last):
File "/media/sf_VBoxShare/LiClipseWorkspace/test/testpack/fasttext.py", line 1, in <module>
import fasttext
File "/media/sf_VBoxShare/LiClipseWorkspace/test/testpack/fasttext.py", line 3, in <module>
model = fasttext.load_model('/home/sproc/share/fastText/model.bin')
AttributeError: module 'fasttext' has no attribute 'load_model'
Does the same thing with cbow and skipgram when trying to create word vectors. I check the init.py file from the .../site-packages/fasttext directory and it imports said attributes, but they are not part of the model.py module. I'm guessing this has something to do with the shared object file but I am not sure. Any help is greatly appreciated.
Here is a solution that worked for me when I got the error you are getting;
Import FastText
from gensim.models.wrappers import FastText
Load the binary
model=FastText.load_fasttext_format('wiki.simple.bin')
Rename your python file .
Don't name it as fasttext.py .If your name it like this , what you import by "import fasttext.py " will be your own file.
You can rename it as 'fast_text.py' or something else .
If you install fastText package instead of the old fasttext, then
import fastText
model = fastText.load_model('/home/sproc/share/fastText/model.bin')
should work as expected.
#spencerktm30 I recommend you using pyfasttext instead of fasttext which is no longer active and it has a lot of bugs. link to pyfasttext
Actually, I faced similar issue when trying to load a C++ pre trained model and I had to switch to using pyfasttext to get it to work.
So this should hopefully work for you:
>>> from pyfasttext import FastText
>>> model = FastText('/home/sproc/share/fastText/model.bin')
Rename the file from fasttext.py to another name, it will work.
Apparently there are different fasttext python libraries out there!
fasttext != fasttext-win
In python scikit learn, there is a method called export_graphviz to export a decision tree to dot file.
I want to ask if there is a method to import a dot file to scikit learn as a decision tree? like some function called sklearn.tree.import_graphviz() ?
AFAIK There is no easy way to do that. Graphviz can only be used to visualise the decision tree. If you wish to save the model you can use Pickle to save the model. For example:
import cPickle
# save the classifier
with open('my_dumped_classifier.pkl', 'wb') as fid:
cPickle.dump(gnb, fid)
# load it again
with open('my_dumped_classifier.pkl', 'rb') as fid:
gnb_loaded = cPickle.load(fid)