smeintadmin commited on
Commit
1ae8986
·
1 Parent(s): 5ed372c

Upload 16 files

Browse files
config.json CHANGED
@@ -1,5 +1,5 @@
1
  {
2
- "_name_or_path": "roberta-large",
3
  "architectures": [
4
  "RobertaForSequenceClassification"
5
  ],
@@ -21,7 +21,7 @@
21
  "position_embedding_type": "absolute",
22
  "problem_type": "single_label_classification",
23
  "torch_dtype": "float32",
24
- "transformers_version": "4.31.0",
25
  "type_vocab_size": 1,
26
  "use_cache": true,
27
  "vocab_size": 50265
 
1
  {
2
+ "_name_or_path": "img_intents_model",
3
  "architectures": [
4
  "RobertaForSequenceClassification"
5
  ],
 
21
  "position_embedding_type": "absolute",
22
  "problem_type": "single_label_classification",
23
  "torch_dtype": "float32",
24
+ "transformers_version": "4.32.0.dev0",
25
  "type_vocab_size": 1,
26
  "use_cache": true,
27
  "vocab_size": 50265
confirmTrain.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification, Trainer, TrainingArguments
2
+ from datasets import Dataset, load_from_disk, concatenate_datasets
3
+ import os
4
+ import torch
5
+ import numpy as np
6
+ from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix
7
+
8
+ MODEL_NAME = "roberta-large"
9
+ SAVE_MODEL_FOLDER = "img_intents_model"
10
+ OUTPUT_DIR = "./results"
11
+ NEG_NAME = "NEGATIVE"
12
+ POS_NAME = "POSITIVE"
13
+
14
+ # Load the model and tokenizer
15
+ model = AutoModelForSequenceClassification.from_pretrained(SAVE_MODEL_FOLDER)
16
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
17
+
18
+ # Load the training arguments
19
+ training_args = torch.load(os.path.join(OUTPUT_DIR, "training_args.bin"))
20
+
21
+ # Load the sentences from the text files into lists
22
+ with open('test_positives.txt', 'r') as file:
23
+ positives_texts = [line.strip() for line in file.readlines()]
24
+ with open('test_negatives.txt', 'r') as file:
25
+ negatives_texts = [line.strip() for line in file.readlines()]
26
+
27
+ # Create datasets from the lists and add a 'label' column
28
+ positives_dataset = Dataset.from_dict({'text': positives_texts, 'label': [1]*len(positives_texts)})
29
+ negatives_dataset = Dataset.from_dict({'text': negatives_texts, 'label': [0]*len(negatives_texts)})
30
+
31
+ # Combine into a single dataset
32
+ test_dataset = concatenate_datasets([positives_dataset, negatives_dataset])
33
+
34
+ # Preprocessing function
35
+ def preprocess_function(examples):
36
+ # Tokenize the texts
37
+ return tokenizer(examples["text"], truncation=True, max_length=512, padding='max_length')
38
+
39
+ test_dataset = test_dataset.map(preprocess_function, batched=True)
40
+
41
+ # Make sure all your tensors are the same size for batching together
42
+ test_dataset = test_dataset.remove_columns(["text"]).rename_column("label", "labels").with_format("torch")
43
+
44
+ # Create the Trainer object
45
+ trainer = Trainer(
46
+ model=model,
47
+ args=training_args,
48
+ )
49
+
50
+ # Evaluate the model and save predictions and labels
51
+ predictions, labels, _ = trainer.predict(test_dataset)
52
+
53
+ # Convert predictions to binary (0 or 1)
54
+ binary_predictions = np.argmax(predictions, axis=1)
55
+
56
+ # Print overall metrics
57
+ accuracy = accuracy_score(labels, binary_predictions)
58
+ precision = precision_score(labels, binary_predictions)
59
+ recall = recall_score(labels, binary_predictions)
60
+ f1 = f1_score(labels, binary_predictions)
61
+
62
+ print(f"Overall accuracy: {accuracy}")
63
+ print(f"Overall precision: {precision}")
64
+ print(f"Overall recall: {recall}")
65
+ print(f"Overall F1 score: {f1}")
66
+
67
+ # Print the report for each class
68
+ cm = confusion_matrix(labels, binary_predictions)
69
+
70
+ for i, class_name in enumerate([NEG_NAME, POS_NAME]):
71
+ total = cm[i].sum()
72
+ correct = cm[i][i]
73
+ loss = total - correct
74
+
75
+ print(f"\n{class_name}:")
76
+ print(f"Total: {total}")
77
+ print(f"Confirmed: {correct}")
78
+ print(f"Loss: {loss} ({loss / total * 100:.2f}%)")
events.out.tfevents.1690445575.DESKTOP-HMQHN82.32493.0 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3b6c685b93f5d55fd18eabefb6dccf600c9d603bd2fecbb5dab6845e115284ff
3
+ size 4775
fineTune.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification, Trainer, TrainingArguments
2
+ from datasets import load_dataset, concatenate_datasets
3
+
4
+ MODEL_NAME = "roberta-large"
5
+ SAVE_MODEL_FOLDER = "img_intents_model"
6
+ OUTPUT_DIR = "./results"
7
+ output_dir = "/results"
8
+
9
+ # Load the model and tokenizer
10
+ model = AutoModelForSequenceClassification.from_pretrained(SAVE_MODEL_FOLDER)
11
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
12
+
13
+ # Load the sentences from the text files into datasets
14
+ positives_dataset = load_dataset('text', data_files='test_positives.txt')
15
+ negatives_dataset = load_dataset('text', data_files='test_negatives.txt')
16
+
17
+ # Manually assign split names to the datasets
18
+ positives_dataset = positives_dataset['train'].map(lambda example: {'label': 1})
19
+ negatives_dataset = negatives_dataset['train'].map(lambda example: {'label': 0})
20
+
21
+ # Combine into a single dataset and add a 'label' column
22
+ train_dataset = concatenate_datasets([positives_dataset, negatives_dataset])
23
+
24
+ # Preprocessing function
25
+ def preprocess_function(examples):
26
+ # Tokenize the texts
27
+ return tokenizer(examples["text"], truncation=True, max_length=512, padding='max_length')
28
+
29
+ train_dataset = train_dataset.map(preprocess_function, batched=True)
30
+
31
+ # Make sure all your tensors are the same size for batching together
32
+ train_dataset = train_dataset.remove_columns(["text"]).rename_column("label", "labels").with_format("torch")
33
+
34
+ # TrainingArguments
35
+ training_args = TrainingArguments(
36
+ output_dir=OUTPUT_DIR,
37
+ num_train_epochs=5, # Fine-tune for a few epochs
38
+ per_device_train_batch_size=16, # Decrease this if necessary
39
+ per_device_eval_batch_size=64,
40
+ warmup_steps=500,
41
+ weight_decay=0.01,
42
+ logging_dir=OUTPUT_DIR,
43
+ logging_strategy='steps', # Log after every training step
44
+ logging_steps=10, # Adjust this to change how often logging occurs
45
+ evaluation_strategy='steps', # Evaluate after every training step
46
+ eval_steps=100, # Adjust this to change how often evaluation occurs
47
+ save_strategy='steps', # Save after every training step
48
+ save_steps=500, # Adjust this to change how often saving occurs
49
+ no_cuda=False, # Use GPU
50
+ gradient_accumulation_steps=2, # If necessary
51
+ fp16=True, # Use mixed precision training
52
+ report_to='tensorboard'
53
+ )
54
+ # Create a Trainer
55
+ trainer = Trainer(
56
+ model=model,
57
+ args=training_args,
58
+ train_dataset=train_dataset,
59
+ )
60
+
61
+ # Fine-tune the model
62
+ trainer.train()
63
+
64
+ # Save the model
65
+ trainer.save_model(SAVE_MODEL_FOLDER)
66
+
67
+ # Save the tokenizer
68
+ tokenizer.save_pretrained(OUTPUT_DIR)
img_intents.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import random
2
+ from datasets import Dataset, DatasetDict
3
+ import pandas as pd
4
+
5
+ # Load positive examples from 'Positives.txt'
6
+ with open('Positives.txt', 'r') as file:
7
+ positive_examples = [line.strip() for line in file.readlines()]
8
+
9
+ # Load negative examples from 'Negatives.txt'
10
+ with open('Negatives.txt', 'r') as file:
11
+ negative_examples = [line.strip() for line in file.readlines()]
12
+
13
+ # Shuffle and combine positive and negative examples
14
+ all_examples = [(example, 'POSITIVE') for example in positive_examples] + [(example, 'NEGATIVE') for example in negative_examples]
15
+ random.shuffle(all_examples)
16
+
17
+ # Convert to pandas DataFrame
18
+ df = pd.DataFrame(all_examples, columns=['text', 'label'])
19
+
20
+ # Split the dataset if desired (e.g., 80% train, 10% validation, 10% test)
21
+ train_size = int(0.8 * len(df))
22
+ val_size = int(0.1 * len(df))
23
+ train_examples = df[:train_size]
24
+ val_examples = df[train_size: train_size + val_size]
25
+ test_examples = df[train_size + val_size:]
26
+
27
+ # Save the dataset to CSV format with 'split' column
28
+ import csv
29
+
30
+ train_examples['split'] = 'train'
31
+ val_examples['split'] = 'validation'
32
+ test_examples['split'] = 'test'
33
+
34
+ with open('dataset_with_split.csv', 'w', newline='', encoding='utf-8') as csvfile:
35
+ csvwriter = csv.writer(csvfile)
36
+ csvwriter.writerow(['text', 'label', 'split']) # Write header
37
+ csvwriter.writerows(train_examples.values.tolist()) # Write train examples
38
+ csvwriter.writerows(val_examples.values.tolist()) # Write validation examples
39
+ csvwriter.writerows(test_examples.values.tolist()) # Write test examples
40
+
41
+ print("Dataset with 'split' column created successfully.")
42
+
43
+ # Load the dataset from the CSV file
44
+ dataset = Dataset.from_csv('dataset_with_split.csv')
45
+
46
+ # Create a DatasetDict object containing train, validation, and test datasets
47
+ datasets = DatasetDict({
48
+ 'train': dataset.filter(lambda example: example['split'] == 'train'),
49
+ 'validation': dataset.filter(lambda example: example['split'] == 'val'),
50
+ 'test': dataset.filter(lambda example: example['split'] == 'test'),
51
+ })
52
+
53
+ # Optional: Define dataset metadata
54
+ dataset_info = {
55
+ "name": "img_intents",
56
+ "description": "A dataset of positive and negative examples",
57
+ "citation": "Provide the citation or source of the dataset",
58
+ "homepage": "Link to the dataset homepage",
59
+ }
60
+
pytorch_model.bin CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:f1ff2702abff612a3c3aadfbfaae3ecc5e54b0203d92f0c94f7e3b38b559cbf0
3
  size 1421582769
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bf5d6bcff602ec06c6251c09acf42c6a6e3039a782060be4accd9a5a0c723d42
3
  size 1421582769
test.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification
3
+
4
+ MODEL_DIR = "img_intents_model"
5
+ TOKENIZER_NAME = "./results"
6
+
7
+ # Load the trained model
8
+ model = AutoModelForSequenceClassification.from_pretrained(MODEL_DIR)
9
+
10
+ # Load the tokenizer
11
+ tokenizer = AutoTokenizer.from_pretrained(TOKENIZER_NAME)
12
+
13
+ while True:
14
+ # Get the input from the command line
15
+ input_text = input("Enter a message to classify (or 'q' to quit): ")
16
+
17
+ if input_text.lower() == 'q':
18
+ break
19
+
20
+ # Encode the input and convert it to a torch tensor
21
+ inputs = tokenizer.encode_plus(input_text, return_tensors='pt')
22
+
23
+ # Get the model's prediction
24
+ outputs = model(**inputs)
25
+
26
+ # Get the predicted class from the model's output
27
+ predicted_class = torch.argmax(outputs.logits).item()
28
+
29
+ if predicted_class == 1:
30
+ print("The message is predicted as an image intent.")
31
+ else:
32
+ print("The message is not predicted as an image intent.")
test_negatives.txt ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Hey, how's it going?
2
+ U up for a movie tonight?
3
+ What's the weather like tmrw?
4
+ Can't make it to the party, sorry.
5
+ Did u finish the assignment?
6
+ Hey, just wanted to check on you. How have you been?
7
+ Did you hear about the latest update on the app?
8
+ I hope everything is going well on your end.
9
+ Could we possibly reschedule our meeting for tomorrow?
10
+ Just a quick reminder about our lunch date.
11
+ Hey, did you manage to catch the latest episode?
12
+ I've been thinking about taking a vacation. Any recommendations?
13
+ How's the new job going? Must be exciting!
14
+ Remember our trip last summer? Good times!
15
+ Been a while since we caught up. Coffee soon?
16
+ Good day. I hope this message finds you well.
17
+ I regret to inform you of a delay in the project.
18
+ Thank you for your prompt response to our previous correspondence.
19
+ Could you kindly provide an update on the matter?
20
+ I appreciate your assistance in this matter.
21
+ Did you know that honey never spoils?
22
+ I've recently taken up reading as a hobby. It's quite relaxing.
23
+ The concert last night was absolutely phenomenal.
24
+ I've always been fascinated by the stars and constellations.
25
+ Nature walks have a therapeutic effect, don't you think?
26
+ I've been feeling a bit under the weather lately.
27
+ Did you hear about the new restaurant downtown?
28
+ Trust the process, everything will fall into place.
29
+ Books are a uniquely portable magic.
30
+ The world is full of endless possibilities.
31
+ How's your family doing?
32
+ I've been thinking of adopting a pet. What do you think?
33
+ Music is such a powerful form of expression.
34
+ There's a meteor shower happening next week.
35
+ Did you hear about the recent developments in the tech world?
36
+ Life has a way of surprising us when we least expect it.
37
+ The movie last night was a roller coaster of emotions.
38
+ Have you ever tried meditation?
39
+ I've been meaning to learn a new language. It's never too late, right?
40
+ Nature is truly the best artist.
41
+ R u going to the concert tonight?
42
+ What's the homework for tomorrow?
43
+ Did u see the new episode last night?
44
+ Pizza for dinner?
45
+ U seen my keys?
46
+ Could we possibly move the meeting to Friday?
47
+ Did you manage to get the tickets for the game?
48
+ Hope everything is well with you.
49
+ Don't forget about our trip next week!
50
+ Just a reminder about the appointment tomorrow.
51
+ Hey, did you watch the football match yesterday?
52
+ Been thinking about starting a new hobby. Any ideas?
53
+ How's the new course you signed up for?
54
+ Remember the high school days? So nostalgic!
55
+ Been a while since our last road trip. We should plan one soon.
56
+ Dear Sir, I hope this message finds you in good health.
57
+ Regrettably, there will be a delay in the delivery.
58
+ Thank you for your prompt attention to this matter.
59
+ Could you kindly provide an update on the project?
60
+ I appreciate your patience in this matter.
61
+ Ever tried bungee jumping? It's quite an adrenaline rush.
62
+ I've recently started a book club. You should join!
63
+ The new art exhibition downtown is quite impressive.
64
+ I've always found the ocean to be quite calming.
65
+ There's something magical about a good cup of coffee, don't you think?
test_positives.txt ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Hey, got any pics of dogs? Need one for a project.
2
+ Can u find a pic of the Grand Canyon? Wanna use it as a wallpaper.
3
+ I need a graphic of the solar system for my presentation. Can u help?
4
+ Hey, can u get me a pic of a beach sunset? Need it for a collage.
5
+ Show me a picture of a Ferrari, wanna show my friends.
6
+ Could you find an image of a beautiful waterfall for me? Thanks!
7
+ I'm looking for a photo of a bustling cityscape. Could you assist?
8
+ Could you please locate a picture of the Sydney Opera House for me?
9
+ I need a graphic of the human skeleton for my study, could you help?
10
+ I'm searching for a photo of a coral reef. Can you assist?
11
+ Hey, I'm looking for a cool pic of a sports car. Can you find one?
12
+ I'm in need of a picture of a blue whale. Can you help me out?
13
+ Hey, could you find a photo of a rainbow for me? Would really appreciate it.
14
+ I'm after a graphic of a world map. Can you help?
15
+ Can you find a photo of a tropical island for me? Thanks in advance!
16
+ Could you please provide an image of the Eiffel Tower?
17
+ I require a picture of a beautiful garden for my project.
18
+ Could you assist in locating a photograph of the Great Wall of China?
19
+ I'm in need of a graphic of the human brain for my research. Could you assist?
20
+ Could you please locate a picture of the Northern Lights for me?
21
+ I need an image of a serene lake. Can you assist?
22
+ Could you provide a graphic of the universe?
23
+ I'm looking for a pic of a wild animal. Can you help?
24
+ Can you find a photo of a bustling cityscape for me?
25
+ I need a picture of an elephant. Can you assist?
26
+ Can you fetch me a photo of a delicious meal?
27
+ Could you help me locate a picture of a medieval castle?
28
+ I'm searching for a photo of a scenic landscape. Can you assist?
29
+ Can you find a graphic of a human heart for me?
30
+ I'm after a picture of a tranquil forest. Can you help me out?
31
+ Yo, got a pic of a golden retriever? Need it for a meme.
32
+ U got a photo of the Pyramids of Giza? Need it for a report.
33
+ Need a graphic of the Milky Way for my project. Can u help?
34
+ Hey, can u find me a pic of a snowy mountain? Need it for a mood board.
35
+ Show me a picture of a Lamborghini, wanna make my friends jealous.
36
+ Could you find an image of cherry blossoms for me? Thanks!
37
+ I'm looking for a photo of a lively marketplace. Could you assist?
38
+ Could you please locate a picture of the Colosseum for me?
39
+ I need a graphic of the human body for my study, could you help?
40
+ I'm searching for a photo of a desert. Can you assist?
41
+ Hey, I'm looking for a cool pic of a yacht. Can you find one?
42
+ I'm in need of a picture of a grizzly bear. Can you help me out?
43
+ Hey, could you find a photo of a lightning strike for me? Would really appreciate it.
44
+ I'm after a graphic of the solar system. Can you help?
45
+ Can you find a photo of a bustling street for me? Thanks in advance!
46
+ Could you please provide an image of the Leaning Tower of Pisa?
47
+ I require a picture of a serene river for my project.
48
+ Could you assist in locating a photograph of the Amazon rainforest?
49
+ I'm in need of a graphic of the human digestive system for my research. Could you assist?
50
+ Could you please locate a picture of a glacier for me?
51
+ I need an image of a bustling airport. Can you assist?
52
+ Could you provide a graphic of the Earth's crust?
53
+ I'm looking for a pic of a majestic lion. Can you help?
54
+ Can you find a photo of a crowded concert for me?
55
+ I need a picture of a giraffe. Can you assist?
56
+ Can you fetch me a photo of a scrumptious pizza?
57
+ Could you help me locate a picture of a haunted house?
58
+ I'm searching for a photo of a rolling hillside. Can you assist?
59
+ Can you find a graphic of the human nervous system for me?
60
+ I'm after a picture of a tranquil beach. Can you help me out?
tokenizer.json CHANGED
@@ -1,21 +1,7 @@
1
  {
2
  "version": "1.0",
3
- "truncation": {
4
- "direction": "Right",
5
- "max_length": 512,
6
- "strategy": "LongestFirst",
7
- "stride": 0
8
- },
9
- "padding": {
10
- "strategy": {
11
- "Fixed": 512
12
- },
13
- "direction": "Right",
14
- "pad_to_multiple_of": null,
15
- "pad_id": 1,
16
- "pad_type_id": 0,
17
- "pad_token": "<pad>"
18
- },
19
  "added_tokens": [
20
  {
21
  "id": 0,
 
1
  {
2
  "version": "1.0",
3
+ "truncation": null,
4
+ "padding": null,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
  "added_tokens": [
6
  {
7
  "id": 0,
train.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification, Trainer, TrainingArguments
2
+ from datasets import Dataset, DatasetDict, load_from_disk, concatenate_datasets
3
+ import torch
4
+ import os
5
+ import tensorflow as tf
6
+
7
+ OUTPUT_DIR = "./results"
8
+ DATASET_NAME = 'dataset_with_split.csv'
9
+ MODEL_NAME = "roberta-large"
10
+ LOG_DIR = "./logs"
11
+ SAVE_MODEL_FOLDER = "img_intents_model"
12
+
13
+ POS_NAME = "POSITIVE"
14
+ NEG_NAME = "NEGATIVE"
15
+
16
+
17
+ BATCH_SIZE_TRAIN = 16
18
+ BATCH_SIZE_EVAL = 64
19
+ EPOCS = 10
20
+ WARMUP_STEPS = 500
21
+
22
+
23
+ tf.debugging.experimental.enable_dump_debug_info(
24
+ LOG_DIR,
25
+ tensor_debug_mode="FULL_HEALTH",
26
+ circular_buffer_size=1000,
27
+ op_regex=None,
28
+ tensor_dtypes=None
29
+ )
30
+
31
+ # Load the dataset from the CSV file
32
+ dataset = Dataset.from_csv(DATASET_NAME)
33
+
34
+ # Create a DatasetDict object containing train, validation, and test datasets
35
+ datasets = DatasetDict({
36
+ 'train': dataset.filter(lambda example: example['split'] == 'train'),
37
+ 'validation': dataset.filter(lambda example: example['split'] == 'validation'),
38
+ 'test': dataset.filter(lambda example: example['split'] == 'test'),
39
+ })
40
+
41
+ # Balance the datasets
42
+ for split in datasets.keys():
43
+ num_positive = len(datasets[split].filter(lambda example: example['label'] == POS_NAME))
44
+ num_negative = len(datasets[split].filter(lambda example: example['label'] == NEG_NAME))
45
+
46
+ if num_positive > num_negative:
47
+ # Downsample the positive examples
48
+ datasets[split] = concatenate_datasets([
49
+ datasets[split].filter(lambda example: example['label'] == POS_NAME).shuffle(seed=42).select(range(num_negative)),
50
+ datasets[split].filter(lambda example: example['label'] == NEG_NAME)
51
+ ])
52
+ else:
53
+ # Downsample the negative examples
54
+ datasets[split] = concatenate_datasets([
55
+ datasets[split].filter(lambda example: example['label'] == POS_NAME),
56
+ datasets[split].filter(lambda example: example['label'] == NEG_NAME).shuffle(seed=42).select(range(num_positive))
57
+ ])
58
+
59
+ # Shuffle the dataset to mix positive and negative examples
60
+ datasets[split] = datasets[split].shuffle(seed=42)
61
+
62
+ # Specify the model name
63
+ model_name = MODEL_NAME # Or whatever model you want to use
64
+
65
+ # Load the tokenizer associated with your model
66
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
67
+
68
+ # Load your datasets
69
+ train_dataset = datasets['train']
70
+ val_dataset = datasets['validation']
71
+ test_dataset = datasets['test']
72
+
73
+ # Preprocessing function
74
+ def preprocess_function(examples):
75
+ # Replace None in 'text' field with an empty string
76
+ examples["text"] = [text if text is not None else "" for text in examples["text"]]
77
+
78
+ # Convert labels from string to int
79
+ examples["label"] = [1 if label == POS_NAME else 0 for label in examples["label"]]
80
+
81
+ # Tokenize the texts
82
+ return tokenizer(examples["text"], truncation=True, max_length=512, padding='max_length')
83
+
84
+ train_dataset = train_dataset.map(preprocess_function, batched=True)
85
+ val_dataset = val_dataset.map(preprocess_function, batched=True)
86
+ test_dataset = test_dataset.map(preprocess_function, batched=True)
87
+
88
+ # Make sure all your tensors are the same size for batching together
89
+ train_dataset = train_dataset.remove_columns(["text"]).rename_column("label", "labels").with_format("torch")
90
+ val_dataset = val_dataset.remove_columns(["text"]).rename_column("label", "labels").with_format("torch")
91
+ test_dataset = test_dataset.remove_columns(["text"]).rename_column("label", "labels").with_format("torch")
92
+
93
+ # Load a pre-trained model for sequence classification
94
+ model = AutoModelForSequenceClassification.from_pretrained(model_name, num_labels=2) # You have two labels: POSITIVE and NEGATIVE
95
+
96
+ # TrainingArguments
97
+ training_args = TrainingArguments(
98
+ output_dir=OUTPUT_DIR,
99
+ num_train_epochs=EPOCS,
100
+ per_device_train_batch_size=BATCH_SIZE_TRAIN, # decrease this if necessary
101
+ per_device_eval_batch_size=BATCH_SIZE_EVAL,
102
+ warmup_steps=WARMUP_STEPS,
103
+ weight_decay=0.01,
104
+ logging_dir=LOG_DIR,
105
+ logging_strategy='steps', # Log after every training step
106
+ logging_steps=10, # Adjust this to change how often logging occurs
107
+ evaluation_strategy='steps', # Evaluate after every training step
108
+ eval_steps=100, # Adjust this to change how often evaluation occurs
109
+ save_strategy='steps', # Save after every training step
110
+ save_steps=500, # Adjust this to change how often saving occurs
111
+ no_cuda=False, # use GPU
112
+ gradient_accumulation_steps=2, # if necessary
113
+ fp16=True, # use mixed precision training
114
+ report_to='tensorboard'
115
+ )
116
+
117
+ # Create a Trainer
118
+ trainer = Trainer(
119
+ model=model,
120
+ args=training_args,
121
+ train_dataset=train_dataset,
122
+ eval_dataset=val_dataset,
123
+ )
124
+
125
+ # Train the model
126
+ trainer.train()
127
+
128
+ # Save the model
129
+ trainer.save_model(SAVE_MODEL_FOLDER)
130
+
131
+ # Save the tokenizer
132
+ tokenizer.save_pretrained(OUTPUT_DIR)
133
+
134
+ # Save the training arguments
135
+ torch.save(training_args, os.path.join(OUTPUT_DIR, "training_args.bin"))
136
+
137
+ # Evaluate the model and print the results
138
+ eval_results = trainer.evaluate(test_dataset)
139
+ print(f"Test set evaluation results: {eval_results}")
training_args.bin CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:99cb2d4f988e976319f712a4a50a4eb0e7485053e6ce66f46cd8987070543c66
3
  size 3899
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8434cb556cc1edbd48d4ac1a3f3ec0b1e09492c025297d4c4ef93d53462acec8
3
  size 3899