我有这段代码会产生错误,错误出在重构函数中。

def reconstruct(pix_str, size=(48,48)):
    pix_arr = np.array(map(int, pix_str.split()))
    return pix_arr.reshape(size)

这个函数加载数据
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(list(data.index), int(len(data)*sample_split))
    data = data.loc[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

这里保存数据
def save_data(X_train, y_train, fname='', folder='../data/'):
    np.save(folder + 'X_train' + fname, X_train)
    np.save(folder + 'y_train' + fname, y_train)

if __name__ == '__main__':
    # makes the numpy arrays ready to use:
    print ('Making moves...')
    emo = ['Angry', 'Fear', 'Happy',
       'Sad', 'Surprise', 'Neutral']
    X_train, y_train, emo_dict = load_data(sample_split=1.0,
                                       classes=emo,
                                       usage='PrivateTest',
                                       verbose=True)
    print ('Saving...')
    save_data(X_train, y_train, fname='_privatetest6_100pct')
    print (X_train.shape)
    print (y_train.shape)
    print ('Done!')

我收到此错误:
 ---> 20     return pix_arr.reshape(size)
      ValueError: cannot reshape array of size 1 into shape (48,48)

错误出在重构函数中。

我该如何解决这个问题?

最佳答案

您只需要将 map 的结果转为列表。

def reconstruct(pix_str, size=(2,4)):
    pix_arr = np.array(list(map(int, pix_str.split(','))))
    return pix_arr.reshape(size)

strlist = ['353,2607,367,2607,388,2620,416,2620',
           '283,2490,290,2490,297,2490,304,2490']
df = pd.DataFrame(strlist,columns=['data'])
df['data'] = df.data.apply(lambda x: reconstruct(x))
print(df)
                                               data
0  [[353, 2607, 367, 2607], [388, 2620, 416, 2620]]
1  [[283, 2490, 290, 2490], [297, 2490, 304, 2490]]

关于python - 无法将大小为 1 的数组重塑为形状 (48,48),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44578248/

10-11 23:55