Splitting your code into two separate .py files—one for data preprocessing and another for the model—will enhance modularity, reusability, and maintainability. Below is a detailed guide on how to achieve this, along with sample code for each file.
Overview
-
data_preprocessing.py: This file will handle all aspects of data loading, cleaning, tokenization, encoding, vocabulary creation, and dataset preparation. It exposes functions and classes that can be easily imported and used in the model training script.
-
model.py: This file will contain all model-related code, including model definitions, training and evaluation functions. It will import necessary functions and classes from data_preprocessing.py.
-
Optional main.py: While not explicitly requested, it's often useful to have a main.py to orchestrate the training process by utilizing both data_preprocessing.py and model.py.
Below, I'll provide the contents for both data_preprocessing.py and model.py, ensuring that they work seamlessly together.
1. data_preprocessing.py
This module will encapsulate all data-related operations. It includes data loading, cleaning, tokenization, encoding, vocabulary building, and dataset preparation.
# data_preprocessing.py
import pandas as pd
import re
from collections import Counter
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from sklearn.model_selection import train_test_split
import torch
from torch.utils.data import Dataset, DataLoader
import nltk
nltk.download('punkt')
nltk.download('stopwords')
# Parameters
MIN_FREQ = 1
SEQUENCE_LENGTH = 8
BATCH_SIZE = 128
# Data Loading Function
def load_data(file_path):
data = []
with open(file_path, 'r', encoding='utf-8') as file:
for line in file:
text, label = line.strip().split('\t')
data.append((text, int(label)))
return pd.DataFrame(data, columns=['text', 'label'])
# Text Cleaning Function
def clean_text(text):
text = text.lower()
text = re.sub(r'<.*?>', '', text) # Remove HTML tags
text = re.sub(r'http\S+|www\S+|https\S+', '', text, flags=re.MULTILINE) # Remove URLs
text = re.sub(r'\d+', '', text) # Remove numbers
text = re.sub(r'[^\w\s]', '', text) # Remove punctuation
words = word_tokenize(text)
stop_words = set(stopwords.words('english'))
words = [word for word in words if word not in stop_words]
return ' '.join(words)
# Tokenization and Encoding Function
def tokenize_and_encode(sentences, vocab, seq_length):
token_ids = [
[vocab.get(token, vocab['<UNK>']) for token in sentence.split()]
for sentence in sentences
]
token_ids = [
t_ids[:seq_length] if len(t_ids) > seq_length else t_ids + [vocab['<PAD>']] * (seq_length - len(t_ids))
for t_ids in token_ids
]
return token_ids
# Vocabulary Building Function
def build_vocab(sentences, min_freq=1):
all_tokens = [token for sentence in sentences for token in sentence.split()]
word_counts = Counter(all_tokens)
filtered_words = [word for word, count in word_counts.items() if count >= min_freq]
vocabulary = {word: i + 2 for i, word in enumerate(filtered_words)}
vocabulary['<UNK>'] = 1
vocabulary['<PAD>'] = 0
return vocabulary, word_counts
# Custom Dataset Class
class SentimentDataset(Dataset):
def __init__(self, token_ids, labels):
self.token_ids = token_ids
self.labels = labels
def __len__(self):
return len(self.token_ids)
def __getitem__(self, idx):
return torch.tensor(self.token_ids[idx], dtype=torch.long), torch.tensor(self.labels[idx], dtype=torch.long)
# Function to Prepare DataLoaders
def prepare_dataloaders(file_path, sequence_length=SEQUENCE_LENGTH, min_freq=MIN_FREQ, batch_size=BATCH_SIZE):
# Load Data
dataset = load_data(file_path)
# Split Data
train_val_set, test_set = train_test_split(
dataset, train_size=900, test_size=100, random_state=42, stratify=dataset['label']
)
train_set, val_set = train_test_split(
train_val_set, train_size=800, test_size=100, random_state=42, stratify=train_val_set['label']
)
# Clean Texts
train_set['text'] = train_set['text'].apply(clean_text)
val_set['text'] = val_set['text'].apply(clean_text)
test_set['text'] = test_set['text'].apply(clean_text)
# Build Vocabulary
vocabulary, word_counts = build_vocab(train_set['text'], min_freq=min_freq)
vocab_size = len(vocabulary)
print(f"Vocabulary size: {vocab_size}")
# Tokenize and Encode
train_token_ids = tokenize_and_encode(train_set['text'], vocabulary, sequence_length)
val_token_ids = tokenize_and_encode(val_set['text'], vocabulary, sequence_length)
test_token_ids = tokenize_and_encode(test_set['text'], vocabulary, sequence_length)
# Create Datasets
train_dataset = SentimentDataset(train_token_ids, train_set['label'].tolist())
val_dataset = SentimentDataset(val_token_ids, val_set['label'].tolist())
test_dataset = SentimentDataset(test_token_ids, test_set['label'].tolist())
# Create DataLoaders
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
val_loader = DataLoader(val_dataset, batch_size=batch_size, shuffle=False)
test_loader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False)
# Label Statistics
def print_label_stats(name, df):
pos = df[df['label'] == 1].shape[0]
neg = df[df['label'] == 0].shape[0]
print(f"{name} Positive count: {pos}")
print(f"{name} Negative count: {neg}")
print_label_stats("Train", train_set)
print_label_stats("Validation", val_set)
print_label_stats("Test", test_set)
return {
'train_loader': train_loader,
'val_loader': val_loader,
'test_loader': test_loader,
'vocabulary': vocabulary,
'vocab_size': vocab_size
}
Explanation
-
Dependencies: The module imports necessary libraries for data manipulation, text processing, and PyTorch data handling.
-
Functions and Classes:
-
load_data: Reads the data from a file and returns a pandas DataFrame.
-
clean_text: Cleans the text by lowercasing, removing HTML tags, URLs, numbers, punctuation, tokenizing, and removing stopwords.
-
build_vocab: Creates a vocabulary dictionary based on word frequency.
-
tokenize_and_encode: Converts sentences into sequences of token IDs, applying padding or truncating to seq_length.
-
SentimentDataset: A custom PyTorch Dataset for sentiment analysis.
-
prepare_dataloaders: Orchestrates the entire preprocessing pipeline and returns DataLoaders along with vocabulary details.
-
Usage: This module can be imported in your main training script or model.py to provide preprocessed data ready for model training.
2. model.py
This module will contain all the model definitions, including any custom layers, the main model class, and training/evaluation functions. It will import the necessary data preprocessing functions from data_preprocessing.py.
# model.py
import torch
from torch import nn
from torch.optim import Adam
from torch.utils.data import DataLoader
from sklearn.metrics import f1_score, recall_score
import pennylane as qml
from pennylane import numpy as np
from collections import Counter
import matplotlib.pyplot as plt
from tqdm import tqdm
from data_preprocessing import prepare_dataloaders
# Set the device
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Hyperparameters
EMBEDDING_DIM = 100
HIDDEN_SIZE = 32
DROPOUT_RATE = 0.3
LEARNING_RATE = 0.001
HEADS = 4
EPOCHS = 50
N_QUBITS = 8
N_QLAYERS = 1
SEQUENCE_LENGTH = 8
BATCH_SIZE = 128
# Self-Attention Class
class MultiHeadSelfAttention(nn.Module):
def __init__(self, embed_dim, heads):
super().__init__()
self.embed_dim = embed_dim
self.heads = heads
self.head_dim = embed_dim // heads
assert self.head_dim * heads == embed_dim, "Embed size needs to be divisible by heads"
self.values = nn.Linear(self.head_dim, self.head_dim, bias=False)
self.keys = nn.Linear(self.head_dim, self.head_dim, bias=False)
self.queries = nn.Linear(self.head_dim, self.head_dim, bias=False)
self.fc_out = nn.Linear(heads * self.head_dim, embed_dim)
def forward(self, values, keys, query, mask):
N = query.shape[0]
value_len, key_len, query_len = values.shape[1], keys.shape[1], query.shape[1]
# Split the embedding into self.heads different pieces
values = values.reshape(N, value_len, self.heads, self.head_dim)
keys = keys.reshape(N, key_len, self.heads, self.head_dim)
queries = query.reshape(N, query_len, self.heads, self.head_dim)
values = self.values(values)
keys = self.keys(keys)
queries = self.queries(queries)
energy = torch.einsum("nqhd,nkhd->nhqk", [queries, keys])
if mask is not None:
energy = energy.masked_fill(mask == 0, float("-1e20"))
attention = torch.softmax(energy / (self.embed_dim ** (1 / 2)), dim=3)
out = torch.einsum("nhql, nlhd->nhqd", [attention, values]).reshape(N, query_len, self.heads * self.head_dim)
out = self.fc_out(out)
return out
# Quantum LSTM Class
class QLSTM(nn.Module):
def __init__(self,
input_size,
hidden_size,
n_qubits=8,
n_qlayers=1,
n_vrotations=3,
batch_first=True,
backend="default.qubit",
dropout_rate=0.3):
super(QLSTM, self).__init__()
self.input_size = input_size
self.hidden_size = hidden_size
self.n_qubits = n_qubits
self.n_qlayers = n_qlayers
self.n_vrotations = n_vrotations
self.backend = backend
self.batch_first = batch_first
# Define wires
self.wires_forget = [f"wire_forget_{i}" for i in range(self.n_qubits)]
self.wires_input = [f"wire_input_{i}" for i in range(self.n_qubits)]
self.wires_update = [f"wire_update_{i}" for i in range(self.n_qubits)]
self.wires_output = [f"wire_output_{i}" for i in range(self.n_qubits)]
self.wires_output_h = [f"wire_output_h_{i}" for i in range(self.n_qubits)]
# Define Linear Layers
self.fc = nn.Linear(self.hidden_size, 2)
self.clayer_in = nn.Linear(self.input_size + self.hidden_size, self.n_qubits)
self.clayer_out_f = nn.Linear(self.n_qubits, self.hidden_size)
self.clayer_out_i = nn.Linear(self.n_qubits, self.hidden_size)
self.clayer_out_g = nn.Linear(self.n_qubits, self.hidden_size)
self.clayer_out_o = nn.Linear(self.n_qubits, self.hidden_size)
# Define Dropout
self.dropout = nn.Dropout(dropout_rate)
# Define QNodes
self.dev_forget = qml.device(self.backend, wires=self.wires_forget)
self.dev_input = qml.device(self.backend, wires=self.wires_input)
self.dev_update = qml.device(self.backend, wires=self.wires_update)
self.dev_output = qml.device(self.backend, wires=self.wires_output)
self.dev_output_h = qml.device(self.backend, wires=self.wires_output_h)
self.qlayer_forget = qml.QNode(self._circuit_forget, self.dev_forget, interface="torch")
self.qlayer_input = qml.QNode(self._circuit_input, self.dev_input, interface="torch")
self.qlayer_update = qml.QNode(self._circuit_update, self.dev_update, interface="torch")
self.qlayer_output = qml.QNode(self._circuit_output, self.dev_output, interface="torch")
self.qlayer_output_h = qml.QNode(self._circuit_output_h, self.dev_output_h, interface="torch")
# Define Weight Shapes
self.weight_shapes = {"weights": (self.n_qlayers, self.n_vrotations, self.n_qubits)}
# Define Torch Layers
self.TorchLayers = {
'forget': qml.qnn.TorchLayer(self.qlayer_forget, self.weight_shapes),
'input': qml.qnn.TorchLayer(self.qlayer_input, self.weight_shapes),
'update': qml.qnn.TorchLayer(self.qlayer_update, self.weight_shapes),
'output': qml.qnn.TorchLayer(self.qlayer_output, self.weight_shapes),
'output_h': qml.qnn.TorchLayer(self.qlayer_output_h, self.weight_shapes)
}
def ansatz(self, params, wires_type):
for i in range(1, 3):
for j in range(self.n_qubits):
if j + i < self.n_qubits:
qml.CNOT(wires=[wires_type[j], wires_type[j + i]])
else:
qml.CNOT(wires=[wires_type[j], wires_type[j + i - self.n_qubits]])
for i in range(self.n_qubits):
qml.RX(params[0][i], wires=wires_type[i])
qml.RY(params[1][i], wires=wires_type[i])
qml.RZ(params[2][i], wires=wires_type[i])
def vqc(self, features, weights, wires_type):
if isinstance(features, np.ndarray):
features = torch.tensor(features, dtype=torch.float32)
if features.dim() == 1:
features = features.unsqueeze(0)
if not isinstance(features, torch.Tensor):
features = torch.tensor(features, dtype=torch.float32)
features = features[:, :self.n_qubits]
ry_params = torch.atan2(features, torch.ones_like(features))
rz_params = torch.atan2(features ** 2, torch.ones_like(features))
for i in range(self.n_qubits):
qml.Hadamard(wires=wires_type[i])
for i in range(self.n_qubits):
qml.RY(ry_params[:, i], wires=wires_type[i])
qml.RZ(rz_params[:, i], wires=wires_type[i])
for i in range(1, 3):
for j in range(self.n_qubits):
if j + i < self.n_qubits:
qml.CNOT(wires=[wires_type[j], wires_type[j + i]])
else:
qml.CNOT(wires=[wires_type[j], wires_type[j + i - self.n_qubits]])
for layer in range(self.n_qlayers):
for i in range(self.n_qubits):
qml.RX(weights[layer, 0, i], wires=wires_type[i])
qml.RY(weights[layer, 1, i], wires=wires_type[i])
qml.RZ(weights[layer, 2, i], wires=wires_type[i])
# Define Quantum Circuits for Gates
def _circuit_forget(self, inputs, weights):
self.vqc(inputs, weights, self.wires_forget)
return [qml.expval(qml.PauliZ(wires=i)) for i in self.wires_forget]
def _circuit_input(self, inputs, weights):
self.vqc(inputs, weights, self.wires_input)
return [qml.expval(qml.PauliZ(wires=i)) for i in self.wires_input]
def _circuit_update(self, inputs, weights):
self.vqc(inputs, weights, self.wires_update)
return [qml.expval(qml.PauliZ(wires=i)) for i in self.wires_update]
def _circuit_output(self, inputs, weights):
self.vqc(inputs, weights, self.wires_output)
return [qml.expval(qml.PauliZ(wires=i)) for i in self.wires_output]
def _circuit_output_h(self, inputs, weights):
self.vqc(inputs, weights, self.wires_output_h)
return [qml.expval(qml.PauliZ(wires=i)) for i in self.wires_output_h]
def forward(self, x, init_states=None):
batch_size, seq_length, _ = x.size()
if init_states is None:
h_t = torch.zeros(batch_size, self.hidden_size, dtype=torch.float32).to(device)
c_t = torch.zeros(batch_size, self.hidden_size, dtype=torch.float32).to(device)
else:
h_t, c_t = init_states
for t in range(seq_length):
x_t = x[:, t, :]
if len(h_t.size()) == 2:
h_t_last = h_t
else:
h_t_last = h_t[-1, :, :]
combined = torch.cat((h_t_last, x_t), dim=1)
combined = self.clayer_in(combined)
f_t_intermediate = self.TorchLayers['forget'](combined)
i_t_intermediate = self.TorchLayers['input'](combined)
g_t_intermediate = self.TorchLayers['update'](combined)
o_t_intermediate = self.TorchLayers['output'](combined)
f_t = torch.sigmoid(self.clayer_out_f(f_t_intermediate))
i_t = torch.sigmoid(self.clayer_out_i(i_t_intermediate))
g_t = torch.tanh(self.clayer_out_g(g_t_intermediate))
o_t = torch.sigmoid(self.clayer_out_o(o_t_intermediate))
c_t = f_t * c_t + i_t * g_t
h_t = o_t * torch.tanh(c_t)
h_t = self.dropout(h_t)
output = self.fc(h_t)
return output
# Classification Model with Attention and QLSTM
class QShallowClassificationLSTM(nn.Module):
def __init__(self, vocab_size, embedding_dim, hidden_units, n_qubits=8, n_qlayers=1, num_classes=2, dropout_rate=0.3, heads=4):
super().__init__()
self.hidden_units = hidden_units
self.num_classes = num_classes
self.embedding = nn.Embedding(vocab_size, embedding_dim)
self.attention = MultiHeadSelfAttention(embedding_dim, heads)
self.dropout = nn.Dropout(dropout_rate)
self.lstm = QLSTM(
input_size=embedding_dim,
hidden_size=hidden_units,
batch_first=True,
n_qubits=n_qubits,
n_qlayers=n_qlayers,
)
self.linear = nn.Linear(hidden_units, self.num_classes)
def forward(self, x):
x = self.embedding(x)
attended_x = self.attention(x, x, x, None)
x = self.dropout(attended_x)
outputs = self.lstm(x)
out = self.linear(outputs)
return out
# Training and Evaluation Functions
def calculate_accuracy_and_scores(data_loader, model):
model.eval()
correct = 0
total = 0
all_labels = []
all_predictions = []
with torch.no_grad():
for X, y in data_loader:
X = X.to(device)
y = y.to(device)
outputs = model(X)
_, predicted = torch.max(outputs.data, 1)
total += y.size(0)
correct += (predicted == y).sum().item()
all_labels.extend(y.cpu().numpy())
all_predictions.extend(predicted.cpu().numpy())
accuracy = 100 * correct / total
recall = recall_score(all_labels, all_predictions, pos_label=1)
f1 = f1_score(all_labels, all_predictions, pos_label=1)
return accuracy, recall, f1
def train_model(train_loader, model, criterion, optimizer, progress_bar):
model.train()
total_loss = 0
for X, y in train_loader:
X = X.to(device)
y = y.to(device)
optimizer.zero_grad()
outputs = model(X)
loss = criterion(outputs, y)
loss.backward()
optimizer.step()
total_loss += loss.item()
progress_bar.update(1)
avg_loss = total_loss / len(train_loader)
return avg_loss
def test_model(val_loader, model, criterion, progress_bar):
model.eval()
total_loss = 0
with torch.no_grad():
for X, y in val_loader:
X = X.to(device)
y = y.to(device)
outputs = model(X)
loss = criterion(outputs, y)
total_loss += loss.item()
progress_bar.update(1)
avg_loss = total_loss / len(val_loader)
return avg_loss
# Function to Plot Metrics
def plot_metrics(train_losses, val_losses, train_accuracies, val_accuracies, train_recalls, val_recalls, train_f1s, val_f1s):
epochs_range = range(1, len(train_losses) + 1)
plt.figure(figsize=(12, 6))
plt.plot(epochs_range, train_losses, label='Train Loss')
plt.plot(epochs_range, val_losses, label='Validation Loss')
plt.title('Loss Across Epochs')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
plt.show()
plt.figure(figsize=(12, 6))
plt.plot(epochs_range, train_accuracies, label='Train Accuracy')
plt.plot(epochs_range, val_accuracies, label='Validation Accuracy')
plt.plot(epochs_range, train_recalls, label='Train Recall')
plt.plot(epochs_range, val_recalls, label='Validation Recall')
plt.plot(epochs_range, train_f1s, label='Train F1 Score')
plt.plot(epochs_range, val_f1s, label='Validation F1 Score')
plt.title('Evaluation Metrics Across Epochs')
plt.xlabel('Epoch')
plt.ylabel('Metrics')
plt.legend()
plt.show()
# Visualization Function for Quantum Circuit (Optional)
def visualize_quantum_circuit(model_instance):
qiskit_circuit = model_instance.to_qiskit_circuit(
example_inputs=np.random.random((1, model_instance.lstm.n_qubits)),
example_weights=np.random.random((model_instance.lstm.n_qlayers, model_instance.lstm.n_vrotations, model_instance.lstm.n_qubits)),
wires_type=model_instance.lstm.wires_forget
)
qiskit_circuit.draw('mpl')
plt.show()
# Training Loop
def train_and_evaluate(file_path):
# Prepare DataLoaders
data = prepare_dataloaders(file_path, sequence_length=SEQUENCE_LENGTH, batch_size=BATCH_SIZE)
train_loader = data['train_loader']
val_loader = data['val_loader']
test_loader = data['test_loader']
vocab_size = data['vocab_size']
# Initialize Model
model = QShallowClassificationLSTM(
vocab_size=vocab_size,
embedding_dim=EMBEDDING_DIM,
hidden_units=HIDDEN_SIZE,
n_qubits=N_QUBITS,
n_qlayers=N_QLAYERS,
num_classes=2,
dropout_rate=DROPOUT_RATE,
heads=HEADS
).to(device)
# Define Loss and Optimizer
criterion = nn.CrossEntropyLoss()
optimizer = Adam(model.parameters(), lr=LEARNING_RATE)
# Metrics Tracking
train_losses = []
val_losses = []
train_accuracies = []
val_accuracies = []
train_recalls = []
val_recalls = []
train_f1s = []
val_f1s = []
# Training Loop
for epoch in range(EPOCHS):
print(f"Epoch {epoch+1}/{EPOCHS}")
total_steps = len(train_loader) + len(val_loader)
progress_bar = tqdm(total=total_steps, desc=f"Epoch {epoch + 1}")
# Train
train_loss = train_model(train_loader, model, criterion, optimizer, progress_bar)
train_losses.append(train_loss)
# Validate
val_loss = test_model(val_loader, model, criterion, progress_bar)
val_losses.append(val_loss)
# Calculate Metrics
train_acc, train_rec, train_f1 = calculate_accuracy_and_scores(train_loader, model)
val_acc, val_rec, val_f1 = calculate_accuracy_and_scores(val_loader, model)
train_accuracies.append(train_acc)
val_accuracies.append(val_acc)
train_recalls.append(train_rec)
val_recalls.append(val_rec)
train_f1s.append(train_f1)
val_f1s.append(val_f1)
progress_bar.close()
# Print Metrics
print(f"Train Loss: {train_loss:.4f} | Validation Loss: {val_loss:.4f}")
print(f"Train Acc: {train_acc:.2f}% | Validation Acc: {val_acc:.2f}%")
print(f"Train Recall: {train_rec:.2f} | Validation Recall: {val_rec:.2f}")
print(f"Train F1: {train_f1:.2f} | Validation F1: {val_f1:.2f}\n")
# Plot Metrics
plot_metrics(train_losses, val_losses, train_accuracies, val_accuracies,
train_recalls, val_recalls, train_f1s, val_f1s)
# Evaluate on Test Set
test_acc, test_rec, test_f1 = calculate_accuracy_and_scores(test_loader, model)
print(f"Test Accuracy: {test_acc:.2f}%")
print(f"Test Recall: {test_rec:.2f}")
print(f"Test F1 Score: {test_f1:.2f}")
return model
# Optional: Function to Visualize Quantum Circuit
def visualize_model(model):
model.lstm.visualize_qiskit_circuit()
# If you want to run model.py independently for testing
if __name__ == "__main__":
import warnings
warnings.filterwarnings("ignore")
file_path = 'amazon_cells_labelled.txt' # Ensure this file is in the same directory
trained_model = train_and_evaluate(file_path)
# visualize_model(trained_model) # Uncomment to visualize quantum circuit
Explanation
-
Dependencies: The module imports necessary libraries for model creation, training, evaluation, and visualization. It also imports the prepare_dataloaders function from data_preprocessing.py.
-
Device Setup: Checks if CUDA is available and sets the device accordingly.
-
Hyperparameters: Defined at the top for easy adjustments.
-
Model Components:
-
MultiHeadSelfAttention: Implements a multi-head self-attention mechanism.
-
QLSTM: Defines the Quantum LSTM layer utilizing PennyLane for quantum computations. This class includes the quantum circuits for forget, input, update, and output gates.
-
QShallowClassificationLSTM: The main classification model that combines Embedding, Self-Attention, Dropout, Quantum LSTM, and a final Linear layer for classification.
-
Training and Evaluation Functions:
-
calculate_accuracy_and_scores: Computes accuracy, recall, and F1-score.
-
train_model: Handles the training loop for one epoch.
-
test_model: Evaluates the model on validation or test data.
-
plot_metrics: Plots loss and evaluation metrics over epochs.
-
Visualization Function (Optional):
visualize_quantum_circuit: Uses Qiskit to visualize the quantum circuit. This requires Qiskit to be installed and properly set up.
-
Training Loop:
train_and_evaluate: Orchestrates the entire training process by preparing data, initializing the model, defining loss and optimizer, and running the training loop over specified epochs. It also plots the metrics and evaluates the model on the test set at the end.
-
Main Execution: Allows model.py to be run independently for testing purposes.
3. Optional main.py
While not explicitly requested, having a main.py can help orchestrate the training process more cleanly, especially if you plan to extend functionality in the future.
# main.py
from model import train_and_evaluate
def main():
file_path = 'amazon_cells_labelled.txt' # Ensure this file is in the same directory
train_and_evaluate(file_path)
if __name__ == "__main__":
main()
Explanation
-
main(): Simply calls the train_and_evaluate function from model.py, specifying the data file path.
-
Execution: Running python main.py will start the training process.
Ensuring Proper Functionality
To ensure that the split works correctly, follow these steps:
-
Directory Structure:
your_project/
├── data_preprocessing.py
├── model.py
├── main.py
├── amazon_cells_labelled.txt
└── other_files/
-
Install Necessary Libraries:
Ensure all required libraries are installed in your environment. You can install them using pip:
pip install pandas numpy matplotlib torch pennylane qiskit nltk scikit-learn tqdm
Additionally, download NLTK data if not already done. This is handled in data_preprocessing.py via nltk.download(), but ensure you have internet access the first time you run the script.
-
Running the Code:
-
Using model.py directly:
python model.py
-
Using main.py:
python main.py
-
Data File:
Ensure that the amazon_cells_labelled.txt file is placed in the same directory as your scripts or update the file_path accordingly.
-
Plotting and Visualization:
-
During training, loss and metric plots will be displayed. Ensure that your environment supports graphical display (e.g., running locally vs. on a headless server).
-
The quantum circuit visualization is optional and requires Qiskit. Uncomment the relevant line in model.py if you wish to visualize.
Benefits of This Split
-
Modularity: Separating data preprocessing from model definitions allows you to manage and update each part independently.
-
Reusability: You can reuse data_preprocessing.py with different models or experiments by simply importing its functions.
-
Maintainability: Easier to debug and maintain code when concerns are separated.
-
Scalability: Facilitates scaling the project by allowing multiple models to be developed and trained using the same preprocessing pipeline.
Additional Recommendations
-
Configuration Management: Consider using a configuration file (e.g., config.yaml or config.json) to manage hyperparameters and file paths. This makes it easier to experiment with different settings without changing the code.
-
Logging: Implement logging instead of printing to stdout for better tracking of training progress, especially for longer training runs.
-
Error Handling: Add error handling to manage potential issues during data loading, preprocessing, or training.
-
Unit Testing: Implement unit tests for your functions in data_preprocessing.py and model.py to ensure that each component works as expected.
By following the above structure and recommendations, you'll achieve a clean, modular, and maintainable codebase that aligns with best practices in software development and machine learning engineering.