gpt4 book ai didi

python - 如何在使用带有 python 的朴素贝叶斯训练数据后进行预测?

转载 作者:行者123 更新时间:2023-11-28 22:22:48 25 4
gpt4 key购买 nike

我有一个数据集,其中仅包含两个用于训练我的模型的有用列,第一个是新闻标题,第二个是新闻类别。

因此,我使用 python 成功运行了以下训练命令:

import re
import numpy as np
import pandas as pd
# the Naive Bayes model
from sklearn.naive_bayes import MultinomialNB
# function to split the data for cross-validation
from sklearn.model_selection import train_test_split
# function for transforming documents into counts
from sklearn.feature_extraction.text import CountVectorizer
# function for encoding categories
from sklearn.preprocessing import LabelEncoder


# grab the data
news = pd.read_csv("/Users/helloworld/Downloads/NewsAggregatorDataset/newsCorpora.csv",encoding='latin-1')
news.head()

def normalize_text(s):
s = s.lower()

# remove punctuation that is not word-internal (e.g., hyphens, apostrophes)
s = re.sub('\s\W',' ',s)
s = re.sub('\W\s',' ',s)

# make sure we didn't introduce any double spaces
s = re.sub('\s+',' ',s)

return s

news['TEXT'] = [normalize_text(s) for s in news['TITLE']]

# pull the data into vectors
vectorizer = CountVectorizer()
x = vectorizer.fit_transform(news['TEXT'])

encoder = LabelEncoder()
y = encoder.fit_transform(news['CATEGORY'])

# split into train and test sets
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)

nb = MultinomialNB()
nb.fit(x_train, y_train)

所以我的问题是,我如何提供一组新数据(例如只是新闻标题)并告诉程序使用 python sklearn 命令预测新闻类别?

附言我的训练数据是这样的:

enter image description here

最佳答案

您应该使用训练数据训练模型(就像您所做的那样),然后您应该使用新数据(测试数据)进行预测。


执行以下操作:

nb = MultinomialNB()
nb.fit(x_train, y_train)

y_predicted = nb.predict(x_test)

现在,如果您想根据**准确度评估预测,您可以执行以下操作:**

from sklearn.metrics import accuracy_score

accuracy_score(y_test, y_predicted)

同样,您可以计算其他指标。

最后,我们可以看到所有可用的指标 here !


编辑 1

当你输入时:

 y_predicted = nb.predict(x_test)

y_predicted 将包含与您的类别相对应的数值。

要投影回这些值并获取标签,您可以执行以下操作:

y_predicted_labels = encoder.inverse_transform(y_predicted) 

关于python - 如何在使用带有 python 的朴素贝叶斯训练数据后进行预测?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47438313/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com