BayesWitnesses / m2cgen

Transform ML models into a native code (Java, C, Python, Go, JavaScript, Visual Basic, C#, R, PowerShell, PHP, Dart, Haskell, Ruby, F#, Rust) with zero dependencies
MIT License
2.8k stars 241 forks source link

How to use model for jpg photo? #582

Open Flashton91 opened 1 year ago

Flashton91 commented 1 year ago

Hello. I converted a model into pure python, which I trained to determine the presence or absence of an object.

import os
import pickle
import sys

from skimage.io import imread
from skimage.transform import resize
import numpy as np
from sklearn import svm
from sklearn.model_selection import train_test_split
from sklearn.model_selection import GridSearchCV
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score

import m2cgen as m2c
sys.setrecursionlimit(2147483647)

input_dir = '0000/clf-data'
categories = ['empty', 'not_empty']

data = []
labels = []
for category_idx, category in enumerate(categories):
    for file in os.listdir(os.path.join(input_dir, category)):
        img_path = os.path.join(input_dir, category, file)
        img = imread(img_path)
        img = resize(img, (15, 15))
        data.append(img.flatten())
        labels.append(category_idx)

data = np.asarray(data)
labels = np.asarray(labels)

clf = svm.SVC()

x_train, x_test, y_train, y_test = train_test_split(data, labels, test_size=0.2, shuffle=True, stratify=labels)

clf.fit(x_train, y_train)

y_prediction = clf.predict(x_test)

score = accuracy_score(y_prediction, y_test)

print('{}% of samples were correctly classified'.format(str(score * 100)))

#pickle.dump(best_estimator, open('./model.p', 'wb'))

code = m2c.export_to_python(clf)
print(code)
nameimgs = "model.py"
fs = open(nameimgs,"w")
fs.write(code)
fs.close()`

Please tell me how to make a prediction on a small JPG photo?

I did not find on the net examples of working with a JPG image. Thank you.