【问题标题】:Population must be a sequence or set. For dicts, use list(d)人口必须是一个序列或集合。对于 dicts,使用 list(d)
【发布时间】:2017-11-06 10:06:26
【问题描述】:

我尝试执行此代码并收到以下错误,我在随机函数中收到错误并且我不知道如何解决它,请帮助我。

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).

【问题讨论】:

  • df 是dataframe 的缩写是什么? random.sample() 需要它的第一个参数是一个序列,因此您需要将 data 转换为一个序列(或集合)才能正确传递它。
  • 你试过rows = random.sample(list(data.index), ...)吗?
  • df 是 DataFrame 函数 read_csv 返回 DataFrame
  • 如果您正在与pandas 打交道,因为@martineau 有点意思(名称df 和pd.concat 似乎是这种情况) - 为什么不使用.sample() 方法它提供而不是内置的random.sample,例如:pandas.pydata.org/pandas-docs/stable/generated/…
  • rows = random.sample(list(data.index), ...) 成功了

标签: python


【解决方案1】:

你的代码在这里:

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

但是,错误信息显示

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

为什么不一样?你修改了吗? 数据的类型是什么? 是清单吗?还是字典?

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

例如,

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

而不是

random.sample(d, 1)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-16
    • 2023-01-23
    • 2023-01-16
    • 2018-07-12
    • 2017-12-27
    相关资源
    最近更新 更多