【问题标题】:AttributeError: 'numpy.bool_' object has no attribute 'keys'AttributeError:“numpy.bool_”对象没有属性“键”
【发布时间】:2020-09-06 21:29:55
【问题描述】:

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

AttributeError: 'numpy.bool_' object has no attribute 'keys'     

这是主要代码:

import matplotlib
matplotlib.use("Agg")

from keras.preprocessing.image import ImageDataGenerator
from keras.callbacks import LearningRateScheduler
from keras.optimizers import Adagrad
from keras.utils import np_utils
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
from cancernet.cancernet import CancerNet
from cancernet import config
from imutils import paths
import matplotlib.pyplot as plt
import numpy as np
import os
 
NUM_EPOCHS=40; INIT_LR=1e-2; BS=32

trainPaths=list(paths.list_images(config.TRAIN_PATH))
lenTrain=len(trainPaths)
lenVal=len(list(paths.list_images(config.VAL_PATH)))
lenTest=len(list(paths.list_images(config.TEST_PATH)))

trainLabels=[int(p.split(os.path.sep)[-2]) for p in trainPaths]
trainLabels=np_utils.to_categorical(trainLabels)
classTotals=trainLabels.sum(axis=0)
classWeight=classTotals.max()/classTotals
 
trainAug = ImageDataGenerator(
    rescale=1/255.0,
    rotation_range=20,
    zoom_range=0.05,
    width_shift_range=0.1,
    height_shift_range=0.1,
    shear_range=0.05,
    horizontal_flip=True,
    vertical_flip=True,
    fill_mode="nearest")

valAug=ImageDataGenerator(rescale=1 / 255.0)

trainGen = trainAug.flow_from_directory(
    config.TRAIN_PATH,
    class_mode="categorical",
    target_size=(48,48),
    color_mode="rgb",
    shuffle=True,
    batch_size=BS)
valGen = valAug.flow_from_directory(
    config.VAL_PATH,
    class_mode="categorical",
    target_size=(48,48),
    color_mode="rgb",
    shuffle=False,
    batch_size=BS)
testGen = valAug.flow_from_directory(
    config.TEST_PATH,
    class_mode="categorical",
    target_size=(48,48),
    color_mode="rgb",
    shuffle=False,
    batch_size=BS)
 
model=CancerNet.build(width=48,height=48,depth=3,classes=2)
opt=Adagrad(lr=INIT_LR,decay=INIT_LR/NUM_EPOCHS)
model.compile(loss="binary_crossentropy",optimizer=opt,metrics=. 
["accuracy"])


M=model.fit_generator(
    trainGen,
    steps_per_epoch=lenTrain//BS,
    validation_data=valGen,
    validation_steps=lenVal//BS,
    class_weight=classWeight.all(),
    epochs=NUM_EPOCHS)

print("Now evaluating the model")
testGen.reset()
pred_indices=model.predict_generator(testGen,steps=(lenTest//BS)+1) 

pred_indices=np.argmax(pred_indices,axis=1)

print(classification_report(testGen.classes, pred_indices, 
target_names=testGen.class_indices.keys()))

cm=confusion_matrix(testGen.classes,pred_indices) 
total=sum(sum(cm))
accuracy=(cm[0,0]+cm[1,1])/total 
specificity=cm[1,1]/(cm[1,0]+cm[1,1])
sensitivity=cm[0,0]/(cm[0,0]+cm[0,1])
print(cm)
print(f'Accuracy: {accuracy}')
print(f'Specificity: {specificity}')
print(f'Sensitivity: {sensitivity}')

N = NUM_EPOCHS
plt.style.use("ggplot")
plt.figure()
plt.plot(np.arange(0,N), M.history["loss"], label="train_loss")
plt.plot(np.arange(0,N), M.history["val_loss"], label="val_loss")
plt.plot(np.arange(0,N), M.history["acc"], label="train_acc")
plt.plot(np.arange(0,N), M.history["val_acc"], label="val_acc")
plt.title("Training Loss and Accuracy on the IDC Dataset")
plt.xlabel("Epoch No.")
plt.ylabel("Loss/Accuracy")
plt.legend(loc="lower left")
plt.savefig('plot.png')

错误:

>WARNING:tensorflow:From /Users/ahwarkhan/Desktop/breast-cancer-classification/breast-cancer-classification/datasets/original/breast-cancer-classification/train_model.py:75: Model.fit_generator (from tensorflow.python.keras.engine.training) is deprecated and will be removed in a future version.
Instructions for updating:
Please use Model.fit, which supports generators.
Traceback (most recent call last):
  >>File "/Users/ahwarkhan/Desktop/breast-cancer-classification/breast-cancer-classification/datasets/original/breast-cancer-classification/train_model.py", line 75, in <module>
    epochs=NUM_EPOCHS)
  >>File "/Users/ahwarkhan/opt/miniconda3/lib/python3.7/site-packages/tensorflow/python/util/deprecation.py", line 324, in new_func
    return func(*args, **kwargs)
  >>File "/Users/ahwarkhan/opt/miniconda3/lib/python3.7/site-packages/tensorflow/python/keras/engine/training.py", line 1829, in fit_generator
    initial_epoch=initial_epoch)
  >>File "/Users/ahwarkhan/opt/miniconda3/lib/python3.7/site-packages/tensorflow/python/keras/engine/training.py", line 108, in _method_wrapper
    return method(self, *args, **kwargs)
  >>File "/Users/ahwarkhan/opt/miniconda3/lib/python3.7/site-packages/tensorflow/python/keras/engine/training.py", line 1063, in fit
    steps_per_execution=self._steps_per_execution)
  >>File "/Users/ahwarkhan/opt/miniconda3/lib/python3.7/site-packages/tensorflow/python/keras/engine/data_adapter.py", line 1122, in __init__
    dataset = dataset.map(_make_class_weight_map_fn(class_weight))
 >> File "/Users/ahwarkhan/opt/miniconda3/lib/python3.7/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: 'numpy.bool_' object has no attribute 'keys'

【问题讨论】:

  • 请尽量简化/缩短代码。这将帮助我们更快地找到答案。

标签: python numpy tensorflow keras deep-learning


【解决方案1】:

问题在于您致电model.fit

M=model.fit_generator(
    trainGen,
    steps_per_epoch=lenTrain//BS,
    validation_data=valGen,
    validation_steps=lenVal//BS,
    class_weight=classWeight.all(),  # problem here
    epochs=NUM_EPOCHS)

class_weight 关键字参数需要字典 (source):

class_weight:可选字典将类索引(整数)映射到权重(浮点)值,用于加权损失函数(仅在训练期间)。这对于告诉模型“更加关注”来自代表性不足的类的样本很有用。

classWeight 变量是一个 numpy 数组。但是,您传入classWeight.all(),它返回一个布尔值。这是你错误的根源。您需要将其更改为类 ID 与其权重之间的映射。

它可能看起来像这样:

class_weight = {0: 0.25, 1: 0.5, 2: 0.25}

【讨论】:

    猜你喜欢
    • 2022-07-08
    • 1970-01-01
    • 1970-01-01
    • 2015-04-22
    • 2021-07-21
    • 2019-12-17
    • 2018-09-07
    • 2021-10-10
    • 2012-12-01
    相关资源
    最近更新 更多