Sure, here's the complete code for text chunking using BERT and k-means clustering:
import torch
from transformers import BertTokenizer, BertModel
import torch.nn.functional as F
import torch.optim as optim
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.cluster import KMeans
# Load pre-trained BERT model and tokenizer
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
model = BertModel.from_pretrained('bert-base-uncased')
# Encode the text into contextualized embeddings
encoded_text = tokenizer.encode("This is an example sentence", return_tensors='pt')
contextualized_embeddings = model(encoded_text['input_ids'], attention_mask=encoded_text['attention_mask'])
# Compute similarities between contextualized embeddings
similarities = torch.matmul(contextualized_embeddings, contextualized_embeddings.transpose(-1, -2))
# Cluster the contextualized embeddings
clusters = torch.kmeans(similarities, 5, batch_size=32, random_state=42)
# Assign chunk labels to each cluster
chunk_labels = torch.argmax(clusters, dim=1)
# Print the chunk labels
print(chunk_labels)
In this code, we first load the pre-trained BERT model and tokenizer. We then encode the input text into contextualized embeddings using the encode method of the tokenizer.
Next, we compute the similarities between the contextualized embeddings using the dot product of the embeddings. We then cluster the similarities using k-means clustering with 5 clusters and a batch size of 32.
Finally, we assign a chunk label to each cluster using the argmax function and print the chunk labels.
Note that you can adjust the number of clusters and the batch size as needed for your specific use case. You can also experiment with different clustering algorithms and parameters to see what works best for your