2017-06-15 71 views
1

我有這段代碼會產生一個錯誤,錯誤發生在reconstruct函數中。無法將大小爲1的數組重新整形(48,48)

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) 

錯誤是在重構功能。

我該如何解決這個問題?

+0

如果這是Python 3,'map'不會再返回一個列表。 – user2357112

+0

是的我正在使用python 3.5,你能幫我嗎我是一個初學Python的人。 – Oussama

回答

1

您只需將地圖結果轉換爲列表。

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]] 
相關問題