import torch
# Example of creating a tensor from token indices
token_indices = [10, 256, 1024]
text_tensor = torch.tensor(token_indices)
# Reshaping the tensor
reshaped_tensor = text_tensor.view(1, -1)
print("Original Tensor:", text_tensor)
print("Reshaped Tensor:", reshaped_tensor)
import torch.nn as nn
# Assuming a pre-trained embedding matrix is available
embedding_matrix = ... # Some pre-loaded embedding matrix
# Creating an embedding layer in PyTorch
embedding_layer = nn.Embedding.from_pretrained(embedding_matrix)
# Example input - indices for the words 'Hello' and 'World'
input_indices = torch.tensor([59, 102], dtype=torch.long)
# Fetching embeddings for the input
embeddings = embedding_layer(input_indices)
print("Embeddings:", embeddings)
import torch
import torch.nn as nn
# Creating a dummy embedding matrix with 1000 tokens, each being a 300-
# dimensional vector
embedding_matrix = torch.rand(1000, 300)
# Creating an embedding layer in PyTorch
embedding_layer = nn.Embedding.from_pretrained(embedding_matrix)
# Example input - indices for two hypothetical words
input_indices = torch.tensor([59, 102], dtype=torch.long)
# Fetching embeddings for the input
embeddings = embedding_layer(input_indices)
print("Embeddings:", embeddings)
import tensorflow as tf
# Load and prepare the dataset
mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
# Build the model
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(input_shape=(28, 28)),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(10)
])
# Compile and train the model
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
model.fit(x_train, y_train, epochs=5)
model.evaluate(x_test, y_test, verbose=2)
pythonCopy code
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
# Load and prepare the dataset
train_loader = torch.utils.data.DataLoader(
datasets.MNIST('./data', train=True, download=True,
transform=transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
])),
batch_size=64, shuffle=True)
test_loader = torch.utils.data.DataLoader(
datasets.MNIST('./data', train=False,
transform=transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
])),
batch_size=1000, shuffle=True)
# Define the network
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.fc1 = nn.Linear(28*28, 128)
self.fc2 = nn.Linear(128, 10)
def forward(self, x):
x = F.relu(self.fc1(x.view(-1, 28*28)))
x = self.fc2(x)
return x
net = Net()
optimizer = optim.Adam(net.parameters())
# Train the model
for epoch in range(5):
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
output = net(data)
loss = F.cross_entropy(output, target)
loss.backward()
optimizer.step()
# Evaluate the model
with torch.no_grad():
for data, target in test_loader:
output = net(data)
test_loss = F.cross_entropy(output, target, reduction='sum').item()