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
seed = 42
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
min_freq = 1
sequence_length = 10 # 10
embedding_dim = 100 # 词嵌入维度 与mat1有关
batch_size = 32
hidden_size = 64
dropout_rate = 0.5
lr = 0.0001
n_qlayers = 1
heads = 2
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()]
计算所有训练数据中单词的频率
Assistant
word_counts = Counter(all_train_tokens)
打印词汇表中每个单词的频率,按照频率从高到低排序
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()
请你综合分析我的模型,其中我所使用的数据集总数为1000条数据,其中经过数据预处理操作后,句子长度为10,并且其中涉及到了较多的0填充。请你结合我的数据集特点判断我的模型是否适合使用多头注意力机制,如果不适合,那为什么在使用多头注意力机制的情况下得到了一组较好效果的参数。
Based on your description and the provided code, let's analyze your model and dataset to understand if using a multi-head attention mechanism is appropriate, and why you might have observed good performance despite potential mismatches.
Dataset Characteristics:
Small Dataset Size: You are working with only 1,000 data points, which is relatively small for training deep learning models, especially those involving complex mechanisms like attention.
Short Sequence Length: After preprocessing, each sentence is padded or truncated to a length of 10 tokens.
Significant Padding: Due to the fixed sequence length and varying sentence lengths, many sequences contain a lot of <PAD> tokens (zeros after encoding). This means that actual informative content per sequence could be much less than 10 tokens.
Model Structure:
Embedding Layer: Transforms token indices into dense vectors of size embedding_dim.
Multi-Head Self-Attention Layer: Allows the model to focus on different positions within the input sequence.
Dropout Layer: Regularization to prevent overfitting.
Quantum LSTM (QLSTM) Layer: A custom LSTM implementation using quantum circuits.
Linear Output Layer: Outputs logits for classification.
Analysis of Using Multi-Head Attention Given the Dataset:
Short Sequences:
Attention Mechanism Purpose: The attention mechanism, especially multi-head attention, is designed to capture long-range dependencies in sequences. It excels in scenarios where important information is spread across long sequences, and relationships between distant tokens need to be modeled.
Impact of Short Sequences: With a maximum sequence length of 10, the potential for long-range dependencies is minimal. The sequences might not be long enough for the attention mechanism to demonstrate its full capabilities.
Padding Without Attention Masking:
Problem with Padding: Sequences are padded with zeros to achieve a uniform length. Without proper attention masking, the attention mechanism treats these padding tokens as valid parts of the sequence.
No Attention Masking in Your Code: In your model's forward method, you pass None for the mask:
attended_x = self.attention(x, x, x, None) # No mask provided
This means the attention mechanism cannot distinguish between actual tokens and padding tokens.
Consequences:
Attention to Padding: The model might attend to padding positions, which carry no meaningful information.
Diluted Attention Weights: Distribution of attention weights might be skewed, potentially reducing the model's ability to focus on important tokens.
Dataset Size Constraints:
Model Complexity vs. Dataset Size: Complex models require large datasets to generalize well. With only 1,000 samples, using sophisticated mechanisms like multi-head attention might lead to overfitting.
Why You Might Have Observed Good Performance Despite This:
Overfitting to Training Data:
Small Dataset: With limited data, models can easily memorize training samples.
Validation Split: If the validation set isn't sufficiently representative or is similar to the training set, overfitting might not be immediately apparent.
Strong Signal Words in Sentiment Analysis:
Presence of Key Tokens: Sentiment analysis often relies on specific words (e.g., "good", "bad", "great") that are strong indicators of sentiment.
Attention Mechanism Benefits: Even without masking, the attention mechanism can help the model focus more on these key tokens, improving performance.
Attention Mechanism as a Weighted Average:
Implicit Feature Selection: Attention layers can, to some extent, prioritize informative tokens over less informative ones, even in short sequences.
Unintended Regularization: The attention mechanism might inadvertently regularize the model by spreading attention weights, preventing any single token from dominating.
Model Capacity Compensating for Issues:
High Model Capacity: The combination of an embedding layer, attention, and a quantum LSTM introduces a large number of parameters.
Learning Despite Imperfections: The model might still find a way to optimize and produce good results, especially if the task isn't highly complex.
Random Chance and Metric Variance:
High Variance with Small Datasets: Metrics like accuracy and F1 score can fluctuate significantly with small datasets.
Possible Optimistic Results: The observed good performance might not generalize to unseen data.
Conclusion and Recommendations:
Suitability of Multi-Head Attention:
Not Ideal Given Dataset: Considering the short sequence length and significant padding without attention masking, using a multi-head attention mechanism might not be the most appropriate choice.
Limited Benefit: The main advantages of attention mechanisms are not fully utilized in this context.
Need for Attention Masking:
Implement Attention Masks: To make better use of the attention mechanism, implement masks to prevent the model from focusing on padding tokens.
# Create mask where '1' indicates actual tokens and '0' indicates padding
mask = (x != vocabulary['<PAD>']).unsqueeze(1).unsqueeze(2)
mask = mask.repeat(1, x.size(1), x.size(1))
attended_x = self.attention(x, x, x, mask)
Simplify the Model:
Consider Removing Attention: Given the dataset's limitations, you might achieve similar or better performance by removing the attention layer, thus reducing model complexity and overfitting risk.
Data Augmentation and Expansion:
Increase Dataset Size: Collect more data or use data augmentation techniques to expand your dataset, which would justify the use of more complex models.
Evaluation with Care:
Cross-Validation: Use techniques like k-fold cross-validation to ensure that your performance metrics are reliable and generalizable.
Test on Unseen Data: If possible, test your model on a separate, larger test set to evaluate its true performance.
Final Thoughts:
While your model might have shown good performance metrics, it's important to ensure that these results are not artifacts of overfitting or dataset biases. By adjusting your model to better suit your dataset and carefully evaluating its performance, you can achieve more reliable and generalizable results.