如何使用Sklearn的RandomForestClassifier进行数据预测

时间:2018-11-22 18:40:35

标签: python machine-learning scikit-learn text-classification

我在https://stackabuse.com/text-classification-with-python-and-scikit-learn/处浏览了此网站,并成功完成了模型并使用自己的数据进行了保存,但是我不知道如何在模型上测试新文档。我有一堆像这样的字符串格式的文档:string =“ Whatever and more of what any”,我只需要知道我需要运行什么代码来通过我的模型测试这些文档。我的代码与网站完全相同,唯一的不同是我已加载文件,并且为了解决我的问题,我尝试使用classifier.predict(string),它给了我错误ValueError:无法将字符串转换为float。任何帮助将不胜感激。

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'^b\s+', '', 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)

更新: 我尝试使用此代码将文档转换为正确的格式

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)

这是我得到的错误                                                                    ValueError:模型的特征数量必须与输入匹配。型号n_features为897,输入n_features为149

0 个答案:

没有答案