人口必须是一个序列或集合。对于字典,使用 list(d)

Ous*_*ama 5 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
Run Code Online (Sandbox Code Playgroud)

我明白了:

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
Run Code Online (Sandbox Code Playgroud)

Jin*_*ing 7

你的代码在这里:

rows = random.sample(data.index, int(len(data)*sample_split))
Run Code Online (Sandbox Code Playgroud)

但是,错误消息显示

rows = random.sample(data, int(len(data)*sample_split))
Run Code Online (Sandbox Code Playgroud)

为什么不同?你修改了吗?以及数据的类型 是什么?它是一个列表吗?或字典?

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

例如,

d = {'a':1,'b':2}
random.sample(list(d), 1)
Run Code Online (Sandbox Code Playgroud)

代替

random.sample(d, 1)
Run Code Online (Sandbox Code Playgroud)