繁体   English   中英

python:AttributeError:'str'对象没有属性'keys'

[英]python : AttributeError: 'str' object has no attribute 'keys'

我正在尝试解决分类问题。 我不知道为什么会出现此错误:

AttributeError: 'str' object has no attribute 'keys'

这是主要代码

def generate_arrays_for_training(indexPat, paths, start=0, end=100):       
    while True:
        from_=int(len(paths)/100*start)
        to_=int(len(paths)/100*end)
        for i in range(from_, int(to_)):
            f=paths[i]
            x = np.load(PathSpectogramFolder+f)
     if('P' in f):
                y = np.repeat([[0,1]],x.shape[0], axis=0)
            else:
                y =np.repeat([[1,0]],x.shape[0], axis=0) 
            yield(x,y)
history=model.fit_generator(generate_arrays_for_training(indexPat, filesPath, end=75) ## problem here
                   steps_per_epoch=int((len(filesPath)-int(len(filesPath)/100*25))), 
                   validation_steps=int((len(filesPath)-int(len(filesPath)/100*75))),
                   verbose=2,class_weight="balanced",
                  epochs=15, max_queue_size=2, shuffle=True, callbacks=[callback])

其中generate_arrays_for_training函数返回xy x是浮点数的二维数组, y是 [0,1]。

错误

Traceback (most recent call last):
  File "/home/user1/thesis2/CNN_dwt2.py", line 437, in <module>
    main()
  File "/home/user1/thesis2/CNN_dwt2.py", line 316, in main
    history=model.fit_generator(generate_arrays_for_training(indexPat, filesPath, end=75), 
  File "/home/user1/.local/lib/python3.8/site-packages/tensorflow/python/util/deprecation.py", line 324, in new_func
    return func(*args, **kwargs)
  File "/home/user1/.local/lib/python3.8/site-packages/tensorflow/python/keras/engine/training.py", line 1815, in fit_generator
    return self.fit(
  File "/home/user1/.local/lib/python3.8/site-packages/tensorflow/python/keras/engine/training.py", line 108, in _method_wrapper
    return method(self, *args, **kwargs)
  File "/home/user1/.local/lib/python3.8/site-packages/tensorflow/python/keras/engine/training.py", line 1049, in fit
    data_handler = data_adapter.DataHandler(
  File "/home/user1/.local/lib/python3.8/site-packages/tensorflow/python/keras/engine/data_adapter.py", line 1122, in __init__
    dataset = dataset.map(_make_class_weight_map_fn(class_weight))
  File "/home/user1/.local/lib/python3.8/site-packages/tensorflow/python/keras/engine/data_adapter.py", line 1295, in _make_class_weight_map_fn
    class_ids = list(sorted(class_weight.keys()))

AttributeError: 'str' object has no attribute 'keys'

您的问题是由传递给model.fit() class_weight="balanced"参数引起的

根据model.fit() 参考,这个参数应该是一个字典:可选字典将类索引(整数)映射到一个权重(浮点数)值,用于对损失函数进行加权(仅在训练期间)。 这对于告诉模型“更多关注”来自代表性不足的类的样本很有用。

尝试class_weight=None进行测试,它应该摆脱原始错误。 稍后提供适当的字典作为class_weight来解决不平衡的数据集问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM