使用vectorizer.fit_transform时出现AttributeError: 'file' object has no attribute 'lower'

问题

最近在读书《Building Machine Learning Systems with Python》1第一版,发现其中的一个代码错误,

AttributeError: ‘file’ object has no attribute ‘lower’

产生该错误的代码为:

import os
os.listdir('./data/toy/')
posts = [open(os.path.join('./data/toy/',f)) for f in os.listdir('./data/toy/')]

from sklearn.feature_extraction.text import CountVectorizer
vectorizer = CountVectorizer(min_df=1)

X_train= vectorizer.fit_transform(posts)
num_samples, num_features = X_train.shape
print("#samples, %d, #features, %d" %(num_samples, num_features))

解决方法

感谢网站提供的解决方法,即将vectorizer = CountVectorizer(min_df=1)改为

vectorizer = CountVectorizer(min_df=1,input="file")

即可解决上面的错误。

由于我使用的是Ipython notebook运行环境,在同一个cell里面将代码改变了以后,重新运行,则出现了新的错误:

ValueError: empty vocabulary; perhaps the documents only contain stop words

尝试了半天也没有找到合适的解决办法。最后,我找到了解决办法:删除所有含有之前代码的cell,新建一个cell,在里面写入更新的代码,即可解决 “empty vocabularty”错误。这个错误与代码本身无关,而与使用的Ipython notebook环境有关。希望大家在以后使用Ipython notebook时,注意这类的问题。

运行成功的界面为:
这里写图片描述


  1. Building Machine Learning Systems with Python. 2013. Willi Ricchert, Luis Pedro Coelho. Packt publishing.
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值