avatarNaina Chaturvedi

Summary

The webpage provides a tutorial on building a logistic regression classifier for movie review sentiment analysis using Scikit-learn, along with an introduction to the library and its utility in machine learning.

Abstract

The article is part of a series on data science and machine learning, focusing on the practical application of Scikit-learn for text classification. It guides readers through the process of creating a logistic regression model to determine the sentiment of movie reviews, using the IMDB dataset. The tutorial covers data preprocessing, feature extraction using TF-IDF, and model evaluation, emphasizing the importance of text cleaning, tokenization, and stemming. The author also highlights the robustness of Scikit-learn as a tool for machine learning tasks and provides links to additional resources and related projects. The article concludes with an invitation to subscribe to a YouTube channel and a tech newsletter for more educational content.

Opinions

  • The author expresses that Scikit-learn is a well-designed and robust library for machine learning, which is essential for tasks such as regression, classification, and data analysis.
  • The article conveys enthusiasm for teaching and sharing knowledge, as evidenced by the invitation to subscribe to educational channels and newsletters.
  • There is an emphasis on the practical implementation of machine learning concepts, with the author providing code snippets and encouraging readers to follow along and apply the techniques.
  • The author values the importance of understanding the underlying principles of machine learning algorithms, such as logistic regression, and the significance of hyperparameter tuning for model optimization.
  • The inclusion of links to various projects and resources suggests a belief in the benefits of hands-on learning and community engagement in the field of data science and machine learning.

Day 39: 60 days of Data Science and Machine Learning Series

Scikit learn with a project..

Welcome back peeps. In this post we are going to understand the basics of Scikit learn with a project.

Some of the other best Series —

30 Days of Natural Language Processing ( NLP) Series

30 days of Data Engineering with projects Series

60 days of Data Science and ML Series with projects

100 days : Your Data Science and Machine Learning Degree Series with projects

23 Data Science Techniques You Should Know

Tech Interview Series — Curated List of coding questions

Complete System Design with most popular Questions Series

Complete Data Visualization and Pre-processing Series with projects

Complete Python Series with Projects

Complete Advanced Python Series with Projects

Kaggle Best Notebooks that will teach you the most

Complete Developers Guide to Git

All the Data Science and Machine Learning Resources

210 Machine Learning Projects

30 days of Machine Learning Ops

Projects Videos —

All the projects, data structures, SQL, algorithms, system design, Data Science and ML , Data Analytics, Data Engineering, , Implemented Data Science and ML projects, Implemented Data Engineering Projects, Implemented Deep Learning Projects, Implemented Machine Learning Ops Projects, Implemented Time Series Analysis and Forecasting Projects, Implemented Applied Machine Learning Projects, Implemented Tensorflow and Keras Projects, Implemented PyTorch Projects, Implemented Scikit Learn Projects, Implemented Big Data Projects, Implemented Cloud Machine Learning Projects, Implemented Neural Networks Projects, Implemented OpenCV Projects,Complete ML Research Papers Summarized, Implemented Data Analytics projects, Implemented Data Visualization Projects, Implemented Data Mining Projects, Implemented Natural Leaning Processing Projects, MLOps and Deep Learning, Applied Machine Learning with Projects Series, PyTorch with Projects Series, Tensorflow and Keras with Projects Series, Scikit Learn Series with Projects, Time Series Analysis and Forecasting with Projects Series, ML System Design Case Studies Series videos will be published on our youtube channel ( just launched).

Subscribe today!

Tech Newsletter —

If you are interested, you can join my newsletter through which I send tech interview tips, techniques, patterns, hacks — Software Development, ML, Data Science, Startups and Technology projects to more than 30K readers. You can subscribe to Tech Brew :

Scikit learn, a library which is written in Python and built upon Scipy, Matplotlib and Numpy provides a set of useful and efficient tools for machine learning and statistical modeling including regression, classification, clustering, predictive data analysis and dimensionality reduction etc and known as the most robust and useful library for Machine Learning.

In this post we are going to build a logistic regression classifier to classify movie reviews as either positive or negative.

The dataset for the project can be found here

Let’s dive in!

Import necessary files

import pandas as pd
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction import TfidTransformer
import re
from nltk.stem.porter import PorterStemmer
import nltk
nltk.download('stopwords')
from nltk.corpus import stopwords
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegressionCV

Load the data

df= pd.read_csv('Path to data file/data.csv')
df.info()

Output —

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 50000 entries, 0 to 49999
Data columns (total 2 columns):
review       50000 non-null object
sentiment    50000 non-null int64
dtypes: int64(1), object(1)
memory usage: 781.3+ KB

Transforming Documents into Feature Vectors

count = CountVectorizer()
docs = np.array (['The sun is shining',
'The weather is sweet',
'The sun is shining, the weather is sweet, and one and one is two'])
bag = count.fit_transform(docs)
print(bag.toarray())

Output —

[[0 1 0 1 1 0 1 0 0]
 [0 1 0 0 0 1 1 0 1]
 [2 3 2 1 1 1 2 1 1]]

Print Vocab

print(count.vocabulary_)

Output —

{'the': 6, 'sun': 4, 'is': 1, 'shining': 3, 'weather': 8, 'sweet': 5, 'and': 0, 'one': 2, 'two': 7}

Term Frequency-Inverse Document Frequency

A good reference to TF-IDF can be found here :

np.set_printoptions(precision = 2)
tfidf = TfidTransformer(use_idf = True, norm ='l2',smooth_idf = True)

Data Preparation

def preprocessor(text):
    text = re.sub('<[^>]*>', '', text)
    emoticons = re.findall('(?::|;|=)(?:-)?(?:\)|\(|D|P)', text)
    text = re.sub('[\W]+', ' ', text.lower()) +\
        ' '.join(emoticons).replace('-', '')
    return text
preprocessor(df.loc[0,'review'][-50:])
df['review'] = df['review'].apply(preprocessor)

Documents Tokenization

porter = PorterStemmer()
def tokenizer(text):
    return text.split()
def tokenizer_porter(text):
    return [porter.stem(word) for word in text.split()]
print(tokenizer('Its a wonderful day'))
print(tokenizer_porter('Beautiful day'))
stop = stopwords.words('english')
[w for w in tokenizer_porter('Snow feels magical during New year')[-5:] if w not in stop]

Output —

['Its', 'a', 'wonderful', 'day']
['beauti', 'day']
['feel', 'magic', 'dure', 'new', 'year']

Document Classification Using Logistic Regression

tfidf = TfidfVectorizer(
                            strip_accents = None, 
                            lowercase=False, preprocessor=None, tokenizer= tokenizer_porter,
                            use_idf = True, norm='l2',
                            smooth_idf= True
)
y = df.sentiment.values
X = tfidf.fit_transform(df.review)
X_train, X_test, y_train, y_test = train_test_split(X,y,random_state=1,test_size=0.5,shuffle=False)
clf = LogisticRegressionCV( cv=5, scoring = 'accuracy', random_state=0,n_jobs=-1,verbose = 3, max_iter = 300).fit(X_train,y_train)

Model Evaluation

clf.score(X_test,y_test)

Output —

0.89604

Learnings —

How to build a logistic regression classifier using scikit-learn, clean and pre-process text data, perform feature extraction with the Natural Language Toolkit (NLTK), tune model hyper parameters and evaluate the model.

Day 40: Coming soon!

Follow and Stay tuned. Keep coding :)

For other projects, tune to —

Build Machine Learning Pipelines( With Code)

Recurrent Neural Network with Keras

Clustering Geolocation Data in Python using DBSCAN and K-Means

Facial Expression Recognition using Keras

Hyperparameter Tuning with Keras Tuner

Custom Layers in Keras

That’s it fellas. Peace out and keep coding :)

Stay Tuned and of-course let me end this post with a quote by Steve Jobs ;)

“You have to be burning with an idea, or a problem, or a wrong that you want to right. If you’re not passionate enough from the start, you’ll never stick it out.”

Machine Learning
Artificial Intelligence
Programming
Tech
Data Science
Recommended from ReadMedium