gpt4 book ai didi

python-3.x - Keras 模型给出 TypeError : only size-1 arrays can be converted to Python scalars

转载 作者:行者123 更新时间:2023-11-30 09:43:30 27 4
gpt4 key购买 nike

我正在训练一个模型来生成图像蒙版。这个错误不断出现,我无法确定原因。如有帮助,将不胜感激。

错误说明:

File "--\Users\-----\Anaconda3\lib\site-packages\keras\initializers.py", line 209, in __call__
scale /= max(1., float(fan_in + fan_out) / 2)
TypeError: only size-1 arrays can be converted to Python scalars

网上查了一下,当普通列表与numpy函数一起使用时会出现此错误,但在我的例子中,使用的数组是numpy数组。下面,我附上了代码。

import cv2
import glob
import numpy as np
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Convolution2D, MaxPooling2D
from keras.utils import np_utils
from keras.datasets import mnist
from keras import backend as K
K.set_image_dim_ordering('tf')
np.random.seed(123) # for reproducibility

image_list = []
test_list = []

for filename in glob.glob("image/*.jpg*"):
im = cv2.imread(filename)
im_r = cv2.resize(im,(200, 200), interpolation = cv2.INTER_AREA)
image_list.append(im_r)

for filename in glob.glob("test/*.png*"):
im = cv2.imread(filename)
im_r = cv2.resize(im,(200, 200), interpolation = cv2.INTER_AREA)
im_r = np.ravel(im_r)
test_list.append(im_r)

x_data = np.array(image_list)
y_data = np.array(test_list)
x_data = x_data.astype("float32")
y_data = y_data.astype("float32")
x_data /= 255
y_data /= 255

X_train = x_data
Y_train = y_data

model = Sequential()
model.add(Convolution2D(32, 5, 5, activation='relu', input_shape=(200, 200, 3)))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Convolution2D(32, 5, 5, activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Convolution2D(32, 3, 3, activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(Y_train[0], activation='sigmoid'))
print('hello')

model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
loss = acc = 0
while acc < 0.9999:
model.fit(X_train, Y_train, batch_size=32, nb_epoch=10, verbose=1)
loss, acc = model.evaluate(X_train, Y_train, verbose=1)
model.save("model_state_no_mapping")

最佳答案

问题出在模型的最后一层。

更改最后一层

model.add(Dense(Y_train[0], activation='sigmoid')) 

model.add(Dense(Y_train.shape[0], activation='sigmoid'))

此外,在较新版本的 Keras 中,建议使用 Conv2D 层而不是旧的 Convolution2D

关于python-3.x - Keras 模型给出 TypeError : only size-1 arrays can be converted to Python scalars,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55780879/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com