Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

python - Error when checking target: expected dense_3 to have shape (2,) but got array with shape (1,)

I'm training a textual sentiment classification model with multiple output layers in Keras's Functional API(using a TensorFlow backend). The model takes as input a Numpy array of hashed values produced by the Keras Preprocessing API's hashing_trick() function, and uses a list of Numpy arrays of binary one-hot labels as its targets, as per Keras specifications for training a model with multiple outputs(see fit()'s documentation here: https://keras.io/models/model/).

Here's the model, sans most of the preprocessing steps:

    textual_features = hashing_utility(filtered_words) # Numpy array of hashed values(training data)

    label_list = [] # Will eventually contain a list of Numpy arrays of binary one-hot labels 

    for index in range(one_hot_labels.shape[0]):
        label_list.append(one_hot_labels[index])

     weighted_loss_value = (1/(len(filtered_words))) # Equal weight on each of the output layers' losses

     weighted_loss_values = []

     for index in range (one_hot_labels.shape[0]):
        weighted_loss_values.append(weighted_loss_value)


     text_input = Input(shape = (1,))


     intermediate_layer = Dense(64, activation = 'relu')(text_input)


     hidden_bottleneck_layer = Dense(32, activation = 'relu')(intermediate_layer)

     keras.regularizers.l2(0.1)

     output_layers = []

     for index in range(len(filtered_words)):
        output_layers.append(Dense(2, activation = 'sigmoid')(hidden_bottleneck_layer))

     model = Model(inputs = text_input, outputs = output_layers)            
     model.compile(optimizer = 'RMSprop', loss = 'binary_crossentropy', metrics = ['accuracy'], loss_weights = weighted_loss_values)                          

     model.fit(textual_features, label_list, epochs = 50)

Here's the gist of the error trace training this model produces:

ValueError: Error when checking target: expected dense_3 to have shape (2,) but got array with shape (1,)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your numpy arrays (both for inputs and outputs) should contain a batch dimension. If your labels are currently of shape (2,), you can reshape them to include a batch dimension as follows:

label_array = label_array.reshape(1, -1)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...