Check this code : import torch import torch.nn as nn from torch.utils.data import…
- User
Check this code : import torch import torch.nn as nn from torch.utils.data import DataLoader, TensorDataset import json
Define pair-bit tokenizer
def tokenize(text): tokens = text.split() token_pairs = [] for i in range(len(tokens)-1): token_pairs.append((tokens[i], tokens[i+1])) return token_pairs
Load training data from JSON file
try: with open('Chatdata.json', 'r') as file: training_data = json.load(file) except FileNotFoundError: print("Training data file not found.") exit()
Tokenization using pair-bit tokenizer
vocab = set() for item in training_data: token_pairs = tokenize(item['input']) token_pairs += tokenize(item['output']) vocab.update(token_pairs) vocab_size = len(vocab) index_to_char = list(vocab) char_to_index = {char: index for index, char in enumerate(index_to_char)}
Convert input and output sequences to numerical representation and pad them
max_seq_length = max(max(len(tokenize(item['input'])), len(tokenize(item['output']))) for item in training_data) input_sequences = torch.zeros((len(training_data), max_seq_length), dtype=torch.long) output_sequences = torch.zeros((len(training_data), max_seq_length), dtype=torch.long)
for i, item in enumerate(training_data): input_seq = [char_to_index[pair] for pair in tokenize(item['input'])] output_seq = [char_to_index[pair] for pair in tokenize(item['output'])] input_sequences[i, :len(input_seq)] = torch.tensor(input_seq) output_sequences[i, :len(output_seq)] = torch.tensor(output_seq)
Define LSTM model
class ChatbotLSTM(nn.Module): def init(self, vocab_size, hidden_size): super(ChatbotLSTM, self).init() self.hidden_size = hidden_size self.embedding = nn.Embedding(vocab_size, hidden_size) self.lstm = nn.LSTM(hidden_size, hidden_size, batch_first=True) self.fc = nn.Linear(hidden_size, vocab_size)
codedef forward(self, input_seq): embedded = self.embedding(input_seq) lstm_out, _ = self.lstm(embedded) output = self.fc(lstm_out) return outputInitialize the model
hidden_size = 512 model = ChatbotLSTM(vocab_size, hidden_size) criterion = nn.CrossEntropyLoss() optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
Create DataLoader for batch processing
batch_size = 64 dataset = TensorDataset(input_sequences, output_sequences) dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=True)
Train the model
model.train() for epoch in range(200): for input_batch, target_batch in dataloader: optimizer.zero_grad() output = model(input_batch)
code - Assistant
The issue is caused by attempting to serialize a dictionary (
char_to_indexandindex_to_char) containing tuples as keys into JSON. The JSON specification doesn't support tuples, lists, or any non-string data types as keys in dictionaries. They must be stringified or changed to a type that is serializable to JSON (like strings).It seems that you're trying to use word pairs (tuples of strings) as keys. To solve this, you can convert these tuples to strings before serialization:
Here’s how you could modify the sections where
char_to_indexandindex_to_charare created, and where they are saved as JSON:python - User
- Assistant
- User
I got this error : Traceback (most recent call last): File "c:\Users\L14\Desktop\Projets\Experimental-Learning\run.py", line 37, in index_to_char = {int(key): tuple(value.split(" ")) for key, value in vocab_data.items()} # Fixed split parameter File "c:\Users\L14\Desktop\Projets\Experimental-Learning\run.py", line 37, in index_to_char = {int(key): tuple(value.split(" ")) for key, value in vocab_data.items()} # Fixed split parameter ValueError: invalid literal for int() with base 10: 'doing?'
- Assistant
It looks like there's a misunderstanding in re-creating the
index_to_chardictionary from thevocab_data—the error suggests that it contains actual token pairs as values rather than numerical indices as the keys.