'NoneType' 对象不可订阅 - 数据生成器

'NoneType' object is not subscriptable - Data generator

我从其他两个列表中创建了一个列表,如下所示:

samples = list(map(lambda x, y: [x,y], image_path, labels8))
[['s01_l01/1_1.png', '7C2 4698'],
 ['s01_l01/2_1.png', '7C2 4698'],
 ['s01_l01/2_2.png', '7C2 4698'],
 ['s01_l01/2_3.png', '7C2 4698'],
 ['s01_l01/2_4.png', '7C2 4698']]

第一个条目是 image_path,第二个条目是标签。

我也创建了这个函数:

def shuffle_data(data):
  data=random.shuffle(data)
  return data

为了获得 data_generator,我修改了在 YouTube 视频 (https://www.youtube.com/watch?v=EkzB6PJIcCA&t=530s) 中找到的代码:

def data_generator(samples, batch_size=32, shuffle_data = True, resize=224):
  num_samples = len(samples)
  while True:
    samples = random.shuffle(samples)

    for offset in range(0, num_samples, batch_size):
      batch_samples = samples[offset: offset + batch_size]

      X_train = []
      y_train = []

      for batch_sample in batch_samples:
        img_name = batch_sample[0]
        label = batch_sample[1]
        img = cv2.imread(os.path.join(root_dir, img_name))

        #img, label = preprocessing(img, label, new_height=224, new_width=224, num_classes=37)
        img = preprocessing(img, new_height=224, new_width=224)
        label = my_onehot_encoded(label)

        X_train.append(img)
        y_train.append(label)

      X_train = np.array(X_train)
      y_train = np.array(y_train)

      yield X_train, y_train

当我现在尝试执行这段代码时:

train_datagen = data_generator(samples, batch_size=32)

x, y = next(train_datagen)
print('x_shape: ', x.shape)
print('labels shape: ', y.shape)
print('labels: ', y)

我收到以下错误代码:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-89-6adc7f4509cd> in <module>()
      1 train_datagen = data_generator(samples, batch_size=32)
      2 
----> 3 x, y = next(train_datagen)
      4 print('x_shape: ', x.shape)
      5 print('labels shape: ', y.shape)

<ipython-input-88-0f34e3e5c990> in data_generator(samples, batch_size, shuffle_data, resize)
      5 
      6     for offset in range(0, num_samples, batch_size):
----> 7       batch_samples = samples[offset: offset + batch_size]
      8 
      9       X_train = []

TypeError: 'NoneType' object is not subscriptable

我不明白错误在哪里...

random.shuffle 就位 returns None.

所以,写

random.shuffle(samples)

而不是

samples = random.shuffle(samples)

random.shuffle 是就地操作,因此您不应将其结果(即 None)分配给洗牌机。相反,保持原样:

while True:
    random.shuffle(samples) # <--here

    for offset in range(0, num_samples, batch_size):
        batch_samples = samples[offset: offset + batch_size]