我有这个代码产生错误,错误在重构函数中。
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 :(得分: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]]