ValueError: Shapes (None, 120) and (None, 4) are incompatible

Рейтинг: 0Ответов: 0Опубликовано: 20.02.2023

Собственно вылазить ошибка при попытке обучить

Ошибка

2023-02-20 19:05:46.588368: I

tensorflow/core/platform/cpu_feature_guard.cc:193] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations:  AVX AVX2
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
Epoch 1/7
Traceback (most recent call last):
  File "C:\Program Files\JetBrains\PyCharm 2022.3.1\plugins\python\helpers\pydev\pydevconsole.py", line 364, in runcode
    coro = func()
  File "<input>", line 1, in <module>
  File "C:\Program Files\JetBrains\PyCharm 2022.3.1\plugins\python\helpers\pydev\_pydev_bundle\pydev_umd.py", line 198, in runfile
    pydev_imports.execfile(filename, global_vars, local_vars)  # execute the script
  File "C:\Program Files\JetBrains\PyCharm 2022.3.1\plugins\python\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "C:\game\ahk\bd\rb\ovc\obuch.py", line 74, in <module>
    history = model.fit(my_x_train_np, my_y_train_cat, validation_data=(my_x_train_np, my_y_train_cat), epochs=7)
  File "C:\Users\Al\PycharmProjects\venv\lib\site-packages\keras\utils\traceback_utils.py", line 70, in error_handler
    raise e.with_traceback(filtered_tb) from None
  File "C:\Users\Al\AppData\Local\Temp\__autograph_generated_fileuecjrwki.py", line 15, in tf__train_function
    retval_ = ag__.converted_call(ag__.ld(step_function), (ag__.ld(self), ag__.ld(iterator)), None, fscope)
ValueError: in user code:
    File "C:\Users\Al\PycharmProjects\venv\lib\site-packages\keras\engine\training.py", line 1249, in train_function  *
        return step_function(self, iterator)
    File "C:\Users\Al\PycharmProjects\venv\lib\site-packages\keras\engine\training.py", line 1233, in step_function  **
        outputs = model.distribute_strategy.run(run_step, args=(data,))
    File "C:\Users\Al\PycharmProjects\venv\lib\site-packages\keras\engine\training.py", line 1222, in run_step  **
        outputs = model.train_step(data)
    File "C:\Users\Al\PycharmProjects\venv\lib\site-packages\keras\engine\training.py", line 1024, in train_step
        loss = self.compute_loss(x, y, y_pred, sample_weight)
    File "C:\Users\Al\PycharmProjects\venv\lib\site-packages\keras\engine\training.py", line 1082, in compute_loss
        return self.compiled_loss(
    File "C:\Users\Al\PycharmProjects\venv\lib\site-packages\keras\engine\compile_utils.py", line 265, in __call__
        loss_value = loss_obj(y_t, y_p, sample_weight=sw)
    File "C:\Users\Al\PycharmProjects\venv\lib\site-packages\keras\losses.py", line 152, in __call__
        losses = call_fn(y_true, y_pred)
    File "C:\Users\Al\PycharmProjects\venv\lib\site-packages\keras\losses.py", line 284, in call  **
        return ag_fn(y_true, y_pred, **self._fn_kwargs)
    File "C:\Users\Al\PycharmProjects\venv\lib\site-packages\keras\losses.py", line 2004, in categorical_crossentropy
        return backend.categorical_crossentropy(
    File "C:\Users\Al\PycharmProjects\venv\lib\site-packages\keras\backend.py", line 5532, in categorical_crossentropy
        target.shape.assert_is_compatible_with(output.shape)
    ValueError: Shapes (None, 120) and (None, 40) are incompatible

my_x_train_np.shape (400, 28, 28, 1) my_y_train_cat.shape (400, 120)

в чем заключается ошибка?

В файле words.py содержится следующее

words = {
    'a': ['a', 97],
    'd': ['d', 100],
    's': ['s', 115],
    'w': ['w', 119]
} 

Основной код

from tensorflow import keras
from keras.models import Sequential
from keras import optimizers
from keras.layers import Convolution2D, MaxPooling2D, Dropout, Flatten, Dense, Reshape, LSTM, BatchNormalization
from keras.optimizers import SGD, RMSprop, Adam
from keras import backend as K
from keras.constraints import maxnorm
import tensorflow as tf
import cv2
import app.neuronet.words as w
import numpy as np
from keras.utils import to_categorical

emnist_labels = [97, 100, 115, 119]

def emnist_model():
    model = Sequential()
    model.add(Convolution2D(filters=32, kernel_size=(3, 3), padding='valid', input_shape=(28, 28, 1), activation='relu'))
    model.add(Convolution2D(filters=64, kernel_size=(3, 3), activation='relu'))
    model.add(MaxPooling2D(pool_size=(2, 2)))
    model.add(Dropout(0.25))
    model.add(Flatten())
    model.add(Dense(512, activation='relu'))
    model.add(Dropout(0.5))
    model.add(Dense(len(emnist_labels), activation='softmax'))
    model.compile(loss='categorical_crossentropy', optimizer='adadelta', metrics=['accuracy'])
    return model


path = "C:\\ovc\\words\\"

words = w.words.items()
print(words)

images = []
my_x_train = []
my_y_train = []
for word in words:
    print(word)
    file_name = path + word[0] + '.png'
    print(file_name)
    img = cv2.imread(file_name)
    matrix = np.array(img)

    z = 0
    while z < 100:
        new_img = []
        for i in matrix:
            for j in i:
                data = round(1 - j[0] / 255, 1)
                new_img.append(data)

        n_arr = np.array(new_img)

        x_train_r = np.reshape(n_arr, (28, 28))

        my_x_train.append(x_train_r)
        my_y_train.append(word[1][1])
        images.append([word[0], word[1], new_img])
        z += 1

my_y_train_cat = to_categorical(my_y_train)
my_x_train_np = np.array(my_x_train)
my_x_train_np = my_x_train_np.reshape(my_x_train_np.__len__(), 28, 28, 1)

model = emnist_model()

print(my_x_train[1])
print(my_y_train_cat[1])


history = model.fit(my_x_train_np, my_y_train_cat, validation_data=(my_x_train_np, my_y_train_cat), epochs=7)

model.save('emnist_letters.h5')

Ответы

Ответов пока нет.