填充必须是序列或集合。对于dicts,使用list(d)

2024-05-20 02:04:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图执行这个代码,我得到的错误如下,我得到的错误在随机函数,我不知道如何修复它,请帮助我。

def load_data(sample_split=0.3, usage='Training', to_cat=True, verbose=True,
          classes=['Angry','Happy'], filepath='C:/Users/Oussama/Desktop/fer2013.csv'):
    df = pd.read_csv(filepath)
    # print df.tail()
    # print df.Usage.value_counts()
    df = df[df.Usage == usage]
    frames = []
    classes.append('Disgust')
    for _class in classes:
        class_df = df[df['emotion'] == emotion[_class]]
        frames.append(class_df)
    data = pd.concat(frames, axis=0)
    rows = random.sample(data.index, int(len(data)*sample_split))
    data = data.ix[rows]
    print ('{} set for {}: {}'.format(usage, classes, data.shape))
    data['pixels'] = data.pixels.apply(lambda x: reconstruct(x))
    x = np.array([mat for mat in data.pixels]) # (n_samples, img_width, img_height)
    X_train = x.reshape(-1, 1, x.shape[1], x.shape[2])
    y_train, new_dict = emotion_count(data.emotion, classes, verbose)
    print (new_dict)
    if to_cat:
        y_train = to_categorical(y_train)
    return X_train, y_train, new_dict

我明白了:

Traceback (most recent call last):
   File "fer2013datagen.py", line 71, in <module>
   verbose=True)
   File "fer2013datagen.py", line 47, in load_data
   rows = random.sample(data, int(len(data)*sample_split))

   File"
   C:\Users\Oussama\AppData\Local\Programs\Python\Python35\lib\random.py",
   line 311, in sample
   raise TypeError("Population must be a sequence or set.  For dicts, use
   list(d).")
TypeError: Population must be a sequence or set.  For dicts, use list(d).

Tags: tosampleintruedfverbosedataframes
1条回答
网友
1楼 · 发布于 2024-05-20 02:04:29

你的代码在这里:

rows = random.sample(data.index, int(len(data)*sample_split))

但是,错误信息显示

rows = random.sample(data, int(len(data)*sample_split))

为什么不同?你修改了吗?数据的类型是什么? 是单子吗?还是听写?

而且,错误消息已经告诉您如何修复它。 这意味着随机的第一个参数。sample必须是一个序列或集合。对于Dict,使用list(Dict)。

例如

d = {'a':1,'b':2}
random.sample(list(d), 1)

而不是

random.sample(d, 1)

相关问题 更多 >