Search code examples
pythonpython-3.xpyc

Precompile Python Script and Include it in another Python Program


I have been conducting a learning algorithm using Decision Tree Classifier in Python.

from sklearn.tree import DecisionTreeClassifier
clf = DecisionTreeClassifier()
clf.fit(train, train_label)
predicted_label = clf.predict(test)

The Decision Tree Classifier accepts training labels from a large text file. I want to run the program without performing again the training process. How will I do it in Python? How will I include a precompiled learning model and used it for testing in another program? Is precompiled python files does have anything to do with it?


Solution

  • After training your model, you could save your model for future use for avoiding the process of training.

    import pickle
    model.fit(X,y)
    saved_model = pickle.dump(model,open('saved_model.sav', 'wb'))#save your model
    .
    .
    .
    
    model = pickle.loads(open('saved_model.sav', 'rb'))#get your model from saved model file
    model.predict(X[0:1])#use without training