python
import os
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from transformers import AutoTokenizer, AutoModelForMaskedLM
from bert_topics import BertTopics
# Load the 20 newsgroups dataset
data_home = "https://s3.amazonaws.com/github-jars/20newsgroups.zip"
20_newsgroups = pd.read_csv(data_home, header=None, names=["group", "topic", "message", "author", "date"])
# Preprocess the dataset
tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
model = AutoModelForMaskedLM.from_pretrained("bert-base-uncased")
def preprocess_function(examples):
text = " ".join([tokenizer.decode(example["message"], skip_special_tokens=True) for example in examples])
inputs = tokenizer(text, truncation=True, padding="max_length", max_length=512)
return inputs
train_data = pd.read_csv("train.csv")
train_data, val_data = train_test_split(train_data, test_size=0.1, random_state=42)
train_dataset = train_data.apply(preprocess_function, axis=1)
val_dataset = val_data.apply(preprocess_function, axis=1)
# Split the topics for the training and validation sets
train_topics = train_data["topic"].tolist()
val_topics = val_data["topic"].tolist()