ValueError:检查目标时出错:预期输出的形状为(1,),但数组的形状为(2,)

时间:2019-01-02 08:59:32

标签: python-2.7 tensorflow keras google-colaboratory

我正在尝试在google colab tpu上创建人脸检测模型。 基本上,它是VGG16的副本。具有相同的图层,但第一个和最后三个除外。 它可以在colab上的Python 2笔记本上运行。

我看到了其他问题,它们在数组中的成员数量都超过了所需的成员,并且有解决方案。 其他人无法回答。

使用模型的训练代码运行单元格时会引发错误。

#img_data contains images converted to array and pre-processed 
img_data = np.array(img_data_list)
img_data=np.rollaxis(img_data,1,0)
img_data =img_data[0]

#outputs
(2000, 1, 224, 224, 3)
(1, 2000, 224, 224, 3)
(1, 2000, 224, 224, 3)

num_classes = 2
num_of_samples = img_data.shape[0]
labels = np.ones((num_of_samples,),dtype='int64')
labels[0:1000]=0
labels[1000:]=1
names = ['happy' , 'not happy']

Y = np_utils.to_categorical(labels, num_classes)

x,y = shuffle(img_data,Y, random_state=2)

x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=2)

model = tf.keras.models.Sequential()
model.add(tf.keras.layers.BatchNormalization(input_shape=(224,224,3)))
model.add(tf.keras.layers.Conv2D(64, (5, 5), padding='same', activation='relu'))
model.add(tf.keras.layers.Conv2D(64, (5, 5), padding='same', activation='relu'))
model.add(tf.keras.layers.MaxPooling2D())

model.add(tf.keras.layers.Conv2D(128, (5, 5), padding='same', activation='relu'))
model.add(tf.keras.layers.Conv2D(128, (5, 5), padding='same', activation='relu'))
model.add(tf.keras.layers.MaxPooling2D(pool_size=(2, 2), strides=(2,2)))

model.add(tf.keras.layers.Conv2D(256, (5, 5), padding='same', activation='relu'))
model.add(tf.keras.layers.Conv2D(256, (5, 5), padding='same', activation='relu'))
model.add(tf.keras.layers.Conv2D(256, (5, 5), padding='same', activation='relu'))
model.add(tf.keras.layers.MaxPooling2D(pool_size=(2, 2), strides=(2,2)))

model.add(tf.keras.layers.Conv2D(512, (5, 5), padding='same', activation='relu'))
model.add(tf.keras.layers.Conv2D(512, (5, 5), padding='same', activation='relu'))
model.add(tf.keras.layers.Conv2D(512, (5, 5), padding='same', activation='relu'))
model.add(tf.keras.layers.MaxPooling2D(pool_size=(2, 2), strides=(2,2)))

model.add(tf.keras.layers.Conv2D(512, (5, 5), padding='same', activation='relu'))
model.add(tf.keras.layers.Conv2D(512, (5, 5), padding='same', activation='relu'))
model.add(tf.keras.layers.Conv2D(512, (5, 5), padding='same', activation='relu'))
model.add(tf.keras.layers.MaxPooling2D(pool_size=(2, 2), strides=(2,2)))

model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(128, activation='relu', name='fc1'))
model.add(tf.keras.layers.Dense(128, activation='relu', name='fc2'))
model.add(tf.keras.layers.Dense(num_classes, activation='softmax', name='output'))
model.summary()

训练模型

import os
tpu_model = tf.contrib.tpu.keras_to_tpu_model(
    model,
    strategy=tf.contrib.tpu.TPUDistributionStrategy(
        tf.contrib.cluster_resolver.TPUClusterResolver(tpu='grpc://' + os.environ['COLAB_TPU_ADDR'])
    )
)
tpu_model.compile(
    optimizer=tf.train.AdamOptimizer(learning_rate=1e-3, ),
    loss=tf.keras.losses.sparse_categorical_crossentropy,
    metrics=['sparse_categorical_accuracy']
)

def train_gen(batch_size):
  while True:
    offset = np.random.randint(0, x_train.shape[0] - batch_size)
    yield x_train[offset:offset+batch_size], y_train[offset:offset + batch_size]


tpu_model.fit_generator(
    train_gen(1024),
    epochs=10,
    steps_per_epoch=100,
    verbose = 1,
    validation_data=(x_test, y_test),
)

预期结果:

具有每个标签概率的数组。

实际结果:

ValueErrorTraceback (most recent call last)
<ipython-input-37-bffa1e87ffe0> in <module>()
     24     steps_per_epoch=100,
     25     verbose = 1,
---> 26     validation_data=(x_test, y_test),
     27 )
ValueError: Error when checking target: expected output to have shape (1,) but got array with shape (2,)

2 个答案:

答案 0 :(得分:0)

我认为我使用了错误的损失函数和指标。 设置

之后
loss = tf.keras.losses.categorical_crossentropy, metrics=['accuracy']

我终于开始运行它。

答案 1 :(得分:0)

您的问题可能是应该处理onehot的y标签, 您使用的tf.keras.losses.categorical_crossentropy可以忽略此过程。