Chedi Bechikh
Chedi Bechikh

Reputation: 173

Naivebayes MultinomialNB scikit-learn/sklearn

I am bulding a naive bayes classifier and I follow the tutorial on the scikit-learn website.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import time
import csv
import string
from sklearn.cross_validation import train_test_split
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB

# Importing dataset
data = pd.read_csv("test.csv", quotechar='"', delimiter=',',quoting=csv.QUOTE_ALL, skipinitialspace=True,error_bad_lines=False)
df2 = data.set_index("name", drop = False)



df2['sentiment'] = df2['rating'].apply(lambda rating : +1 if rating > 3 else -1)


train, test = train_test_split(df2, test_size=0.2)


count_vect = CountVectorizer()
X_train_counts = count_vect.fit_transform(traintrain['review'])
test_matrix = count_vect.transform(testrain['review'])

clf = MultinomialNB().fit(X_train_tfidf, train['sentiment'])

The first argument is the vocabulary dictionary and it returns a Document-Term matrix. What should be the second argument,twenty_train.target?

Edit Data example

Name, review,rating
film1,......,1
film2, the film is....,5 
film3, film about..., 4

with this instruction I created a new column , if the rating is >3 so the review is positive, else it is negative

df2['sentiment'] = df2['rating'].apply(lambda rating : +1 if rating > 3 else -1)

Upvotes: 3

Views: 9796

Answers (1)

seralouk
seralouk

Reputation: 33182

The fit method of MultinomialNB expects as input the x and y. Now, x should be the training vectors (training data) and y should be the target values.

clf = MultinomialNB().fit(X_train_tfidf, twenty_train.target)

In more detail:

X : {array-like, sparse matrix}, shape = [n_samples, n_features]
Training vectors, where n_samples is the number of samples and n_features is 
the number of features.

y : array-like, shape = [n_samples]
Target values.

Note: Make sure that shape = [n_samples, n_features] and shape = [n_samples] of x and y are defined correctly. Otherwise, the fit will throw an error.


Toy example:

from sklearn.datasets import fetch_20newsgroups
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn import metrics

newsgroups_train = fetch_20newsgroups(subset='train')
categories = ['alt.atheism', 'talk.religion.misc',
              'comp.graphics', 'sci.space']

newsgroups_train = fetch_20newsgroups(subset='train',
                                      categories=categories)
vectorizer = TfidfVectorizer()
# the following will be the training data
vectors = vectorizer.fit_transform(newsgroups_train.data)
vectors.shape

newsgroups_test = fetch_20newsgroups(subset='test',
                                     categories=categories)
# this is the test data
vectors_test = vectorizer.transform(newsgroups_test.data)

clf = MultinomialNB(alpha=.01)

# the fitting is done using the TRAINING data
# Check the shapes before fitting
vectors.shape
#(2034, 34118)
newsgroups_train.target.shape
#(2034,)

# fit the model using the TRAINING data
clf.fit(vectors, newsgroups_train.target)

# the PREDICTION is done using the TEST data
pred = clf.predict(vectors_test)

EDIT:

The newsgroups_train.target is just a numpy array that contains the labels (or targets or classes).

import numpy as np

newsgroups_train.target
array([1, 3, 2, ..., 1, 0, 1])

np.unique(newsgroups_train.target)
array([0, 1, 2, 3])

So in this example we have 4 different classes/targets.

This variable is needed in order to fit a classifier.

Upvotes: 5

Related Questions