我正在实现这个代码,这给了我相应的输出,但我想将这四行“数据集”保存在一个文件中然后使用它。我可以这样做吗?我怎么能用我自己的文件代替手动输入数据集?
from naiveBayesClassifier import tokenizer
from naiveBayesClassifier.trainer import Trainer
from naiveBayesClassifier.classifier import Classifier
nTrainer = Trainer(tokenizer)
dataSet =[
{'text': 'hello everyone', 'category': 'NO'},
{'text': 'dont use words like jerk', 'category': 'YES'},
{'text': 'what the hell.', 'category': 'NO'},
{'text': 'you jerk','category': 'yes'},
]
for n in dataSet:
nTrainer.train(n['text'], n['category'])
nClassifier = Classifier(nTrainer.data, tokenizer)
.
unknownInstance = "Even if I eat too much, is not it possible to lose some weight"
classification = nClassifier.classify(unknownInstance)
print classification
答案 0 :(得分:1)
您可以将数据集存储为json文件,然后将其加载到您的python代码中:
import json
with open('data.json') as f:
dataSet = json.loads(f.read())
# Use dataset.
答案 1 :(得分:0)
这条线似乎是最有效的训练工作。
nTrainer.train(n['text'], n['category'])
这条线似乎在学习后进行预测。
classification = nClassifier.classify(unknownInstance)
因此,如果您有一个语料库列表(培训数据),您要预测的相应标签和数据列表列表(未知实例)
你可以这样像
from naiveBayesClassifier import tokenizer
from naiveBayesClassifier.trainer import Trainer
from naiveBayesClassifier.classifier import Classifier
corpus = ['hello everyone', 'dont use words like jerk', 'what the hell.', 'you jerk'] # Your training data
labels = ['NO', 'YES', 'NO', 'YES'] # Your labels
unknown_data = ['Even if I eat too much, is not it possible to lose some weight'] # List of data to be predicted
nTrainer = Trainer(tokenizer)
# model training
for item, category in zip(corpus, labels):
nTrainer.train(item, category)
nClassifier = Classifier(nTrainer.data, tokenizer)
predictions = [ nClassifier.classify(unknownInstance) for unknownInstance in unknown_data]
print classification