Upload bert.py
Browse files
bert.py
ADDED
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pandas as pd
|
2 |
+
from sklearn.model_selection import train_test_split
|
3 |
+
from transformers import BertTokenizer, TFBertForSequenceClassification
|
4 |
+
import tensorflow as tf
|
5 |
+
|
6 |
+
# Load preprocessed data
|
7 |
+
def load_data(file_path="preprocessed_reviews.csv"):
|
8 |
+
return pd.read_csv("preprocessed_reviews.csv")
|
9 |
+
|
10 |
+
# Tokenize text using BERT tokenizer
|
11 |
+
|
12 |
+
def tokenize_text(tokenizer, texts, max_length):
|
13 |
+
encodings = tokenizer(texts.tolist(), padding=True, truncation=True, max_length=max_length, return_tensors="tf")
|
14 |
+
# Convert BatchEncoding to dictionary
|
15 |
+
encodings_dict = {key: value.numpy() for key, value in encodings.items()}
|
16 |
+
return encodings_dict
|
17 |
+
|
18 |
+
|
19 |
+
if __name__ == "__main__":
|
20 |
+
# Load preprocessed data
|
21 |
+
data = load_data("preprocessed_reviews.csv")
|
22 |
+
|
23 |
+
# Check if 'sentiment' column exists
|
24 |
+
if 'sentiment' in data.columns:
|
25 |
+
# Split data into train and validation sets
|
26 |
+
train_data, val_data = train_test_split(data, test_size=0.2, random_state=42)
|
27 |
+
|
28 |
+
# Tokenize text using BERT tokenizer
|
29 |
+
max_length = 128
|
30 |
+
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
|
31 |
+
train_inputs = tokenize_text(tokenizer, train_data['clean_text'], max_length)
|
32 |
+
val_inputs = tokenize_text(tokenizer, val_data['clean_text'], max_length)
|
33 |
+
|
34 |
+
# Convert 'sentiment' column to numerical format
|
35 |
+
num_labels = len(data['sentiment'].unique())
|
36 |
+
train_labels = train_data['sentiment'].astype('category').cat.codes.values
|
37 |
+
val_labels = val_data['sentiment'].astype('category').cat.codes.values
|
38 |
+
|
39 |
+
# Fine-tuning BERT model for sequence classification
|
40 |
+
model = TFBertForSequenceClassification.from_pretrained('bert-base-uncased', num_labels=num_labels)
|
41 |
+
optimizer = tf.keras.optimizers.Adam(learning_rate=2e-5)
|
42 |
+
loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
|
43 |
+
metrics = ['accuracy']
|
44 |
+
model.compile(optimizer=optimizer, loss=loss, metrics=metrics)
|
45 |
+
|
46 |
+
# Train the model
|
47 |
+
history = model.fit(
|
48 |
+
train_inputs,
|
49 |
+
train_labels,
|
50 |
+
validation_data=(val_inputs, val_labels),
|
51 |
+
epochs=3,
|
52 |
+
batch_size=32,
|
53 |
+
verbose=1
|
54 |
+
)
|
55 |
+
|
56 |
+
# Evaluate the model
|
57 |
+
loss, accuracy = model.evaluate(val_inputs, val_labels)
|
58 |
+
print(f'Validation loss: {loss}, Validation accuracy: {accuracy}')
|
59 |
+
|
60 |
+
# Save the trained model
|
61 |
+
model.save_pretrained('fine_tuned_bert_model')
|
62 |
+
|
63 |
+
else:
|
64 |
+
raise ValueError("The 'sentiment' column is not found in the DataFrame.")
|