簡體   English   中英

ValueError:logits 和標簽必須具有相同的形狀 ((32, 1) vs (32, 2))

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

我已經用 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

但是在運行train_selfie_model()時出現以下錯誤

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

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

我是 TF 和 Keras 的新手。 似乎這是一個數組維度不匹配。 但我怎么能解決這個問題?

問題是

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

您將y_trainy_test設置為 one-hot 編碼(形狀為 (2,) 的向量。但在

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

您只有一個 output 神經元(形狀為 (1,) 的輸出)。

因此,注釋掉/刪除以下行將解決您的問題。

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

要使(32, 1)數組顯示為(32, 2) ,您可以構造一個視圖:

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

您可以采取更加手動的方法:

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

兩者都可以兩次查看相同的 memory,因此您通常應該將它們視為只讀。 要復制數據,請使用以下任一方法:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM