python - keras 不兼容的数据形状
问题描述
我正在为我的第一个 tensorflow 代码而苦苦挣扎。我正在尝试定义哪个图片是苹果或梨,但输出给了我错误。请帮我 !每次运行代码时我都会得到相同的结果有什么问题?
x_train, x_test, y_train, y_test = \
train_test_split(x, y)
xy = (x_train, x_test, y_train, y_test)
np.save('C:train.npy',xy)
x_train, x_test, y_train, y_test = np.load('train.npy',allow_pickle=True)
x_train = x_train.astype('float') / 256
x_test = x_test.astype('float') /256
model = Sequential()
model.add(Conv2D(32, (3, 3), input_shape=x_train.shape[1:], padding='same'))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Conv2D(64, (3, 3), padding='same'))
model.add(Activation('relu'))
model.add(Conv2D(64, (3, 3)))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
# 전결합층
model.add(Flatten()) # 벡터형태로 reshape
model.add(Dense(512)) # 출력
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(1))
model.add(Activation('sigmoid'))
# 모델 구축하기
model.compile(loss = 'binary_crossentropy', optimizer = 'adam', metrics = ['accuracy'])
hdf5_file = "7obj-model.hdf5"
if os.path.exists(hdf5_file):
model.load_weights(hdf5_file)
else:
model.fit(x_train, y_train, batch_size=32, nb_epoch=10)
model.save_weights(hdf5_file)
score = model.evaluate(x_test, y_test)
print('loss = ', score[0])
print('accuracy = ', score[1])
img_list = ['apple.jpg', 'apple.jpg', 'pear.jpg', 'pear1.jpg', 'pear2.jpg', 'pear3.jpg', 'pear4.jpg'] # test pictures
for test_image in img_list:
img = Image.open(test_image)
img = img.convert("RGB")
img = img.resize((64,64))
data = np.asarray(img)
X = np.array(data)
X = X.astype("float") / 256
X = X.reshape(-1, 64, 64,3)
# 예측
pred = model.predict(X)
result = [np.argmax(value) for value in pred]
print('New data category : ',categories[result[0]]) # return prediction
输出,我发布了它,也许是错误行 85:
File "C:/Users/심현규/PycharmProjects/yoyeo2012/main.py", line 85, in <module>
model.load_weights(hdf5_file
raise ValueError("Shapes %s and %s are incompatible" % (self, other))
ValueError: Shapes (512, 1) and (512, 2) are incompatible
解决方案
推荐阅读
- javascript - 如何在 Javascript 上隐藏 API 密钥?
- r - 使用 geom_point 具有不同颜色的 stat_smooth
- r - 将列名作为列中的值返回
- typescript - 从命令行重新组织大型 TypeScript 项目
- database - 不同的主键可以指向完全相同的记录吗?
- mongodb - MongoDB - 将对象转换为数组
- asp.net-identity - 如何使用 dotnet-ef 创建用于 ASP.NET Core 的 Postgres 身份数据库?
- python - Spark:如何从数据框行转换具有多个键的 JSON 字符串?
- javascript - 键入'字符串 | undefined' 不可分配给类型 'string'
- javascript - Angular removing elements from a list shared with a service