Commit
·
8768724
1
Parent(s):
ea4b4e5
Adding Model... let's test it
Browse files
model.py
ADDED
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pandas as pd
|
2 |
+
import torch
|
3 |
+
from sklearn.model_selection import train_test_split
|
4 |
+
from transformers import BertTokenizer, BertForSequenceClassification, TrainingArguments, Trainer
|
5 |
+
|
6 |
+
df = pd.read_csv('Training_Essay_Data 1.csv.csv')
|
7 |
+
|
8 |
+
train_df, eval_df = train_test_split(df, test_size=0.1) # Here 10% for validation
|
9 |
+
|
10 |
+
tokenizer = BertTokenizer.from_pretrained('bert-baseuncased')
|
11 |
+
|
12 |
+
|
13 |
+
def tokenize_function(examples):
|
14 |
+
return tokenizer(examples['text'], padding='max_length', truncation=True, max_length=512)
|
15 |
+
|
16 |
+
|
17 |
+
train_encodings = tokenize_function(train_df)
|
18 |
+
eval_encodings = tokenize_function(eval_df)
|
19 |
+
|
20 |
+
|
21 |
+
class EssayDataset(torch.utils.data.Dataset):
|
22 |
+
def __init__(self, encodings, labels):
|
23 |
+
self.encodings = encodings
|
24 |
+
self.labels = labels
|
25 |
+
|
26 |
+
def __getitem__(self, idx):
|
27 |
+
item = {key: torch.tensor(val[idx]) for key, val in self.encodings.items()}
|
28 |
+
item['labels'] = torch.tensor(int(self.labels[idx])) # Convert labels to tensor
|
29 |
+
return item
|
30 |
+
|
31 |
+
def __len__(self):
|
32 |
+
return len(self.labels)
|
33 |
+
|
34 |
+
|
35 |
+
train_dataset = EssayDataset(train_encodings, train_df['label'].tolist())
|
36 |
+
eval_dataset = EssayDataset(eval_encodings, eval_df['label'].tolist())
|
37 |
+
|
38 |
+
model = BertForSequenceClassification.from_pretrained('bertbase-uncased', num_labels=2)
|
39 |
+
|
40 |
+
training_args = TrainingArguments(
|
41 |
+
output_dir='./results',
|
42 |
+
num_train_epochs=3,
|
43 |
+
per_device_train_batch_size=16,
|
44 |
+
per_device_eval_batch_size=64,
|
45 |
+
warmup_steps=500,
|
46 |
+
weight_decay=0.01,
|
47 |
+
logging_dir='./logs',
|
48 |
+
)
|
49 |
+
|
50 |
+
trainer = Trainer(
|
51 |
+
model=model,
|
52 |
+
args=training_args,
|
53 |
+
train_dataset=train_dataset,
|
54 |
+
eval_dataset=eval_dataset
|
55 |
+
)
|
56 |
+
|
57 |
+
trainer.train()
|
58 |
+
|
59 |
+
user_input = input("Enter the text you want to classify: ")
|
60 |
+
inputs = tokenizer(user_input, padding=True, truncation=True,
|
61 |
+
return_tensors="pt")
|
62 |
+
outputs = model(**inputs)
|
63 |
+
predictions = torch.argmax(outputs.logits, dim=-1)
|
64 |
+
print("Classified as:", "AI-generated" if predictions.item() == 1 else "Human-written")
|