Keras Model提供TypeError:只能将size-1数组转换为Python标量

时间:2019-04-21 07:42:12

标签: python-3.x machine-learning keras

我正在训练一个模型来制作图像蒙版。此错误不断弹出,我无法确定原因。帮助将不胜感激。

错误声明:

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")

1 个答案:

答案 0 :(得分:1)

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

更改

的最后一层
as

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

此外,在较新版本的Keras中,建议使用model.add(Dense(Y_train.shape[0], activation='sigmoid')) 层而不是旧的Conv2D