简体   繁体   中英

How to predict the label after training the dataset in NLP

I am trying to do sentiment analysis on comments; the data set contains two main colums: the first one is "review" which has the reviews of the users, and the second colum is whether it is positive or negative; I got a template from a source to prepocessing the data, the training and testing is okay. However, I want to input a text and want the model to predict whether it is positive or negative. I tried so many forms of the input: string only, list of strings, numpy to array etc. However, I always got erros; any ideas how to input the data to be predicted? here's my code:

import matplotlib.pyplot as plt
import pandas as pd

# Importing the dataset
dataset = pd.read_csv('Restaurant_Reviews.tsv', delimiter='\t',quoting=3)

import re 
import nltk
nltk.download('stopwords')
from nltk.corpus import stopwords
from nltk.stem.porter import PorterStemmer
corpus=[]
for i in range(0,1000):
    review=re.sub('[^a-zA-Z]',' ',dataset['Review'][i])
    review.lower()
    review=review.split()
    ps=PorterStemmer()
    review=[ps.stem(word) for word in review if not word in set(stopwords.words('english'))]
    review=' '.join(review)
    corpus.append(review)

#the bag of word
from sklearn.feature_extraction.text import CountVectorizer
cv=CountVectorizer(max_features=1500)
X=cv.fit_transform(corpus).toarray()
y=dataset.iloc[:,1].values

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)



# Fitting Naive Bayes to the Training set
from sklearn.naive_bayes import GaussianNB
classifier = GaussianNB()
classifier.fit(X_train, y_train)

# Predicting the Test set results
xeval=["I like it okay"]
prediction=classifier.predict(xeval)```

the error in this case is:
Expected 2D array, got 1D array instead:
array=['I like it okay'].
Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.

As G.Anderson has already mentioned your classfier is trained with numerical data, as you used:

X=cv.fit_transform(corpus).toarray()

and CountVectorizer is made for this.

To use it, you also have to use the trained CountVectorizer, you have to implement:

# Predicting the Test set results
xeval=["I like it okay"]
xeval_numeric = cv.transform(xeval).toarray() 
prediction=classifier.predict(xeval_numeric)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM