Tensorflow issue: logits and labels must have the same first dimension, got logits shape [3,21] and labels shape [15]

I got this error: logits and labels must have the same first dimension, got logits shape [3,21] and labels shape [15] when trying to train my chatbot I created using SimpleRNN layers that tensorflow provided. I’ve made sure that I used padding and proper tokenization to make inputs the same size, but I still got this error. My code is below.

import tensorflow as tf
import numpy as np
import json

# Step 1: Prepare the Data
questions = ["What is your name?", "How are you?", "What is the time?"]
answers = ["My name is ChatBot.", "I am fine, thank you.", "I do not have a watch."]

with open('q.txt', 'w') as q_file, open('a.txt', 'w') as a_file:
    for q, a in zip(questions, answers):
        q_file.write(q + 'n')
        a_file.write(a + 'n')

# Step 2: Preprocess the Data
with open('q.txt', 'r') as q_file:
    questions = q_file.readlines()
with open('a.txt', 'r') as a_file:
    answers = a_file.readlines()

tokenizer = tf.keras.preprocessing.text.Tokenizer()
tokenizer.fit_on_texts(questions + answers)

q_sequences = tokenizer.texts_to_sequences(questions)
a_sequences = tokenizer.texts_to_sequences(answers)

q_sequences = tf.keras.preprocessing.sequence.pad_sequences(q_sequences, padding='post')
a_sequences = tf.keras.preprocessing.sequence.pad_sequences(a_sequences, padding='post')

q_sequences = np.array(q_sequences)
a_sequences = np.array(a_sequences)

# Step 3: Build the Model
model = tf.keras.Sequential([
    tf.keras.layers.Embedding(input_dim=len(tokenizer.word_index) + 1, output_dim=64, input_length=q_sequences.shape[1]),
    tf.keras.layers.SimpleRNN(64, return_sequences=True),
    tf.keras.layers.SimpleRNN(64),
    tf.keras.layers.Dense(len(tokenizer.word_index) + 1, activation='softmax')
])

model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
model.summary()

# Step 4: Train the Model
# Adjust labels to match the model's output
# Since we are predicting the next token, slice answers accordingly
model.fit(q_sequences, a_sequences[:, 1:], epochs=10)

# Step 5: Save the Weights and Biases
model.save('chatbot_model.h5')

weights_and_biases = {}
for layer in model.layers:
    if isinstance(layer, tf.keras.layers.SimpleRNN) or isinstance(layer, tf.keras.layers.Dense):
        weights_and_biases[layer.name] = {
            'weights': layer.get_weights()[0].tolist(),
            'biases': layer.get_weights()[1].tolist()
        }

with open('weights_and_biases.json', 'w') as json_file:
    json.dump(weights_and_biases, json_file)

# Step 6: Custom Feedforward Function
def custom_feedforward(input_sequence, weights_and_biases):
    def relu(x):
        return np.maximum(0, x)

    def softmax(x):
        e_x = np.exp(x - np.max(x))
        return e_x / e_x.sum(axis=-1, keepdims=True)

    w_rnn1 = np.array(weights_and_biases['simple_rnn']['weights'])
    b_rnn1 = np.array(weights_and_biases['simple_rnn']['biases'])

    hidden_state = np.zeros((w_rnn1.shape[1],))
    for t in range(input_sequence.shape[0]):
        hidden_state = relu(np.dot(input_sequence[t], w_rnn1) + b_rnn1 + np.dot(hidden_state, w_rnn1.T))

    w_dense = np.array(weights_and_biases['dense']['weights'])
    b_dense = np.array(weights_and_biases['dense']['biases'])

    output = softmax(np.dot(hidden_state, w_dense) + b_dense)
    
    return output

# Example usage of the custom feedforward function
input_sequence = q_sequences[0]
output = custom_feedforward(input_sequence, weights_and_biases)
print(output)

Error happened on model.fit line.

I was expecting the program to train through the 20 epochs properly without any size errors.

New contributor

air_heads is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật