【问题标题】:AttributeError: dense not foundAttributeError:未找到密集
【发布时间】:2021-02-28 23:52:30
【问题描述】:

任务:使用CountVectorizerTfidfTransformer 使用SVC 进行文档分类。

我已经使用pickle 对模型进行了训练、测试并与 CountVectorizer 和 TfidfTransformer 一起保存了模型。

现在,当我加载并使用它进行预测时,它会给出AttributeError: dense not found

我在训练和测试阶段检查了输入的形状。一样的。但我认为形状不是问题。

在训练和通过加载使用它之间没有进行版本更新。一切都在同一个版本scikit-learn==0.23.2

这是我的代码:

#Training
X_train = train["Text"]
Y_train = train["Class"]

count = CountVectorizer(lowercase=False)
X_count_vector = count.fit_transform(X_train)

tfidf = TfidfTransformer(smooth_idf=True, use_idf=True)
X_train = tfidf.fit_transform(X_count_vector)

classifier = SVC()
classifier.fit(X_train.todense(), Y_train) #Training as dense matrix

#Testing
cvec = count.transform(test["Text"])
predable = tfidf.transform(cvec)
pred = classifier.predict(predable.todense()) #This line works, it gived the predicted values as expected.

#Saving the model
pickle.dump(classifier, open("classifier.txt", 'wb'))
pickle.dump(count, open("countVec.txt", 'wb'))
pickle.dump(tfidf, open("tfidf.txt", 'wb'))

#Loading the model
classifiernew = pickle.load(open("classifier.txt", 'rb'))
countVectornew = pickle.load(open("countVec.txt", 'rb'))
tfidfnew = pickle.load(open("tfidf.txt", 'rb'))

#Using the Loaded Model
newInp = test["Text"]
countVec = countVectornew.transform(newInp)
X_test = tfidfnew.transform(countVec)
#Prediction, this is where the Error enters in
predd = classifiernew.predict(X_test.todense()) #The error causing line

这是完整的回溯:

res = clf.predict(testable.dense())
Traceback (most recent call last):

  File "<ipython-input-74-d4714966beb3>", line 1, in <module>
    res = clf.predict(testable.dense())

  File "...\env\lib\site-packages\scipy\sparse\base.py", line 687, in __getattr__
    raise AttributeError(attr + " not found")

AttributeError: dense not found

【问题讨论】:

  • 我建议发一个minimal reproducible example
  • @RandomDavis Ive 添加了代码以及负责该问题的行。如果您需要任何详细信息,请告诉我。
  • 无法发布答案,但我找到了解决此问题的方法。由于某种原因 .dense() 方法不起作用,我使用了 .toarray() ,它对我来说非常有效。谢谢。

标签: python machine-learning scikit-learn svm tf-idf


【解决方案1】:

好吧,在重新打开这个问题之后,我可以针对这个问题发布一个解决方法。 出于某种原因,.dense() 方法不起作用,我使用了 .toarray(),这对我来说非常有效。

快乐建模。

【讨论】:

    猜你喜欢
    • 2022-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-15
    • 2018-10-15
    • 2017-04-30
    • 2018-12-01
    • 1970-01-01
    相关资源
    最近更新 更多