Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Storing, Loading, and Using ML Models With Sklearn

DZone's Guide to

Storing, Loading, and Using ML Models With Sklearn

Explore storing, loading, and using Machine Learning models with sklearn.

· AI Zone ·
Free Resource

Did you know that 50- 80% of your enterprise business processes can be automated with AssistEdge?  Identify processes, deploy bots and scale effortlessly with AssistEdge.

One of the situations we often encounter is the need to store and use machine learning based models. In this article, I will talk about how to store the models we created with sklearn and how to load and use them later. I hope there will be a useful article in terms of awareness.

First, let's create a model. In this example, we will create a model that will make a simple text classification. Information about the data set that I will use when creating this model is as follows.

Data Set Name: Sentiment Labeled Sentences Data Set 

Data Set Source: UCI Machine Learning Library

Data Set Info: This dataset was created with user reviews collected via 3 different websites (Amazon, Yelp, IMDB). These comments consist of restaurant, film, and product reviews. Each record in the data set is labeled with two different emot  ons. These are 1: Positive, 0: Negative.

Now let's move to the model creation step.

import pandas as pd
import numpy as np
import pickle
import sys
import os
import io
import re
from sys import path
import numpy as np
import pickle
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelBinarizer
import matplotlib.pyplot as plt
from string import punctuation, digits
from IPython.core.display import display, HTML
from nltk.corpus import stopwords
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from nltk.tokenize import RegexpTokenizer

#Amazon Data
input_file = "../data/amazon_cells_labelled.txt"
amazon = pd.read_csv(input_file,delimiter='\t',header=None)
amazon.columns = ['Sentence','Class']

#Yelp Data
input_file = "../data/yelp_labelled.txt"
yelp = pd.read_csv(input_file,delimiter='\t',header=None)
yelp.columns = ['Sentence','Class']

#Imdb Data
input_file = "../data/imdb_labelled.txt"
imdb = pd.read_csv(input_file,delimiter='\t',header=None)
imdb.columns = ['Sentence','Class']


#combine all data sets
data = pd.DataFrame()
data = pd.concat([amazon, yelp, imdb])
data['index'] = data.index

#Text Preprocessing
columns = ['index','Class', 'Sentence']
df_ = pd.DataFrame(columns=columns)

#lower string
data['Sentence'] = data['Sentence'].str.lower()

#remove email adress
data['Sentence'] = data['Sentence'].replace('[a-zA-Z0-9-_.]+@[a-zA-Z0-9-_.]+', '', regex=True)

#remove IP address
data['Sentence'] = data['Sentence'].replace('((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.|$)){4}', '', regex=True)

#remove punctaitions and special chracters
data['Sentence'] = data['Sentence'].str.replace('[^\w\s]','')

#remove numbers
data['Sentence'] = data['Sentence'].replace('\d', '', regex=True)

#remove stop words
for index, row in data.iterrows():
    word_tokens = word_tokenize(row['Sentence'])
    filtered_sentence = [w for w in word_tokens if not w in stopwords.words('english')]
    df_ = df_.append({"index": row['index'], "Class":  row['Class'],"Sentence": " ".join(filtered_sentence[0:])}, ignore_index=True)

data = df_

#Split test and training data set
X_train, X_test, y_train, y_test = train_test_split(data['Sentence'].values.astype('U'),data['Class'].values.astype('int32'), test_size=0.10, random_state=0)
classes  = data['Class'].unique()

#Creating Model
from sklearn.metrics import confusion_matrix
from sklearn.model_selection import cross_val_score
from sklearn.metrics import accuracy_score
from sklearn.neural_network import MLPClassifier
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import SGDClassifier


#grid search result
vectorizer = TfidfVectorizer(analyzer='word',ngram_range=(1,2), max_features=50000,max_df=0.5,use_idf=True, norm='l2') 
counts = vectorizer.fit_transform(X_train)
vocab = vectorizer.vocabulary_
classifier = SGDClassifier(alpha=1e-05,max_iter=50,penalty='elasticnet')
targets = y_train
classifier = classifier.fit(counts, targets)
example_counts = vectorizer.transform(X_test)
predictions = classifier.predict(example_counts)

Yes, we created our model. Now, we will save this model using Pickle lib. 

# Model and Vocabulary Save
pickle.dump(classifier,open("sentiment_classifier.pkl","wb"))
pickle.dump(vocab,open("vocab_sentiment_classifier.pkl","wb"))

We saved our model. Now we restore the model and let us find the sentiment of a sample text.

# Reload Model and Vocabulary
vec = open("sentiment_classifier.pkl", 'rb')
loaded_model = pickle.load(vec)

vcb = open("vocab_sentiment_classifier.pkl", 'rb')
loaded_vocab = pickle.load(vcb)

Load operation completed successfully. Now let's make an example using the model that we loaded.


# Single Value Prediction
examples = 'this is the greatest film that I have ever seen'

#lower string
examples = examples.lower()

#remove email adress
examples = re.sub(r'[a-zA-Z0-9-_.]+@[a-zA-Z0-9-_.]+', '', examples)

#remove IP address
examples = re.sub(r'((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.|$)){4}', '', examples)

#remove punctaitions and special chracters
examples = re.sub(r'[^\w\s]', '', examples)

#remove numbers
examples = re.sub(r'\d', '', examples)

examples = [examples]

from sklearn.feature_extraction.text import TfidfTransformer
count_vect = TfidfVectorizer(analyzer='word',ngram_range=(1,2), max_features=50000,max_df=0.5,use_idf=True, norm='l2',vocabulary=loaded_vocab)
tfidf_transformer = TfidfTransformer()
x_count = count_vect.fit_transform(examples)
predicted = loaded_model.predict(x_count)

result_category = predicted[0]

if result_category == 1:
    print('Positive')
else:
    print('Negative')

Input: "This is the greatest film that I have ever seen."
Result: Positive

Consuming AI in byte sized applications is the best way to transform digitally. #BuiltOnAI, EdgeVerve’s business application, provides you with everything you need to plug & play AI into your enterprise.  Learn more.

Topics:
machine learning ,nlp ,predictive analytics ,ai ,sklearn ,tutorial

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}