Spaces:
Paused
Paused
Commit
•
1be676c
1
Parent(s):
1cc112a
added in a general model
Browse files- .gitignore +2 -1
- general_model_train.py +158 -0
- requirements.txt +1 -0
.gitignore
CHANGED
@@ -7,4 +7,5 @@ raw copy/*
|
|
7 |
results/*
|
8 |
logs/*
|
9 |
specificity-model/*
|
10 |
-
specificity-results/*
|
|
|
|
7 |
results/*
|
8 |
logs/*
|
9 |
specificity-model/*
|
10 |
+
specificity-results/*
|
11 |
+
trained_model/*
|
general_model_train.py
ADDED
@@ -0,0 +1,158 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import psycopg2
|
3 |
+
import logging
|
4 |
+
from sklearn.preprocessing import LabelEncoder
|
5 |
+
from db.db_utils import get_connection
|
6 |
+
from dotenv import load_dotenv
|
7 |
+
from psycopg2.extras import DictCursor
|
8 |
+
import pandas as pd
|
9 |
+
from datasets import Dataset
|
10 |
+
from transformers import AutoTokenizer, AutoModelForSequenceClassification, Trainer, TrainingArguments, EarlyStoppingCallback
|
11 |
+
import torch
|
12 |
+
import transformers
|
13 |
+
|
14 |
+
# Configure logging
|
15 |
+
logging.basicConfig(level=logging.INFO)
|
16 |
+
logger = logging.getLogger(__name__)
|
17 |
+
transformers.logging.set_verbosity_info()
|
18 |
+
|
19 |
+
# Load environment variables
|
20 |
+
load_dotenv()
|
21 |
+
|
22 |
+
# Set device
|
23 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
24 |
+
|
25 |
+
# Fetch data from database
|
26 |
+
def fetch_data():
|
27 |
+
logger.info("Connecting to the database...")
|
28 |
+
conn = get_connection()
|
29 |
+
cursor = conn.cursor(cursor_factory=DictCursor)
|
30 |
+
try:
|
31 |
+
logger.info("Fetching data from mappings table...")
|
32 |
+
cursor.execute("SELECT input_word, dictionary_word FROM mappings")
|
33 |
+
mappings_data = cursor.fetchall()
|
34 |
+
logger.info(f"Fetched {len(mappings_data)} records from mappings table.")
|
35 |
+
|
36 |
+
logger.info("Fetching data from dictionary table...")
|
37 |
+
cursor.execute("SELECT description FROM dictionary")
|
38 |
+
dictionary_data = cursor.fetchall()
|
39 |
+
logger.info(f"Fetched {len(dictionary_data)} records from dictionary table.")
|
40 |
+
|
41 |
+
return mappings_data, dictionary_data
|
42 |
+
finally:
|
43 |
+
cursor.close()
|
44 |
+
conn.close()
|
45 |
+
logger.info("Database connection closed.")
|
46 |
+
|
47 |
+
# Load data
|
48 |
+
logger.info("Loading data from database...")
|
49 |
+
mappings_data, dictionary_data = fetch_data()
|
50 |
+
|
51 |
+
# Prepare data for model
|
52 |
+
logger.info("Preparing data for the model...")
|
53 |
+
mappings_df = pd.DataFrame(mappings_data, columns=['word', 'usda_item'])
|
54 |
+
dictionary_df = pd.DataFrame(dictionary_data, columns=['usda_item'])
|
55 |
+
|
56 |
+
# Combine the mappings and dictionary data
|
57 |
+
data = pd.concat([mappings_df, dictionary_df], ignore_index=True).drop_duplicates()
|
58 |
+
|
59 |
+
# Show the first 100 rows of the dataset
|
60 |
+
logger.info("Showing the first 100 rows of the dataset...")
|
61 |
+
print(data.head(100))
|
62 |
+
|
63 |
+
# Encode the USDA items as labels
|
64 |
+
logger.info("Encoding USDA items as labels...")
|
65 |
+
label_encoder = LabelEncoder()
|
66 |
+
data['label'] = label_encoder.fit_transform(data['usda_item'])
|
67 |
+
|
68 |
+
# Prepare the dataset
|
69 |
+
logger.info("Creating dataset from the data frame...")
|
70 |
+
dataset = Dataset.from_pandas(data)
|
71 |
+
|
72 |
+
# Split data into training and validation sets
|
73 |
+
logger.info("Splitting data into training and validation sets...")
|
74 |
+
train_test = dataset.train_test_split(test_size=0.1)
|
75 |
+
train_dataset = train_test['train']
|
76 |
+
eval_dataset = train_test['test']
|
77 |
+
|
78 |
+
# Initialize tokenizer and model
|
79 |
+
model_name = "roberta-base"
|
80 |
+
logger.info(f"Loading tokenizer and model: {model_name}...")
|
81 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
82 |
+
model = AutoModelForSequenceClassification.from_pretrained(model_name, num_labels=len(label_encoder.classes_))
|
83 |
+
|
84 |
+
# Move model to device
|
85 |
+
model.to(device)
|
86 |
+
|
87 |
+
# Tokenize data
|
88 |
+
logger.info("Tokenizing data...")
|
89 |
+
def preprocess_data(examples):
|
90 |
+
return tokenizer(examples['word'], truncation=True, padding='max_length')
|
91 |
+
|
92 |
+
train_dataset = train_dataset.map(preprocess_data, batched=True)
|
93 |
+
eval_dataset = eval_dataset.map(preprocess_data, batched=True)
|
94 |
+
|
95 |
+
# Set format for PyTorch
|
96 |
+
logger.info("Setting dataset format for PyTorch...")
|
97 |
+
train_dataset.set_format(type='torch', columns=['input_ids', 'attention_mask', 'label'])
|
98 |
+
eval_dataset.set_format(type='torch', columns=['input_ids', 'attention_mask', 'label'])
|
99 |
+
|
100 |
+
# Define training arguments
|
101 |
+
logger.info("Defining training arguments...")
|
102 |
+
training_args = TrainingArguments(
|
103 |
+
output_dir="./results",
|
104 |
+
evaluation_strategy="epoch",
|
105 |
+
logging_dir='./logs', # Directory for storing logs
|
106 |
+
logging_steps=10, # Log every 10 steps
|
107 |
+
learning_rate=2e-5, # Try different values like 1e-5, 3e-5, etc.
|
108 |
+
per_device_train_batch_size=16, # Try different values like 32, 64, etc.
|
109 |
+
per_device_eval_batch_size=16,
|
110 |
+
num_train_epochs=5, # Experiment with 3, 5, 10, etc.
|
111 |
+
weight_decay=0.01, # Try different values like 0.1
|
112 |
+
warmup_steps=500, # Number of warmup steps for learning rate scheduler
|
113 |
+
save_total_limit=2, # Limit the total amount of checkpoints
|
114 |
+
load_best_model_at_end=True, # Load the best model at the end
|
115 |
+
)
|
116 |
+
|
117 |
+
# Initialize Trainer
|
118 |
+
logger.info("Initializing Trainer...")
|
119 |
+
trainer = Trainer(
|
120 |
+
model=model,
|
121 |
+
args=training_args,
|
122 |
+
train_dataset=train_dataset,
|
123 |
+
eval_dataset=eval_dataset,
|
124 |
+
callbacks=[EarlyStoppingCallback(early_stopping_patience=3)] # Early stopping
|
125 |
+
)
|
126 |
+
|
127 |
+
# Train the model
|
128 |
+
logger.info("Starting model training...")
|
129 |
+
trainer.train()
|
130 |
+
logger.info("Model training completed.")
|
131 |
+
|
132 |
+
# Evaluate the model
|
133 |
+
logger.info("Evaluating the model...")
|
134 |
+
trainer.evaluate()
|
135 |
+
logger.info("Model evaluation completed.")
|
136 |
+
|
137 |
+
# Save the trained model and tokenizer
|
138 |
+
output_dir = "./trained_model"
|
139 |
+
logger.info(f"Saving model and tokenizer to {output_dir}...")
|
140 |
+
model.save_pretrained(output_dir)
|
141 |
+
tokenizer.save_pretrained(output_dir)
|
142 |
+
logger.info("Model and tokenizer saved.")
|
143 |
+
|
144 |
+
# Function to predict USDA food item
|
145 |
+
def predict_usda_item(word):
|
146 |
+
logger.info(f"Predicting USDA food item for the word: {word}")
|
147 |
+
inputs = tokenizer(word, return_tensors="pt", truncation=True, padding="max_length").to(device)
|
148 |
+
outputs = model(**inputs)
|
149 |
+
predictions = outputs.logits.argmax(-1)
|
150 |
+
predicted_label = predictions.item()
|
151 |
+
predicted_item = label_encoder.inverse_transform([predicted_label])[0]
|
152 |
+
logger.info(f"Predicted USDA food item: {predicted_item}")
|
153 |
+
return predicted_item
|
154 |
+
|
155 |
+
# Test the function
|
156 |
+
logger.info("Testing the prediction function...")
|
157 |
+
print(predict_usda_item("Squash"))
|
158 |
+
logger.info("Script completed.")
|
requirements.txt
CHANGED
@@ -1,6 +1,7 @@
|
|
1 |
--extra-index-url https://download.pytorch.org/whl/cu113
|
2 |
accelerate==0.31.0
|
3 |
autocorrect==2.6.1
|
|
|
4 |
gradio==4.36.1
|
5 |
mistralai==0.4.0
|
6 |
numpy==1.26.4
|
|
|
1 |
--extra-index-url https://download.pytorch.org/whl/cu113
|
2 |
accelerate==0.31.0
|
3 |
autocorrect==2.6.1
|
4 |
+
datasets==2.20.0
|
5 |
gradio==4.36.1
|
6 |
mistralai==0.4.0
|
7 |
numpy==1.26.4
|