【问题标题】:Supervised machine learning with scikit-learn使用 scikit-learn 进行监督机器学习
【发布时间】:2017-08-22 02:45:14
【问题描述】:

这是我第一次进行有监督的机器学习。这是一个相当高级的话题(至少对我来说),我发现很难指定一个问题,因为我不确定出了什么问题。

# Create a training list and test list (looks something like this):
train = [('this hostel was nice',2),('i hate this hostel',1)]
test = [('had a wonderful time',2),('terrible experience',1)]

# Loading modules
from sklearn.naive_bayes import MultinomialNB
from sklearn.feature_extraction.text import CountVectorizer
from sklearn import metrics

# Use a BOW representation of the reviews
vectorizer = CountVectorizer(stop_words='english') 
train_features = vectorizer.fit_transform([r[0] for r in train]) 
test_features = vectorizer.fit([r[0] for r in test])

# Fit a naive bayes model to the training data
nb = MultinomialNB()
nb.fit(train_features, [r[1] for r in train])

# Use the classifier to predict classification of test dataset
predictions = nb.predict(test_features)
actual=[r[1] for r in test]

这里我得到了错误:

float() argument must be a string or a number, not 'CountVectorizer'

这让我很困惑,因为我在评论中压缩的原始评分是:

type(ratings_new[0])
int

【问题讨论】:

  • 您是否有堆栈跟踪和/或发生错误的行号?
  • 这是您要查找的信息吗? Traceback(最近一次调用最后一次) in () ----> 1 predictions = nb.predict(test_features)

标签: python scikit-learn supervised-learning


【解决方案1】:

你应该换行

test_features = vectorizer.fit([r[0] for r in test])

到:

test_features = vectorizer.transform([r[0] for r in test])

原因是您已经使用您的训练数据来拟合矢量化器,因此您无需再次将其拟合到您的测试数据上。相反,您需要对其进行改造。

【讨论】:

    猜你喜欢
    • 2019-04-16
    • 2017-02-28
    • 2019-02-08
    • 2020-12-10
    • 2017-08-18
    • 2016-05-28
    • 2013-12-01
    • 2018-10-18
    相关资源
    最近更新 更多