import pandas as pd
import time
import numpy as np
import matplotlib.pyplot as plt
import os
import torch
from torch import nn
from torch.utils.data import Dataset, DataLoader
from collections import Counter
import torch.nn.functional
import pennylane as qml
from pennylane import numpy as np
from datasets import load_dataset
from tqdm import tqdm # 添加进度条
import nltk
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
import re
from sklearn.model_selection import train_test_split
from qiskit import QuantumCircuit
from qiskit.visualization import circuit_drawer
from sklearn.metrics import f1_score, recall_score
import random
random.seed(42)
min_freq = 1
sequence_length = 8
embedding_dim = 100 # 词嵌入维度 与mat1有关
batch_size = 128
hidden_size = 32
dropout_rate = 0.3
lr = 0.001
n_qlayers = 1
heads = 4
epoch = 40
n_qubits = 4
#weight_decay = 0.00001
读取数据文件
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'])
文本清洗函数
def clean_text(text):
# 转换为小写
text = text.lower()
# 移除 HTML 标签
text = re.sub(r'<.*?>', '', text)
# 移除 URL
text = re.sub(r'http\S+|www\S+|https\S+', '', text, flags=re.MULTILINE)
# 移除标点符号和数字
text = re.sub(r'\d+', '', text)
text = re.sub(r'[^\w\s]', '', text)
# 分词
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)
def tokenize_and_encode(sentences, vocab, seq_length):
token_ids = [
[vocab.get(token, vocab['']) 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['']] * (seq_length - len(t_ids))
for t_ids in token_ids
]
return token_ids
从训练数据集创建词汇表
all_train_tokens = [token for sentence in train_set['text'] for token in sentence.split()]
计算所有训练数据中单词的频率
word_counts = Counter(all_train_tokens)
Assistant
打印词汇表中每个单词的频率,按照频率从高到低排序
for word, count in word_counts.most_common():
print(f"{word}: {count}")
只保留出现次数大于等于阈值的单词
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[''] = 1
vocabulary[''] = 0
plt.plot(train_f1_list, label='Train F1 Score')
plt.plot(val_f1_list, label='Validation F1 Score')
plt.plot(test_f1_list, label='Test F1 Score')
模型性能指标
plt.title('Model Evaluation Metrics Across Epochs')
plt.xlabel('Epoch')
plt.ylabel('Metrics')
plt.legend()
plt.show()
我的模型已经设置了随机数种子,但是我在使用相同参数进行模型训练时结果还是不相同。请你结合我的代码分析是什么原因导致的
The differences in your results between runs are due to incomplete control of randomness across all libraries and modules used in your code. While you have set the random seed for Python's built-in random module using random.seed(42), your code also utilizes other libraries like NumPy, PyTorch, and possibly quantum computing frameworks like PennyLane or Qiskit, which have their own random number generators. Each of these libraries must have their random seeds set independently to ensure reproducibility.
Here's why you're experiencing non-deterministic behavior and how to fix it:
NumPy's Randomness:
NumPy has its own random number generator, and functions from NumPy's random module (e.g., np.random.random, np.random.randn) will produce different results unless you set the seed for NumPy as well.
Solution: Add np.random.seed(42) at the beginning of your code.
PyTorch's Randomness:
PyTorch's operations, especially those involving initialization (like nn.Linear), data loading, and certain operations (like dropout), utilize random numbers.
Solution: Add torch.manual_seed(42) at the beginning of your code.
CUDNN Determinism in PyTorch:
If you're using a GPU, PyTorch's cuDNN backend introduces non-determinism due to optimization algorithms that are non-deterministic.
Note that setting torch.backends.cudnn.deterministic = True may impact performance because it disables some optimizations.
Quantum Computing Libraries:
Quantum simulators and frameworks like PennyLane or Qiskit can introduce randomness, especially if they're configured to simulate probabilistic quantum behavior.
Solution: Check the documentation of the quantum libraries you're using to see if they provide a way to set seeds or control randomness. For example, in PennyLane, you can set the seed when creating a device:
dev = qml.device('default.qubit', wires=4, shots=1024, seed=42)
Ensure that all devices are initialized with a fixed seed.
DataLoader Randomness:
PyTorch's DataLoader uses multiple worker processes (if num_workers > 0) which can introduce randomness in data shuffling.
Solution: When creating your DataLoader, set worker_init_fn to set the seed for each worker:
Operating System and Hardware Sources of Non-Determinism:
Some operations may behave non-deterministically due to the way floating-point arithmetic is handled by your CPU or GPU.
Solution: While this is harder to control, ensuring that all seeds are set and that you use deterministic algorithms where possible will minimize variability.
Third-Party Libraries:
If there are any other libraries that use randomness, ensure their seeds are set if they provide such an option.
Updated Code with Fixes:
import random
import numpy as np
import torch
# Set seeds for all relevant libraries
random.seed(42)
np.random.seed(42)
torch.manual_seed(42)
# If using GPU
torch.cuda.manual_seed(42)
torch.cuda.manual_seed_all(42) # if you are using multi-GPU.
# Ensure deterministic behavior in cuDNN (may affect performance)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
# For PyTorch DataLoader workers
def seed_worker(worker_id):
worker_seed = torch.initial_seed() % 2**32
np.random.seed(worker_seed)
random.seed(worker_seed)
# Use generator with fixed seed for DataLoader
g = torch.Generator()
g.manual_seed(42)
# Update your DataLoader to include worker_init_fn and generator
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True, worker_init_fn=seed_worker, generator=g)
val_loader = DataLoader(val_dataset, batch_size=batch_size, shuffle=False, worker_init_fn=seed_worker, generator=g)
Additional Considerations:
Quantum Device Seeds:
For each quantum device you instantiate, ensure that you set the seed. For example:
Do this for all devices (dev_forget, dev_input, etc.).
Version Consistency:
Make sure all library versions are the same between runs. Different versions might handle randomness differently.
Re-Execution of Cells in Notebooks:
If you're running this code in a Jupyter notebook, be cautious about re-executing cells. State from previous executions can persist.
Why This Matters:
Random Number Generators (RNGs): Each library has its own RNG. If you only set the seed for one, the others will still produce different random numbers each time.
Reproducibility: Setting seeds across all libraries ensures that every source of randomness is controlled, leading to reproducible results.
Determinism in Parallel Computing: Operations that utilize parallelism or GPUs can introduce non-determinism due to asynchronous execution and non-deterministic algorithms unless explicitly controlled.
Conclusion:
To achieve reproducible results, you need to set the random seeds for all libraries and control any other sources of non-determinism, such as setting deterministic flags in PyTorch and ensuring consistent behavior in quantum simulations. By updating your code as shown, your model's training should produce consistent results across runs with the same parameters.