In the previous article , I touched on a simple machine learning program. Very small data like the previous article is not actually used. Machine learning basically has the advantage of having a lot of data, so it usually results in a very large amount of data. Of course, if you have a lot of data, it will take a lot of time to learn. You may be surprised if you don't know it, but it is natural to leave your PC for a week to study. There is no practicality in doing such a long learning every time a program is executed. Therefore, you can save time by saving the learning result as a model and executing it in the actual program using the model. This time, I would like to create a "save program" and a "prediction program using a model".
If you don't know what you're doing, see previous article .
python 3.8.5 scikit-learn 0.231
Some of the code used in the previous article is used.
save_model.py
import numpy as np
from sklearn import svm
import pickle
#Read csv file
npArray = np.loadtxt("data.csv", delimiter = ",", dtype = "float")
#Storage of explanatory variables
x = npArray[:, 0:4]
#Storage of objective variable
y = npArray[:, 4:5].ravel()
#Select SVM as the learning method
clf = svm.SVC()
#Learning
clf.fit(x,y)
#Saving the learning model
with open('model.pickle', mode='wb') as f:
pickle.dump(clf,f,protocol=2)
open_model.py
import pickle
#Model open
with open('model.pickle', mode='rb') as f:
clf = pickle.load(f)
#Evaluation data
weather = [[9,0,7.9,6.5]]
#Prediction using a model
ans = clf.predict(weather)
if ans == 0:
print("It's sunny")
if ans == 1:
print("It's cloudy")
if ans == 2:
print("It's rain")
$ python3 open_model.py
It's sunny
Thank you for your hard work. By saving the model trained in this way, it becomes possible to evaluate and predict the data without training each execution. Currently, AI, which is said in the world, is created and operated as a set of "program" + "learning data". Looking at the learning model created from the collected data, it is a pleasure different from creating a large-scale program. See you again.
Recommended Posts