How to Make Predictions of Data Using Sklearn's RandomForestClassifier












0















I followed this website here https://stackabuse.com/text-classification-with-python-and-scikit-learn/ and have successfully completed the model and saved it using my own data, however I don't know how to test a new document on the model. I have a bunch of documents in a string format like so: string = "Whatever and more of whatever" and I just need to know what code I need to run to test these documents through my model. My code is the exact same as the website with the only difference being the files I have loaded and to solve my problem I tried to use classifier.predict(string) and it gave me the error ValueError: could not convert string to float. Any help would be appreciated.



import re
import nltk
from sklearn.datasets import load_files
from sklearn.ensemble import RandomForestClassifier
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.model_selection import train_test_split
nltk.download('wordnet')
from nltk.stem.wordnet import WordNetLemmatizer
stemmer = WordNetLemmatizer()
nltk.download('stopwords')
import pickle
from nltk.corpus import stopwords

doctor_data = load_files(r"pathtodata")
X, y = doctor_data.data, doctor_data.target

documents =
for sen in range(0, len(X)):
# Remove all the special characters
document = re.sub(r'W', ' ', str(X[sen]))

# remove all single characters
document = re.sub(r's+[a-zA-Z]s+', ' ', document)

# Remove single characters from the start
document = re.sub(r'^[a-zA-Z]s+', ' ', document)

# Substituting multiple spaces with single space
document = re.sub(r's+', ' ', document, flags=re.I)

# Removing prefixed 'b'
document = re.sub(r'^bs+', '', document)

# Converting to Lowercase
document = document.lower()

# Lemmatization
document = document.split()

document = [stemmer.lemmatize(word) for word in document]
document = ' '.join(document)

documents.append(document)

vectorizer = CountVectorizer(max_features=1500, min_df=5, max_df=0.7, stop_words=stopwords.words('english'))
X = vectorizer.fit_transform(documents).toarray()

tfidfconverter = TfidfTransformer()
X = tfidfconverter.fit_transform(X).toarray()

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)

classifier = RandomForestClassifier(n_estimators=1000, random_state=0)
classifier.fit(X_train, y_train)

y_pred = classifier.predict(X_test)

from sklearn.metrics import classification_report, confusion_matrix, accuracy_score

print(confusion_matrix(y_test,y_pred))
print(classification_report(y_test,y_pred))
print(accuracy_score(y_test, y_pred))
with open('text_classifier', 'wb') as picklefile:
pickle.dump(classifier,picklefile)


Update:
I tried to convert my document to the proper format using this code



vectorizer = CountVectorizer(max_features=1500, min_df=5, max_df=0.7, stop_words=stopwords.words('english'))
X = vectorizer.fit_transform(MYDOC).toarray()

tfidfconverter = TfidfTransformer()
X = tfidfconverter.fit_transform(X).toarray()

pred = model.predict(X)
print(pred)


And this is the error I got
ValueError: Number of features of the model must match the input. Model n_features is 897 and input n_features is 149










share|improve this question

























  • Hard to know what's your issue without the code, but you need to apply the same transformation to your new document as you did to the training one.

    – Guillaume Legoy
    Nov 22 '18 at 19:13











  • Sorry, here is my code. It works and dumps the data as a pickle file I can later access, but I don't know how to run a new document with this code

    – CodingKing
    Nov 22 '18 at 19:18











  • Apply the same transformation to the new document (minus the y target) as you did above to the training document, then run your classifier on it with .predict.

    – Guillaume Legoy
    Nov 22 '18 at 19:22













  • If you use this exact same code, your problem comes from the fact that you don't give the path to your data: doctor_data = load_files(r"pathtodata")

    – godot
    Nov 22 '18 at 19:29











  • NB: I just tried your code after downloading the dataset and it works. The result I have is the same as the tutorial: [[180 28] [ 30 162]] precision recall f1-score support 0 0.86 0.87 0.86 208 1 0.85 0.84 0.85 192 avg / total 0.85 0.85 0.85 400 0.855

    – godot
    Nov 22 '18 at 19:36


















0















I followed this website here https://stackabuse.com/text-classification-with-python-and-scikit-learn/ and have successfully completed the model and saved it using my own data, however I don't know how to test a new document on the model. I have a bunch of documents in a string format like so: string = "Whatever and more of whatever" and I just need to know what code I need to run to test these documents through my model. My code is the exact same as the website with the only difference being the files I have loaded and to solve my problem I tried to use classifier.predict(string) and it gave me the error ValueError: could not convert string to float. Any help would be appreciated.



import re
import nltk
from sklearn.datasets import load_files
from sklearn.ensemble import RandomForestClassifier
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.model_selection import train_test_split
nltk.download('wordnet')
from nltk.stem.wordnet import WordNetLemmatizer
stemmer = WordNetLemmatizer()
nltk.download('stopwords')
import pickle
from nltk.corpus import stopwords

doctor_data = load_files(r"pathtodata")
X, y = doctor_data.data, doctor_data.target

documents =
for sen in range(0, len(X)):
# Remove all the special characters
document = re.sub(r'W', ' ', str(X[sen]))

# remove all single characters
document = re.sub(r's+[a-zA-Z]s+', ' ', document)

# Remove single characters from the start
document = re.sub(r'^[a-zA-Z]s+', ' ', document)

# Substituting multiple spaces with single space
document = re.sub(r's+', ' ', document, flags=re.I)

# Removing prefixed 'b'
document = re.sub(r'^bs+', '', document)

# Converting to Lowercase
document = document.lower()

# Lemmatization
document = document.split()

document = [stemmer.lemmatize(word) for word in document]
document = ' '.join(document)

documents.append(document)

vectorizer = CountVectorizer(max_features=1500, min_df=5, max_df=0.7, stop_words=stopwords.words('english'))
X = vectorizer.fit_transform(documents).toarray()

tfidfconverter = TfidfTransformer()
X = tfidfconverter.fit_transform(X).toarray()

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)

classifier = RandomForestClassifier(n_estimators=1000, random_state=0)
classifier.fit(X_train, y_train)

y_pred = classifier.predict(X_test)

from sklearn.metrics import classification_report, confusion_matrix, accuracy_score

print(confusion_matrix(y_test,y_pred))
print(classification_report(y_test,y_pred))
print(accuracy_score(y_test, y_pred))
with open('text_classifier', 'wb') as picklefile:
pickle.dump(classifier,picklefile)


Update:
I tried to convert my document to the proper format using this code



vectorizer = CountVectorizer(max_features=1500, min_df=5, max_df=0.7, stop_words=stopwords.words('english'))
X = vectorizer.fit_transform(MYDOC).toarray()

tfidfconverter = TfidfTransformer()
X = tfidfconverter.fit_transform(X).toarray()

pred = model.predict(X)
print(pred)


And this is the error I got
ValueError: Number of features of the model must match the input. Model n_features is 897 and input n_features is 149










share|improve this question

























  • Hard to know what's your issue without the code, but you need to apply the same transformation to your new document as you did to the training one.

    – Guillaume Legoy
    Nov 22 '18 at 19:13











  • Sorry, here is my code. It works and dumps the data as a pickle file I can later access, but I don't know how to run a new document with this code

    – CodingKing
    Nov 22 '18 at 19:18











  • Apply the same transformation to the new document (minus the y target) as you did above to the training document, then run your classifier on it with .predict.

    – Guillaume Legoy
    Nov 22 '18 at 19:22













  • If you use this exact same code, your problem comes from the fact that you don't give the path to your data: doctor_data = load_files(r"pathtodata")

    – godot
    Nov 22 '18 at 19:29











  • NB: I just tried your code after downloading the dataset and it works. The result I have is the same as the tutorial: [[180 28] [ 30 162]] precision recall f1-score support 0 0.86 0.87 0.86 208 1 0.85 0.84 0.85 192 avg / total 0.85 0.85 0.85 400 0.855

    – godot
    Nov 22 '18 at 19:36
















0












0








0


1






I followed this website here https://stackabuse.com/text-classification-with-python-and-scikit-learn/ and have successfully completed the model and saved it using my own data, however I don't know how to test a new document on the model. I have a bunch of documents in a string format like so: string = "Whatever and more of whatever" and I just need to know what code I need to run to test these documents through my model. My code is the exact same as the website with the only difference being the files I have loaded and to solve my problem I tried to use classifier.predict(string) and it gave me the error ValueError: could not convert string to float. Any help would be appreciated.



import re
import nltk
from sklearn.datasets import load_files
from sklearn.ensemble import RandomForestClassifier
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.model_selection import train_test_split
nltk.download('wordnet')
from nltk.stem.wordnet import WordNetLemmatizer
stemmer = WordNetLemmatizer()
nltk.download('stopwords')
import pickle
from nltk.corpus import stopwords

doctor_data = load_files(r"pathtodata")
X, y = doctor_data.data, doctor_data.target

documents =
for sen in range(0, len(X)):
# Remove all the special characters
document = re.sub(r'W', ' ', str(X[sen]))

# remove all single characters
document = re.sub(r's+[a-zA-Z]s+', ' ', document)

# Remove single characters from the start
document = re.sub(r'^[a-zA-Z]s+', ' ', document)

# Substituting multiple spaces with single space
document = re.sub(r's+', ' ', document, flags=re.I)

# Removing prefixed 'b'
document = re.sub(r'^bs+', '', document)

# Converting to Lowercase
document = document.lower()

# Lemmatization
document = document.split()

document = [stemmer.lemmatize(word) for word in document]
document = ' '.join(document)

documents.append(document)

vectorizer = CountVectorizer(max_features=1500, min_df=5, max_df=0.7, stop_words=stopwords.words('english'))
X = vectorizer.fit_transform(documents).toarray()

tfidfconverter = TfidfTransformer()
X = tfidfconverter.fit_transform(X).toarray()

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)

classifier = RandomForestClassifier(n_estimators=1000, random_state=0)
classifier.fit(X_train, y_train)

y_pred = classifier.predict(X_test)

from sklearn.metrics import classification_report, confusion_matrix, accuracy_score

print(confusion_matrix(y_test,y_pred))
print(classification_report(y_test,y_pred))
print(accuracy_score(y_test, y_pred))
with open('text_classifier', 'wb') as picklefile:
pickle.dump(classifier,picklefile)


Update:
I tried to convert my document to the proper format using this code



vectorizer = CountVectorizer(max_features=1500, min_df=5, max_df=0.7, stop_words=stopwords.words('english'))
X = vectorizer.fit_transform(MYDOC).toarray()

tfidfconverter = TfidfTransformer()
X = tfidfconverter.fit_transform(X).toarray()

pred = model.predict(X)
print(pred)


And this is the error I got
ValueError: Number of features of the model must match the input. Model n_features is 897 and input n_features is 149










share|improve this question
















I followed this website here https://stackabuse.com/text-classification-with-python-and-scikit-learn/ and have successfully completed the model and saved it using my own data, however I don't know how to test a new document on the model. I have a bunch of documents in a string format like so: string = "Whatever and more of whatever" and I just need to know what code I need to run to test these documents through my model. My code is the exact same as the website with the only difference being the files I have loaded and to solve my problem I tried to use classifier.predict(string) and it gave me the error ValueError: could not convert string to float. Any help would be appreciated.



import re
import nltk
from sklearn.datasets import load_files
from sklearn.ensemble import RandomForestClassifier
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.model_selection import train_test_split
nltk.download('wordnet')
from nltk.stem.wordnet import WordNetLemmatizer
stemmer = WordNetLemmatizer()
nltk.download('stopwords')
import pickle
from nltk.corpus import stopwords

doctor_data = load_files(r"pathtodata")
X, y = doctor_data.data, doctor_data.target

documents =
for sen in range(0, len(X)):
# Remove all the special characters
document = re.sub(r'W', ' ', str(X[sen]))

# remove all single characters
document = re.sub(r's+[a-zA-Z]s+', ' ', document)

# Remove single characters from the start
document = re.sub(r'^[a-zA-Z]s+', ' ', document)

# Substituting multiple spaces with single space
document = re.sub(r's+', ' ', document, flags=re.I)

# Removing prefixed 'b'
document = re.sub(r'^bs+', '', document)

# Converting to Lowercase
document = document.lower()

# Lemmatization
document = document.split()

document = [stemmer.lemmatize(word) for word in document]
document = ' '.join(document)

documents.append(document)

vectorizer = CountVectorizer(max_features=1500, min_df=5, max_df=0.7, stop_words=stopwords.words('english'))
X = vectorizer.fit_transform(documents).toarray()

tfidfconverter = TfidfTransformer()
X = tfidfconverter.fit_transform(X).toarray()

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)

classifier = RandomForestClassifier(n_estimators=1000, random_state=0)
classifier.fit(X_train, y_train)

y_pred = classifier.predict(X_test)

from sklearn.metrics import classification_report, confusion_matrix, accuracy_score

print(confusion_matrix(y_test,y_pred))
print(classification_report(y_test,y_pred))
print(accuracy_score(y_test, y_pred))
with open('text_classifier', 'wb') as picklefile:
pickle.dump(classifier,picklefile)


Update:
I tried to convert my document to the proper format using this code



vectorizer = CountVectorizer(max_features=1500, min_df=5, max_df=0.7, stop_words=stopwords.words('english'))
X = vectorizer.fit_transform(MYDOC).toarray()

tfidfconverter = TfidfTransformer()
X = tfidfconverter.fit_transform(X).toarray()

pred = model.predict(X)
print(pred)


And this is the error I got
ValueError: Number of features of the model must match the input. Model n_features is 897 and input n_features is 149







python machine-learning scikit-learn text-classification






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 22 '18 at 21:17







CodingKing

















asked Nov 22 '18 at 18:40









CodingKingCodingKing

62




62













  • Hard to know what's your issue without the code, but you need to apply the same transformation to your new document as you did to the training one.

    – Guillaume Legoy
    Nov 22 '18 at 19:13











  • Sorry, here is my code. It works and dumps the data as a pickle file I can later access, but I don't know how to run a new document with this code

    – CodingKing
    Nov 22 '18 at 19:18











  • Apply the same transformation to the new document (minus the y target) as you did above to the training document, then run your classifier on it with .predict.

    – Guillaume Legoy
    Nov 22 '18 at 19:22













  • If you use this exact same code, your problem comes from the fact that you don't give the path to your data: doctor_data = load_files(r"pathtodata")

    – godot
    Nov 22 '18 at 19:29











  • NB: I just tried your code after downloading the dataset and it works. The result I have is the same as the tutorial: [[180 28] [ 30 162]] precision recall f1-score support 0 0.86 0.87 0.86 208 1 0.85 0.84 0.85 192 avg / total 0.85 0.85 0.85 400 0.855

    – godot
    Nov 22 '18 at 19:36





















  • Hard to know what's your issue without the code, but you need to apply the same transformation to your new document as you did to the training one.

    – Guillaume Legoy
    Nov 22 '18 at 19:13











  • Sorry, here is my code. It works and dumps the data as a pickle file I can later access, but I don't know how to run a new document with this code

    – CodingKing
    Nov 22 '18 at 19:18











  • Apply the same transformation to the new document (minus the y target) as you did above to the training document, then run your classifier on it with .predict.

    – Guillaume Legoy
    Nov 22 '18 at 19:22













  • If you use this exact same code, your problem comes from the fact that you don't give the path to your data: doctor_data = load_files(r"pathtodata")

    – godot
    Nov 22 '18 at 19:29











  • NB: I just tried your code after downloading the dataset and it works. The result I have is the same as the tutorial: [[180 28] [ 30 162]] precision recall f1-score support 0 0.86 0.87 0.86 208 1 0.85 0.84 0.85 192 avg / total 0.85 0.85 0.85 400 0.855

    – godot
    Nov 22 '18 at 19:36



















Hard to know what's your issue without the code, but you need to apply the same transformation to your new document as you did to the training one.

– Guillaume Legoy
Nov 22 '18 at 19:13





Hard to know what's your issue without the code, but you need to apply the same transformation to your new document as you did to the training one.

– Guillaume Legoy
Nov 22 '18 at 19:13













Sorry, here is my code. It works and dumps the data as a pickle file I can later access, but I don't know how to run a new document with this code

– CodingKing
Nov 22 '18 at 19:18





Sorry, here is my code. It works and dumps the data as a pickle file I can later access, but I don't know how to run a new document with this code

– CodingKing
Nov 22 '18 at 19:18













Apply the same transformation to the new document (minus the y target) as you did above to the training document, then run your classifier on it with .predict.

– Guillaume Legoy
Nov 22 '18 at 19:22







Apply the same transformation to the new document (minus the y target) as you did above to the training document, then run your classifier on it with .predict.

– Guillaume Legoy
Nov 22 '18 at 19:22















If you use this exact same code, your problem comes from the fact that you don't give the path to your data: doctor_data = load_files(r"pathtodata")

– godot
Nov 22 '18 at 19:29





If you use this exact same code, your problem comes from the fact that you don't give the path to your data: doctor_data = load_files(r"pathtodata")

– godot
Nov 22 '18 at 19:29













NB: I just tried your code after downloading the dataset and it works. The result I have is the same as the tutorial: [[180 28] [ 30 162]] precision recall f1-score support 0 0.86 0.87 0.86 208 1 0.85 0.84 0.85 192 avg / total 0.85 0.85 0.85 400 0.855

– godot
Nov 22 '18 at 19:36







NB: I just tried your code after downloading the dataset and it works. The result I have is the same as the tutorial: [[180 28] [ 30 162]] precision recall f1-score support 0 0.86 0.87 0.86 208 1 0.85 0.84 0.85 192 avg / total 0.85 0.85 0.85 400 0.855

– godot
Nov 22 '18 at 19:36














0






active

oldest

votes











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53436609%2fhow-to-make-predictions-of-data-using-sklearns-randomforestclassifier%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























0






active

oldest

votes








0






active

oldest

votes









active

oldest

votes






active

oldest

votes
















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53436609%2fhow-to-make-predictions-of-data-using-sklearns-randomforestclassifier%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

"Incorrect syntax near the keyword 'ON'. (on update cascade, on delete cascade,)

Alcedinidae

Origin of the phrase “under your belt”?