can you write python code to train text data in csv file, where column names are text, LOS and predict LOS which is number running from 1 days to 10 days or more, try using language model like GPT style in one file
Assistant
python
import pandas as pd
import torch
from transformers import BertTokenizer, BertForSequenceClassification, AdamW
from sklearn.model_selection import train_test_split
from torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler
from tqdm import tqdm
def main():
# Check if CUDA is available
device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')
print(f'Using device: {device}')
# Load data
df = pd.read_csv('data.csv') # Ensure 'data.csv' contains 'text' and 'LOS' columns
# Split data into training and validation sets
train_texts, val_texts, train_labels, val_labels = train_test_split(
df['text'], df['LOS'], test_size=0.2, random_state=42
)
# Initialize the tokenizer and model
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
model = BertForSequenceClassification.from_pretrained(
'bert-base-uncased',
num_labels=1,
problem_type='regression'
)
model.to(device)
# Tokenize the inputs
train_encodings = tokenizer(
train_texts.tolist(),
truncation=True,
padding=True,
max_length=512
)
val_encodings = tokenizer(
val_texts.tolist(),
truncation=True,
padding=True,
max_length=512
)
# Convert labels to tensors
train_labels = torch.tensor(train_labels.values, dtype=torch.float)
val_labels = torch.tensor(val_labels.values, dtype=torch.float)
# Create TensorDatasets
train_dataset = TensorDataset(
torch.tensor(train_encodings['input_ids']),
torch.tensor(train_encodings['attention_mask']),
train_labels
)
val_dataset = TensorDataset(
torch.tensor(val_encodings['input_ids']),
torch.tensor(val_encodings['attention_mask']),
val_labels
)
# Create DataLoaders
batch_size = 8
train_loader = DataLoader(
train_dataset,
sampler=RandomSampler(train_dataset),
batch_size=batch_size
)
val_loader = DataLoader(
val_dataset,
sampler=SequentialSampler(val_dataset),
batch_size=batch_size
)
# Set up the optimizer
optimizer = AdamW(model.parameters(), lr=2e-5)
# Training loop
epochs = 3
for epoch in range(epochs):
print(f'Epoch {epoch + 1}/{epochs}')
# Training
model.train()
total_train_loss = 0
for batch in tqdm(train_loader, desc='Training'):
optimizer.zero_grad()
input_ids = batch[0].to(device)
attention_mask = batch[1].to(device)
labels = batch[2].to(device)
outputs = model(
input_ids=input_ids,
attention_mask=attention_mask,
labels=labels
)
loss = outputs.loss
total_train_loss += loss.item()
loss.backward()
optimizer.step()
avg_train_loss = total_train_loss / len(train_loader)
print(f'Average training loss: {avg_train_loss}')
# Validation
model.eval()
total_val_loss = 0
with torch.no_grad():
for batch in tqdm(val_loader, desc='Validation'):
input_ids = batch[0].to(device)
attention_mask = batch[1].to(device)
labels = batch[2].to(device)
outputs = model(
input_ids=input_ids,
attention_mask=attention_mask,
labels=labels
)
loss = outputs.loss
total_val_loss += loss.item()
avg_val_loss = total_val_loss / len(val_loader)
print(f'Validation loss: {avg_val_loss}')
# Save the trained model
model.save_pretrained('./model_save/')
tokenizer.save_pretrained('./model_save/')
print('Model saved to ./model_save/')
if __name__ == '__main__':
main()
Instructions:
Prepare your data: Ensure you have a CSV file named data.csv in the same directory as this script. The CSV file should contain two columns: text (the input text data) and LOS (the length of stay as a numerical value).
Install required packages:
bash
pip install pandas torch transformers sklearn
Run the script:
bash
python train_los_model.py
Replace train_los_model.py with the filename you saved the script as.
Explanation:
The script reads the CSV file and splits the data into training and validation sets.
It uses the BertTokenizer and BertForSequenceClassification models from Hugging Face's Transformers library.
The model is fine-tuned for a regression task by setting num_labels=1 and problem_type='regression'.
The script tokenizes the input texts and creates PyTorch datasets and dataloaders.
It trains the model over a specified number of epochs and evaluates it on the validation set after each epoch.
Finally, it saves the trained model and tokenizer for future use.
Notes:
Adjust the batch_size, epochs, and learning rate (lr) as needed based on your dataset size and resources.
If you have access to a GPU, the script will automatically use it for faster training.
You can load and use the saved model for predictions or further fine-tuning later.