#!/usr/bin/env python # coding: utf-8 # # **학습데이터 Restful API 서버 만들기** # 1. https://honeyteacs.tistory.com/6 # 1. https://scikit-learn.org/stable/modules/model_persistence.html # 1. https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html?highlight=randomforestclassifier#sklearn.ensemble.RandomForestClassifier # In[41]: from sklearn.ensemble import RandomForestClassifier from sklearn.datasets import make_classification X, y = make_classification(n_samples=1000, n_features=4, n_informative=2, n_redundant=0, random_state=0, shuffle=False) clf = RandomForestClassifier(max_depth=2, random_state=0) clf.fit(X, y) print(clf.feature_importances_) print(clf.predict([[0, 0, 0, 0]])) # In[45]: # Save Model import pickle with open('data/train.pk', 'wb') as f: pickle.dump(clf, f) # In[53]: # Load Model clf = pickle.load(open("data/train.pk", "rb")) print(clf.predict([[0,0,1,1]])) # In[ ]: import pickle s = pickle.dumps(clf) clf2 = pickle.loads(s) clf2.predict(X[0:1]) array([0]) y[0] 0 # In[ ]: # In[24]: import numpy as np import pandas as pd from sklearn import datasets from sklearn.ensemble import RandomForestClassifier iris = datasets.load_iris() mapping = dict(zip(np.unique(iris.target), iris.target_names)) mapping # In[38]: X = pd.DataFrame(iris.data, columns=iris.feature_names) y = pd.DataFrame(iris.target).replace(mapping) X.head(3), y.head(3) # Train, Test DataFrame # In[40]: clf = RandomForestClassifier() clf.fit(X,y) # In[ ]: # In[ ]: # In[ ]: # In[ ]: # In[34]: # In[37]: # In[27]: # Model Save & Load # In[ ]: import pickle s = pickle.dumps(clf) clf2 = pickle.loads(s) clf2.predict(X[0:1]) array([0]) y[0] 0