import tensorflow as tf
import torch
import re
def preprocess_text(text):
text = text.lower()
text = re.sub(r'\d+', '', text)
text = re.sub(r'\s+', ' ', text)
text = re.sub(r'\W', ' ', text)
return text
class RNNModel(nn.Module):
def __init__(self, vocab_size, embed_size, hidden_size, num_layers):
super(RNNModel, self).__init__()
self.embed = nn.Embedding(vocab_size, embed_size)
self.rnn = nn.RNN(embed_size, hidden_size, num_layers)
self.linear = nn.Linear(hidden_size, vocab_size)
def forward(self, x, h):
x = self.embed(x)
out, h = self.rnn(x, h)
out = self.linear(out)
return out, h
def train(model, data, epochs, lr):
optimizer = torch.optim.Adam(model.parameters(), lr=lr)
criterion = nn.CrossEntropyLoss()
for epoch in range(epochs):
hidden = None
for x, y in data:
optimizer.zero_grad()
outputs, hidden = model(x, hidden)
loss = criterion(outputs, y)
loss.backward()
optimizer.step()
Explaindef generate_text(model, seed_text, num_words):
model.eval()
text = seed_text
for _ in range(num_words):
x = torch.tensor([text[-1]])
output, _ = model(x, None)
_, predicted = torch.max(output, 1)
text.append(predicted.item())
return text
python
import tensorflow as tf
import torch
python
Explainimport re
def preprocess_text(text):
text = text.lower()
text = re.sub(r'\d+', '', text)
text = re.sub(r'\s+', ' ', text)
text = re.sub(r'\W', ' ', text)
return text
python
Explainclass RNNModel(nn.Module):
def __init__(self, vocab_size, embed_size, hidden_size, num_layers):
super(RNNModel, self).__init__()
self.embed = nn.Embedding(vocab_size, embed_size)
self.rnn = nn.RNN(embed_size, hidden_size, num_layers)
self.linear = nn.Linear(hidden_size, vocab_size)
def forward(self, x, h):
x = self.embed(x)
out, h = self.rnn(x, h)
out = self.linear(out)
return out, h
python
Explaindef train(model, data, epochs, lr):
optimizer = torch.optim.Adam(model.parameters(), lr=lr)
criterion = nn.CrossEntropyLoss()
for epoch in range(epochs):
hidden = None
for x, y in data:
optimizer.zero_grad()
outputs, hidden = model(x, hidden)
loss = criterion(outputs, y)
loss.backward()
optimizer.step()
python
def generate_text(model, seed_text, num_words):
model.eval()
text = seed_text
for _ in range(num_words):
x = torch.tensor([text[-1]])
output, _ = model(x, None)
_, predicted = torch.max(output, 1)
text.append(predicted.item())
return text