rating title text sentiment
5 Such a lovely scent but not overpowering. This spray is really nice. It smells really good, goes on really fine, and does the trick. I will say it feels like you need a lot of it though to get the texture I want. I have a lot of hair, medium thickness. I am comparing to other brands with yucky chemicals so I'm gonna stick with this. Try it! positive
4 Works great but smells a little weird. This product does what I need it to do, I just wish it was odorless or had a soft coconut smell. Having my head smell like an orange coffee is offputting. (granted, I did know the smell was described but I was hoping it would be light) positive
5 Yes! Smells good, feels great! positive
Given these, Give me a script to train my own LLM to give me positive, negative or neutral (only 3) that can accept n number of inputs and outputs positive negative or neutral.. Small Language model, as my dataset is 10k of each.
Clean dataset (remove non-characteric tokens) and ensure proper things.
use gpu.
Return full python code.
Assistant
python
import pandas as pd
import numpy as np
import torch
import re
from transformers import BertTokenizerFast, BertForSequenceClassification
from torch.utils.data import Dataset, DataLoader
import torch.nn as nn
import torch.optim as optim
from sklearn.model_selection import train_test_split
from tqdm import tqdm
# Check if GPU is available
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print(f'Using device: {device}')
# Load the dataset
# Replace 'dataset.csv' with your dataset file path
df = pd.read_csv('dataset.csv')
# Data Cleaning Function
def clean_text(text):
# Remove non-alphabetic characters
text = re.sub(r'[^a-zA-Z\s]', '', text)
# Lowercase
text = text.lower()
# Remove extra whitespace
text = re.sub(r'\s+', ' ', text).strip()
return text
# Clean the 'title' and 'text' columns and combine them
df['clean_title'] = df['title'].apply(clean_text)
df['clean_text'] = df['text'].apply(clean_text)
df['clean_full_text'] = df['clean_title'] + ' ' + df['clean_text']
# Map sentiments to labels
label_mapping = {'negative': 0, 'neutral': 1, 'positive': 2}
df['label'] = df['sentiment'].map(label_mapping)
# Split the dataset into training and validation sets
train_df, val_df = train_test_split(df, test_size=0.1, random_state=42, stratify=df['label'])
# Custom Dataset Class
class SentimentDataset(Dataset):
def __init__(self, texts, labels, tokenizer, max_len):
self.texts = texts.tolist()
self.labels = labels.tolist()
self.tokenizer = tokenizer
self.max_len = max_len
def __len__(self):
return len(self.labels)
def __getitem__(self, idx):
text = str(self.texts[idx])
label = self.labels[idx]
encoding = self.tokenizer.encode_plus(
text,
add_special_tokens=True,
truncation=True,
max_length=self.max_len,
padding='max_length', # Pad sequences to max_length
return_attention_mask=True,
return_tensors='pt'
)
return {
'input_ids': encoding['input_ids'].flatten(), # Flatten to 1D tensor
'attention_mask': encoding['attention_mask'].flatten(),
'labels': torch.tensor(label, dtype=torch.long)
}
# Initialize the tokenizer
tokenizer = BertTokenizerFast.from_pretrained('bert-base-uncased')
MAX_LEN = 128
# Create DataLoaders
BATCH_SIZE = 16
train_dataset = SentimentDataset(
texts=train_df['clean_full_text'],
labels=train_df['label'],
tokenizer=tokenizer,
max_len=MAX_LEN
)
val_dataset = SentimentDataset(
texts=val_df['clean_full_text'],
labels=val_df['label'],
tokenizer=tokenizer,
max_len=MAX_LEN
)
train_loader = DataLoader(train_dataset, batch_size=BATCH_SIZE, shuffle=True)
val_loader = DataLoader(val_dataset, batch_size=BATCH_SIZE, shuffle=False)
# Initialize the model
model = BertForSequenceClassification.from_pretrained('bert-base-uncased', num_labels=3)
model.to(device)
# Set up the optimizer
optimizer = optim.AdamW(model.parameters(), lr=2e-5)
# Training and Evaluation Functions
def train_epoch(model, data_loader, optimizer, device):
model.train()
losses = []
correct_predictions = 0
for batch in tqdm(data_loader, desc="Training"):
input_ids = batch['input_ids'].to(device)
attention_mask = batch['attention_mask'].to(device)
labels = batch['labels'].to(device)
outputs = model(
input_ids=input_ids,
attention_mask=attention_mask,
labels=labels
)
loss = outputs.loss
logits = outputs.logits
_, preds = torch.max(logits, dim=1)
correct_predictions += torch.sum(preds == labels)
losses.append(loss.item())
loss.backward()
optimizer.step()
optimizer.zero_grad()
return correct_predictions.double() / len(data_loader.dataset), np.mean(losses)
def eval_model(model, data_loader, device):
model.eval()
losses = []
correct_predictions = 0
with torch.no_grad():
for batch in tqdm(data_loader, desc="Validation"):
input_ids = batch['input_ids'].to(device)
attention_mask = batch['attention_mask'].to(device)
labels = batch['labels'].to(device)
outputs = model(
input_ids=input_ids,
attention_mask=attention_mask,
labels=labels
)
loss = outputs.loss
logits = outputs.logits
_, preds = torch.max(logits, dim=1)
correct_predictions += torch.sum(preds == labels)
losses.append(loss.item())
return correct_predictions.double() / len(data_loader.dataset), np.mean(losses)
# Training Loop
EPOCHS = 3
for epoch in range(EPOCHS):
print(f'Epoch {epoch + 1}/{EPOCHS}')
train_acc, train_loss = train_epoch(
model,
train_loader,
optimizer,
device
)
print(f'Train loss {train_loss:.4f} accuracy {train_acc:.4f}')
val_acc, val_loss = eval_model(
model,
val_loader,
device
)
print(f'Val loss {val_loss:.4f} accuracy {val_acc:.4f}')
# Save the trained model
model.save_pretrained('sentiment_model')
tokenizer.save_pretrained('sentiment_model')
# Function to predict sentiment
def predict_sentiment(text, tokenizer, model, device, max_len=128):
model.eval()
# Clean the text
text = clean_text(text)
encoding = tokenizer.encode_plus(
text,
add_special_tokens=True,
truncation=True,
max_length=max_len,
return_attention_mask=True,
return_tensors='pt'
)
input_ids = encoding['input_ids'].to(device)
attention_mask = encoding['attention_mask'].to(device)
with torch.no_grad():
outputs = model(
input_ids=input_ids,
attention_mask=attention_mask
)
logits = outputs.logits
_, prediction = torch.max(logits, dim=1)
label_map = {0: 'negative', 1: 'neutral', 2: 'positive'}
return label_map[prediction.item()]
# Example usage
# Load the trained model and tokenizer
tokenizer = BertTokenizerFast.from_pretrained('sentiment_model')
model = BertForSequenceClassification.from_pretrained('sentiment_model')
model.to(device)
# Predict sentiments for new texts
texts = [
"I absolutely love this product! It works wonders.",
"It's okay, nothing special.",
"I'm really disappointed. It broke after one use."
]
for text in texts:
sentiment = predict_sentiment(text, tokenizer, model, device)
print(f'Text: "{text}"')
print(f'Predicted Sentiment: {sentiment}')
print('-' * 50)
Explanation:
This script trains a sentiment analysis model using BERT on your dataset with 10,000 samples for each class (positive, negative, neutral). It performs the following steps:
Imports necessary libraries: Such as pandas, torch, transformers, etc.
Loads and cleans the dataset:
Removes non-alphabetic characters and extra whitespace.
Converts text to lowercase.
Combines the cleaned title and text columns.
Encodes sentiments into labels:
Maps 'negative' to 0, 'neutral' to 1, 'positive' to 2.
Splits the dataset into training and validation sets.
Creates a custom Dataset class to handle text data.
Initializes a tokenizer (BertTokenizerFast) and tokenizes the text data.
Prepares DataLoaders for batching and shuffling the data.
Loads a pre-trained BERT model (BertForSequenceClassification) with a classification head suitable for three classes.
Defines training and evaluation functions that handle the forward pass, loss computation, backpropagation, and accuracy calculation.
Trains the model for a specified number of epochs, printing out loss and accuracy for each epoch.
Saves the trained model and tokenizer to a directory ('sentiment_model').
Defines a function to predict sentiment for any given input text using the trained model.
Provides an example usage where it predicts sentiments for a list of new texts.
Notes:
GPU Usage: The script checks for a GPU and uses it if available for faster training.
Data Cleaning: The clean_text function is crucial to remove unwanted characters and standardize the text.
Batch Size and Sequence Length: Adjust BATCH_SIZE and MAX_LEN according to your computational resources.
Epochs: The number of epochs (EPOCHS) is set to 3, but you can increase it to improve performance.
Model Saving: The model and tokenizer are saved for later use without retraining.
To Run the Script:
Prepare your dataset in a CSV file named 'dataset.csv' with columns: rating, title, text, sentiment.