成功解决 AttributeError: ‘Field‘ object has no attribute ‘vocab‘

这篇具有很好参考价值的文章主要介绍了成功解决 AttributeError: ‘Field‘ object has no attribute ‘vocab‘。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

最近复现代码过程中,需要用到 torchtext.data 中的 Field 类。本篇博客记录使用过程中的问题及解决方式。

  1. 注意 torchtext 版本不宜过新

在较新版本的 torchtext.data 里面并没有 Field 方法,这一点需要注意。

启示:在复现别人代码时,应同时复制他们使用环境的版本信息。

  1. 运行下述代码:
from torchtext.data import Field

SRC = Field(tokenize = tokenize_en, 
            init_token = '<sos>', 
            eos_token = '<eos>',
            fix_length = max_length,
            lower = True, 
            batch_first = True,
            sequential=True)

TRG = Field(tokenize = tokenize_en, 
            init_token = '<sos>', 
            eos_token = '<eos>', 
            fix_length = max_length,
            lower = True, 
            batch_first = True,
            sequential=True)

print(SRC.vocab.stoi["<sos>"])
print(TRG.vocab.stoi["<sos>"])

报错信息:

print(SRC.vocab.stoi["<sos>"])  # 2
AttributeError: 'Field' object has no attribute 'vocab'

于是查看 Field 类的定义,寻找和词表建立相关的函数,发现其 build_vocab() 函数中有建立词表的操作, build_vocab() 函数定义如下:

class Field(RawField):
	
	...
    
    def build_vocab(self, *args, **kwargs):
        """Construct the Vocab object for this field from one or more datasets.

        Arguments:
            Positional arguments: Dataset objects or other iterable data
                sources from which to construct the Vocab object that
                represents the set of possible values for this field. If
                a Dataset object is provided, all columns corresponding
                to this field are used; individual columns can also be
                provided directly.
            Remaining keyword arguments: Passed to the constructor of Vocab.
        """
        counter = Counter()
        sources = []
        for arg in args:
            if isinstance(arg, Dataset):
                sources += [getattr(arg, name) for name, field in
                            arg.fields.items() if field is self]
            else:
                sources.append(arg)
        for data in sources:
            for x in data:
                if not self.sequential:
                    x = [x]
                try:
                    counter.update(x)
                except TypeError:
                    counter.update(chain.from_iterable(x))
        specials = list(OrderedDict.fromkeys(
            tok for tok in [self.unk_token, self.pad_token, self.init_token,
                            self.eos_token] + kwargs.pop('specials', [])
            if tok is not None))
        self.vocab = self.vocab_cls(counter, specials=specials, **kwargs)
	
	...

解决方式:在程序中 Field 定义后添加 SRC.build_vocab()TRG.build_vocab(),程序变成:

SRC.build_vocab()
TRG.build_vocab()

print(SRC.vocab.stoi["<sos>"])  # 输出结果:2
print(TRG.vocab.stoi["<sos>"])  # 输出结果:2

至此,程序就会顺利执行啦!


参考资料文章来源地址https://www.toymoban.com/news/detail-539560.html

  1. python - BucketIterator 抛出 ‘Field’ 对象没有属性 ‘vocab’ - IT工具网 (coder.work)
  2. ImportError: cannot import name ‘Field‘ from ‘torchtext.data‘, No module named “legacy“_no module named 'torchtext.legacy_御用厨师的博客-CSDN博客

到了这里,关于成功解决 AttributeError: ‘Field‘ object has no attribute ‘vocab‘的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 解决AttributeError: ‘Namespace‘ object has no attribute ‘arch‘

    在运行ACmix-ResNet模型时出现问题 很简单的一个错误,没有添加参数 使用parser添加相应参数即可

    2024年02月08日
    浏览(35)
  • 解决AttributeError: ‘DataFrame‘ object has no attribute ‘append‘

    自然语言处理执行 train_data = pd.DataFrame()... contents = pd.DataFrame(content)... 再执行train_data = train_data.append(contents[:400])出现错误AttributeError: \\\'DataFrame\\\' object has no attribute \\\'append\\\' 估计是pandas版本升级弃用了 老版本\\\'DataFrame\\\'的append方法。由于pandas与众多的第三方软件包捆绑,一般不宜轻易

    2024年02月11日
    浏览(38)
  • 已解决AttributeError: ‘list‘ object has no attribute ‘text‘

    已解决AttributeError: ‘list’ object has no attribute ‘text’ 粉丝群里面的一个小伙伴遇到问题跑来私信我,想用selenium操作浏览器自动化,但是发生了报错(当时他心里瞬间凉了一大截,跑来找我求助,然后顺利帮助他解决了,顺便记录一下希望可以帮助到更多遇到这个bug不会解决

    2023年04月17日
    浏览(75)
  • 已解决AttributeError: ‘str‘ object has no attribute ‘read‘

    已解决(json.load()读取json文件报错)AttributeError: ‘str‘ object has no attribute ‘read‘ 粉丝群里面的一个粉丝在用Python读取json文件的时候,出现了报错(跑来找我求助,然后顺利帮助他解决了,顺便记录一下希望可以帮助到更多遇到这个bug不会解决的小伙伴),报错信息和代码

    2024年02月12日
    浏览(32)
  • 成功解决AttributeError: module ‘numpy‘ has no attribute ‘float‘.

    AttributeError: module ‘numpy’ has no attribute ‘float’. np.float was a deprecated alias for the builtin float . To avoid this error in existing code, use float by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use np.float64 here. The aliases was originally deprecated in NumPy 1.20; for

    2024年02月16日
    浏览(46)
  • AttributeError: ‘NoneType‘ object has no attribute ‘split‘的解决办法

    在用KMeans算法训练数据的时候,报错如下: 经过各种途径的查询,有些回答建议尝试对sklearn、numpy修改版本。经过验证,sklearn与numpy版本与建议者所要修改的版本一致,故没有采纳。 经过自己的仔细观察,因为在使用KMeans算法训练数据代码之前,只有一行代码,那就是 故尝

    2024年02月13日
    浏览(29)
  • AttributeError:‘CartPoleEnv‘ object has no attribute ‘seed‘解决方案

    在尝试运行gym的classic control模块中的Cart Pole的相关代码时,想用随机种子重置一下环境,结果不停的报AttributeError:\\\'CartPoleEnv\\\' object has no attribute \\\'seed\\\'的错,查看gym的官方文档后也没有得出什么结果。后来,意外发现了在另外一台机器上运行该代码的警告信息: gym/core.py:256:

    2024年02月15日
    浏览(34)
  • 已解决AttributeError: ‘str‘ object has no attribute ‘decode‘方案二

    已解决AttributeError: ‘str‘ object has no attribute ‘decode‘解决方法异常的正确解决方法,亲测有效!!! AttributeError: ‘str‘ object has no attribute ‘decode‘ AttributeError: ‘str’ object has no attribute \\\'decode’错误通常发生在Python 3版本中,当尝试对字符串对象使用decode()方法时。 下滑查

    2024年02月07日
    浏览(26)
  • 解决出现的AttributeError: ‘dict‘ object has no attribute ‘encode‘错误

    这个错误通常表示您正在尝试对字典类型的对象使用字符串编码方法。但是字典类型的对象没有编码属性。 通常可能需要检查代码中哪些部分试图将字典转换为字符串并应用编码。例如,在以下代码中: 这个错误就会出现,因为字典类型的对象没有encode() 方法 解决方法是将字

    2024年02月11日
    浏览(36)
  • AttributeError: ‘bytes‘ object has no attribute ‘encode‘异常解决方案

    AttributeError: \\\'bytes\\\' object has no attribute \\\'encode\\\'是:“字节”对象没有属性的编码的意思。 很明显,是编码格式的问题,例如:已经是byte格式的字符串类型,二次进行encode的时候就会出现这个bug,示例如下: 异常的报错效果如下: 其实异常说的是比较明显的,属性误差:【At

    2024年02月11日
    浏览(32)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包