简体   繁体   English

ValueError:logits 和标签必须具有相同的形状 ((32, 1) vs (32, 2))

[英]ValueError: logits and labels must have the same shape ((32, 1) vs (32, 2))

I have altered the code take from here for binary classification with 1 output neuron我已经用 1 output 神经元更改了从这里获取的代码以进行二进制分类

import os
from keras.models import Sequential
from sklearn.model_selection import train_test_split
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras import optimizers
from skimage import io
from skimage.transform import resize
from keras.utils import to_categorical
import numpy as np
import tensorflow as tf
import random
import glob

n_category_samples = 4000
batch_size = 32
num_classes = 2
epochs = 10

n_image_rows = 106
n_image_cols = 106
n_channels = 3


def train_selfie_model():
    random_seed = 1
    tf.random.set_seed(random_seed)
    np.random.seed(random_seed)

    x_train, y_train = prepare_train_set()

    x_train, x_test, y_train, y_test = train_test_split(x_train, y_train, test_size=0.30, random_state=42)

    mean = np.array([0.5, 0.5, 0.5])
    std = np.array([1, 1, 1])
    x_train = x_train.astype('float')
    x_test = x_test.astype('float')
    for i in range(3):
        x_train[:, :, :, i] = (x_train[:, :, :, i] - mean[i]) / std[i]
        x_test[:, :, :, i] = (x_test[:, :, :, i] - mean[i]) / std[i]

    y_train = to_categorical(y_train, num_classes)
    y_test = to_categorical(y_test, num_classes)

    model = compile_model()

    print(model.summary())

    print(y)
    model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, validation_data=(x_test, y_test))

    score = model.evaluate(x_test, y_test, verbose=0)

    print('Test loss: ', score[0])
    print('Test accuracy: ', score[1])

    model_path = os.getcwd() + "/models/saved/selfie-model/"
    model.save(model_path)


def prepare_train_set():
    positive_samples = glob.glob('datasets/drunk_resize_frontal_faces/pos/*')[0:n_category_samples]
    negative_samples = glob.glob('datasets/drunk_resize_frontal_faces/neg/*')[0:n_category_samples]
    negative_samples = random.sample(negative_samples, len(positive_samples))
    x_train = []
    y_train = []
    for i in range(len(positive_samples)):
        x_train.append(resize(io.imread(positive_samples[i]), (n_image_rows, n_image_cols)))
        y_train.append(1)
        if i % 1000 == 0:
            print('Reading positive image number ', i)
    for i in range(len(negative_samples)):
        x_train.append(resize(io.imread(negative_samples[i]), (n_image_rows, n_image_cols)))
        y_train.append(0)
        if i % 1000 == 0:
            print('Reading negative image number ', i)
    x_train = np.array(x_train)
    y_train = np.array(y_train)
    return x_train, y_train


def compile_model():
    model_input_shape = (n_image_rows, n_image_cols, n_channels)
    model = Sequential()
    model.add(
        Conv2D(8, kernel_size=(3, 3), activation='relu', strides=(1, 1), padding='same', input_shape=model_input_shape))
    model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2), padding='valid'))
    model.add(Dropout(0.25))
    model.add(Conv2D(16, kernel_size=(3, 3), padding='same', activation='relu'))
    model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2), padding='valid'))
    model.add(Dropout(0.25))
    model.add(Conv2D(16, kernel_size=(3, 3), padding='same', activation='relu'))
    model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2), padding='valid'))
    model.add(Conv2D(8, kernel_size=(3, 3), padding='same', activation='relu'))
    model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2), padding='valid'))
    model.add(Flatten())
    model.add(Dense(10, activation='relu'))
    # single output neuron
    model.add(Dense(1, activation='sigmoid'))
    sgd = optimizers.SGD(lr=.001, momentum=0.9, decay=0.000005, nesterov=False)
    model.compile(loss='binary_crossentropy', optimizer=sgd, metrics=['accuracy'])
    return model

But I am getting following error when running train_selfie_model()但是在运行train_selfie_model()时出现以下错误

ValueError: logits and labels must have the same shape ((32, 1) vs (32, 2))

at

model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, validation_data=(x_test, y_test))

I am new to TF and Keras.我是 TF 和 Keras 的新手。 Seems like this is an array dimension mismatch.似乎这是一个数组维度不匹配。 But how could I fix this?但我怎么能解决这个问题?

The problem is问题是

At

def train_selfie_model():
    ...
    y_train = to_categorical(y_train, num_classes)
    y_test = to_categorical(y_test, num_classes)
    ...

you set y_train and y_test to one-hot encoding (vectors of shape (2,). But at您将y_trainy_test设置为 one-hot 编码(形状为 (2,) 的向量。但在

def compile_model():
    ...
    model.add(Dense(1, activation='sigmoid'))
    ...

you have only one output neuron (output of shape (1,)).您只有一个 output 神经元(形状为 (1,) 的输出)。

So commenting out / removing following lines will fix your problem.因此,注释掉/删除以下行将解决您的问题。

y_train = to_categorical(y_train, num_classes)
y_test = to_categorical(y_test, num_classes)

To make a (32, 1) array appear as a (32, 2) , you can construct a view:要使(32, 1)数组显示为(32, 2) ,您可以构造一个视图:

arr = np.lib.stride_tricks.as_strided(arr, shape=(arr.shape[0], 2), strides=(arr.strides[0], 0))

You could take an even more manual approach:您可以采取更加手动的方法:

arr = np.ndarray(shape=(arr.shape[0], 2), strides=(arr.strides[0], 0), dtype=arr.dtype, buffer=arr)

Both well view the same memory twice, so you should normally treat them as read-only.两者都可以两次查看相同的 memory,因此您通常应该将它们视为只读。 To copy the data, use any of the following:要复制数据,请使用以下任一方法:

arr = np.concatenate((arr,) * 2, axis=-1)
arr = np.repeat(arr, 2, axis=-1)
arr = np.tile(arr, [1, 2])

暂无
暂无

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

相关问题 Keras ValueError:logits 和标签必须具有相同的形状((无,32,17)与(无,17)) - Keras ValueError: logits and labels must have the same shape ((None, 32, 17) vs (None, 17)) ValueError:logits 和标签必须具有相同的形状 ((None, 5) vs (None, 1)) - ValueError: logits and labels must have the same shape ((None, 5) vs (None, 1)) ValueError:logits 和标签必须具有相同的形状 ((1, 21) vs (21, 1)) - ValueError: logits and labels must have the same shape ((1, 21) vs (21, 1)) ValueError:logits 和标签必须具有相同的形状 ((1, 7, 7, 2) vs (1, 2)) - ValueError: logits and labels must have the same shape ((1, 7, 7, 2) vs (1, 2)) ValueError:logits 和标签必须具有相同的形状 ((None, 6, 8, 1) vs (None, 1)) - ValueError: logits and labels must have the same shape ((None, 6, 8, 1) vs (None, 1)) ValueError:logits 和标签必须具有相同的形状 ((None, 1) vs (None, 2)) - ValueError: logits and labels must have the same shape ((None, 1) vs (None, 2)) ValueError:logits 和标签必须具有相同的形状 ((None, 2) vs (None, 1)) - ValueError: logits and labels must have the same shape ((None, 2) vs (None, 1)) Tensorflow 估计器 ValueError:logits 和标签必须具有相同的形状 ((?, 1) vs (?,)) - Tensorflow estimator ValueError: logits and labels must have the same shape ((?, 1) vs (?,)) ValueError:logits 和标签必须具有相同的形状 ((None, 4) vs (None, 1)) - ValueError: logits and labels must have the same shape ((None, 4) vs (None, 1)) logits 和 labels 必须具有相同的第一维,得到 logits 形状 [2048,10] 和标签形状 [32] - logits and labels must have the same first dimension, got logits shape [2048,10] and labels shape [32]
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM