Input 0 of layer "dense" is incompatible with the layer: expected axis -1 of input shape to have value 6, but received input with shape (None, 2)
Я создаю нейронную сеть с двумя входным нейронам (погода и температура) и с четырьмя выходными нейронами (головной убор, верхняя одежда, штаны, обувь). Пока я создал код до ее обучения. Вот ее код:
import tensorflow as tf
import numpy as np
import pandas as pd
from tensorflow.keras.preprocessing.text import Tokenizer
data = pd.read_csv('weather.txt')
data.dropna(inplace=True)
f = open("weather.txt")
ls = f.read().split("\n")
mas = []
m_g = []
m_w = []
m_t = []
m_h = []
m_o = []
m_p = []
m_s = []
for l in ls:
l = l.split(",")
m_g.append(l[0].lower())
m_w.append(l[1].lower())
m_t.append([int(l[2])])
m_h.append(l[3].lower())
m_o.append(l[4].lower())
m_p.append(l[5].lower())
m_s.append(l[6].lower())
tokenizer = Tokenizer()
tokenizer.fit_on_texts(m_w)
tokenizer.fit_on_texts(m_h)
tokenizer.fit_on_texts(m_o)
tokenizer.fit_on_texts(m_p)
tokenizer.fit_on_texts(m_s)
m_w = np.array(tokenizer.texts_to_sequences(m_w))
m_t = np.array(m_t)
m_h = np.array(tokenizer.texts_to_sequences(m_h))
m_o = np.array(tokenizer.texts_to_sequences(m_o))
m_p = np.array(tokenizer.texts_to_sequences(m_p))
m_s = np.array(tokenizer.texts_to_sequences(m_s))
input1 = tf.keras.Input(shape=(len(np.unique(m_w)),))
input2 = tf.keras.Input(shape=(1,))
conc = tf.keras.layers.concatenate([input1,input2])
x = tf.keras.layers.Dense(64, activation='relu')(conc)
x = tf.keras.layers.Dropout(0.2)(x)
x = tf.keras.layers.Dense(32, activation='relu')(x)
x = tf.keras.layers.Dropout(0.2)(x)
o_h = tf.keras.layers.Dense(len(np.unique(m_h)), activation='softmax', name='hat')(x)
o_o = tf.keras.layers.Dense(len(np.unique(m_o)), activation='softmax', name='outerwear')(x)
o_p = tf.keras.layers.Dense(len(np.unique(m_p)), activation='softmax', name='pants')(x)
o_s = tf.keras.layers.Dense(len(np.unique(m_s)), activation='softmax', name='shoes')(x)
model = tf.keras.Model(inputs=[input1,input2],outputs = [o_h,o_o,o_p,o_s])
model.compile(optimizer="adam",
loss={'hat': 'categorical_crossentropy',
'outerwear': 'categorical_crossentropy',
'pants': 'categorical_crossentropy',
'shoes': 'categorical_crossentropy'},
metrics=['accuracy'])
model.fit([m_w,m_t],
{
"hat":m_h,
"outerwear":m_o,
"pants":m_p,
"shoes":m_s
},epochs=100)
Когда я запускаю код вылезает ошибка:
Traceback (most recent call last):
File "/home/user/PycharmProjects/ai_projects/weather_ai/v1/v1.py", line 61, in <module>
model.fit([m_w,m_t],
File "/home/user/PycharmProjects/ai_projects/.venv/lib/python3.12/site-packages/keras/src/utils/traceback_utils.py", line 122, in error_handler
raise e.with_traceback(filtered_tb) from None
File "/home/user/PycharmProjects/ai_projects/.venv/lib/python3.12/site-packages/keras/src/layers/input_spec.py", line 227, in assert_input_compatibility
raise ValueError(
ValueError: Exception encountered when calling Functional.call().
Input 0 of layer "dense" is incompatible with the layer: expected axis -1 of input shape to have value 5, but received input with shape (None, 2)
Arguments received by Functional.call():
• inputs=('tf.Tensor(shape=(None, 1), dtype=int64)', 'tf.Tensor(shape=(None, 1), dtype=int64)')
• training=True
• mask=('None', 'None')
• kwargs=<class 'inspect._empty'>
Как я понял тут связано с форматом входом данных. Направьте меня, пожалуйста, на путь к решению этой проблемы. Если нужна дополнительная информация, допишу. Заранее благодарю.