简体   繁体   English

ValueError:检查目标时出错:预期激活具有形状 (1,) 但得到形状为 (2,) 的数组

[英]ValueError: Error when checking target: expected activation to have shape (1,) but got array with shape (2,)

I am trying to create a deep neural network with keras in python, but I am getting the following error:我正在尝试使用 python 中的 keras 创建一个深度神经网络,但出现以下错误:

ValueError: Error when checking target: expected activation to have shape (1,) but got array with shape (2,) ValueError:检查目标时出错:预期激活具有形状 (1,) 但得到形状为 (2,) 的数组

My code is as follows:我的代码如下:

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Convolution2D
from tensorflow.keras.layers import MaxPooling2D
from tensorflow.keras.layers import Flatten
from tensorflow.keras.layers import Dense, Activation, Dropout
from sklearn.model_selection import train_test_split
from tensorflow.keras.preprocessing.image import img_to_array
from tensorflow.keras.utils import to_categorical
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import cv2
import random

df = pd.read_csv(r'UTKFace\data.csv', low_memory=False, header=None)
df = df.values

labels = [];
data = [];
random.seed(42)
random.shuffle(df);

for i in range(0,df.shape[0]):
    # load the image, pre-process it, and store it in the data list
    image = cv2.imread("UTKFace/" + df[i][0])
    image = img_to_array(image)
    data.append(image)

    # extract the class label from the image path and update the
    # labels list
    labels.append(df[i][1])

data = np.array(data, dtype="float") / 255.0
labels = np.array(labels)

(trainX, testX, trainY, testY) = train_test_split(data, labels, test_size=0.3, random_state=42)

trainY = to_categorical(trainY, 2)
testY = to_categorical(testY, 2)

print(trainX.shape)
print(trainY.shape)

print('done')

model = Sequential()
model.add(Convolution2D(32, (3,3), input_shape = (100,100,3), activation = 'relu'))
model.add(MaxPooling2D(pool_size = (2,2), strides=(2,2)))
model.add(Convolution2D(64, (1,1), activation = 'relu'))
model.add(MaxPooling2D(pool_size = (2,2), strides=(2,2)))
model.add(Convolution2D(128, (1,1), activation = 'relu'))
model.add(MaxPooling2D(pool_size = (2,2), strides=(2,2)))
model.add(Convolution2D(256, (1,1), activation = 'relu'))
model.add(MaxPooling2D(pool_size = (2,2), strides=(2,2)))
model.add(Flatten())
model.add(Dense(256, activation = 'relu'))
model.add(Dense(256, activation = 'relu'))
model.add(Dropout(0.5));
model.add(Dense(1, activation = 'relu'))
model.add(Activation('softmax'))
model.summary()
model.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])

#train the network
print("[INFO] training network...")
hist = model.fit(trainX, trainY, batch_size=256, epochs=10, validation_split=0.3)

Can anybody tell me what am I doing wrong?谁能告诉我我做错了什么? My model architecture is as follows:我的模型架构如下:

> Layer (type)                 Output Shape              Param #
=================================================================
conv2d (Conv2D)              (None, 98, 98, 32)        896
_________________________________________________________________
max_pooling2d (MaxPooling2D) (None, 49, 49, 32)        0
_________________________________________________________________
conv2d_1 (Conv2D)            (None, 49, 49, 64)        2112
_________________________________________________________________
max_pooling2d_1 (MaxPooling2 (None, 24, 24, 64)        0
_________________________________________________________________
conv2d_2 (Conv2D)            (None, 24, 24, 128)       8320
_________________________________________________________________
max_pooling2d_2 (MaxPooling2 (None, 12, 12, 128)       0
_________________________________________________________________
conv2d_3 (Conv2D)            (None, 12, 12, 256)       33024
_________________________________________________________________
max_pooling2d_3 (MaxPooling2 (None, 6, 6, 256)         0
_________________________________________________________________
flatten (Flatten)            (None, 9216)              0
_________________________________________________________________
dense (Dense)                (None, 256)               2359552
_________________________________________________________________
dense_1 (Dense)              (None, 256)               65792
_________________________________________________________________
dropout (Dropout)            (None, 256)               0
_________________________________________________________________
dense_2 (Dense)              (None, 1)                 257
_________________________________________________________________
activation (Activation)      (None, 1)                 0
=================================================================
Total params: 2,469,953
Trainable params: 2,469,953
Non-trainable params: 0
_________________________________________________________________

Change your activation function and neuron number in the output layer:更改输出层中的激活函数和神经元数:

model.add(Dense(2, activation = 'sigmoid'))

And remove this, because it's now redundant:并删除它,因为它现在是多余的:

model.add(Activation('softmax'))

If that doesn't work change your loss to categorical_crossentropy , I'm not sure if binary_crossentropy expects 1D or 2D output.如果这不起作用,请将您的损失更改为categorical_crossentropy ,我不确定binary_crossentropy需要 1D 或 2D 输出。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Keras - “ValueError:检查目标时出错:预期activation_1具有形状(无,9)但得到的数组具有形状(9,1) - Keras - "ValueError: Error when checking target: expected activation_1 to have shape (None, 9) but got array with shape (9,1) ValueError:检查目标时出错:预期activation_5 的形状为(1,),但数组的形状为(100,) - ValueError: Error when checking target: expected activation_5 to have shape (1,) but got array with shape (100,) ValueError:检查目标时出错:预期 activation_9 具有形状 (74, 6) 但得到形状为 (75, 6) 的数组 - ValueError: Error when checking target: expected activation_9 to have shape (74, 6) but got array with shape (75, 6) ValueError:检查目标时出错:预期activation_1的形状为(158,),但数组的形状为(121,) - ValueError: Error when checking target: expected activation_1 to have shape (158,) but got array with shape (121,) ValueError:检查目标时出错:预期 activation_6 具有形状(70,)但得到形状为(71,)的数组 - ValueError: Error when checking target: expected activation_6 to have shape (70,) but got array with shape (71,) ValueError:检查目标时出错:预期 activation_10 有 2 个维度,但得到了形状为 (118, 50, 1) 的数组 - ValueError: Error when checking target: expected activation_10 to have 2 dimensions, but got array with shape (118, 50, 1) ValueError:检查目标时出错:预期activation_7具有形状(154,154,1),但形状为(200,200,3)的数组 - ValueError: Error when checking target: expected activation_7 to have shape (154, 154, 1) but got array with shape (200, 200, 3) keras:ValueError:检查模型目标时出错:预期activation_1具有形状(无,60),但数组的形状为(10,100) - keras: ValueError: Error when checking model target: expected activation_1 to have shape (None, 60) but got array with shape (10, 100) ValueError:检查模型目标时出错:预期activation_2具有形状(无,761,1)但是具有形状的数组(1,779,1) - ValueError: Error when checking model target: expected activation_2 to have shape (None, 761, 1) but got array with shape (1, 779, 1) Keras-检查目标时出错:预期activation_5具有形状(2,),但数组的形状为(1,) - Keras - Error when checking target: expected activation_5 to have shape (2,) but got array with shape (1,)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM