-
Notifications
You must be signed in to change notification settings - Fork 0
4 random sampling #13
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
J-Dymond
wants to merge
8
commits into
main
Choose a base branch
from
4-random-sampling
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 6 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
06e2ca5
shifted some functions around to tidy up repo
J-Dymond d322190
WIP EDA script
J-Dymond 9290034
numpy typing
jack89roberts a096581
eda script which pulls out the most common words, entropies, and soft…
J-Dymond 3f11963
Merge remote-tracking branch 'refs/remotes/origin/4-random-sampling' …
J-Dymond 0f1e1a7
added functionality of imbalancing classes the other way in random_sa…
J-Dymond 023d330
dataset imbalancing now happens in get_reddit_data
J-Dymond 2d01b48
Merge branch 'main' into 4-random-sampling
J-Dymond File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
data_name: reddit_dataset_12 | ||
data_args: | ||
n_rows: 15000 | ||
setting: multi-class | ||
target_config: sport | ||
balanced: True |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
model_id: "tomaarsen/glove-wikipedia-tf-idf" | ||
model_kwargs: | ||
num_labels: 2 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file was deleted.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,125 @@ | ||
import argparse | ||
import json | ||
import os | ||
from collections import Counter | ||
|
||
import matplotlib.pyplot as plt | ||
import numpy as np | ||
from tqdm import tqdm | ||
|
||
from arc_tigers.data.reddit_data import get_reddit_data | ||
from arc_tigers.utils import load_yaml | ||
|
||
|
||
def main(args): | ||
counter_dict = { | ||
"all": Counter(), | ||
"correct": {0: Counter(), 1: Counter()}, | ||
"incorrect": {0: Counter(), 1: Counter()}, | ||
} | ||
experiment_dir = args.experiment_dir | ||
|
||
eval_stats = os.path.join(experiment_dir, "stats_full.json") | ||
with open(eval_stats) as f: | ||
eval_data = json.load(f) | ||
|
||
accuracy_vector = np.array(eval_data["accuracy"]) | ||
entropy_vector = np.array(eval_data["entropy"]) | ||
softmax_vector = np.array(eval_data["softmax"]) | ||
n_classes = softmax_vector.shape[1] | ||
|
||
softmax_probs = np.max(softmax_vector, axis=1) | ||
normalised_entropy = entropy_vector / np.log(n_classes) | ||
|
||
correct_indices = np.concatenate(np.argwhere(accuracy_vector == 1)) | ||
incorrect_indices = np.concatenate(np.argwhere(accuracy_vector == 0)) | ||
|
||
correct_softmax = softmax_probs[correct_indices] | ||
incorrect_softmax = softmax_probs[incorrect_indices] | ||
correct_entropy = normalised_entropy[correct_indices] | ||
incorrect_entropy = normalised_entropy[incorrect_indices] | ||
|
||
plt.hist(correct_softmax, bins=100, alpha=0.5, label="correct") | ||
plt.hist(incorrect_softmax, bins=100, alpha=0.5, label="incorrect") | ||
plt.yscale("log") | ||
plt.xlabel("Predicted Softmax") | ||
plt.ylabel("Counts") | ||
plt.legend(title="Prediction type") | ||
plt.savefig(experiment_dir + "/softmax_histogram.pdf") | ||
plt.clf() | ||
|
||
plt.hist(correct_entropy, bins=100, alpha=0.5, label="correct") | ||
plt.hist(incorrect_entropy, bins=100, alpha=0.5, label="incorrect") | ||
plt.yscale("log") | ||
plt.xlabel("Normalised Predicted Entropy") | ||
plt.ylabel("Counts") | ||
plt.legend(title="Prediction type") | ||
plt.savefig(experiment_dir + "/entropy_histogram.pdf") | ||
plt.clf() | ||
|
||
exp_config = os.path.join(experiment_dir, "../experiment_config.json") | ||
with open(exp_config) as f: | ||
exp_config = json.load(f) | ||
data_config = load_yaml(exp_config["data_config_pth"]) | ||
_, _, test_data, meta_data = get_reddit_data( | ||
**data_config["data_args"], random_seed=exp_config["seed"], tokenizer=None | ||
) | ||
subreddit_label_map: dict[str, int] = meta_data["test_target_map"] | ||
label_subreddit_map: dict[int, str] = {v: k for k, v in subreddit_label_map.items()} | ||
|
||
for input in test_data["text"]: | ||
counter_dict["all"].update(input.split()) | ||
|
||
correct_inputs = test_data[correct_indices]["text"] | ||
correct_labels = test_data[correct_indices]["label"] | ||
|
||
incorrect_inputs = test_data[incorrect_indices]["text"] | ||
incorrect_labels = test_data[incorrect_indices]["label"] | ||
|
||
for label, inp in tqdm(zip(incorrect_labels, incorrect_inputs, strict=True)): | ||
counter_dict["incorrect"][label].update(inp.split()) | ||
|
||
for label, inp in tqdm(zip(correct_labels, correct_inputs, strict=True)): | ||
counter_dict["correct"][label].update(inp.split()) | ||
|
||
# remove the top 50 frequent words from the all counter | ||
most_common_words = counter_dict["all"].most_common(100) | ||
for word, _ in most_common_words: | ||
for counter in counter_dict["correct"].values(): | ||
if word in counter: | ||
counter.pop(word) | ||
for counter in counter_dict["incorrect"].values(): | ||
if word in counter: | ||
counter.pop(word) | ||
|
||
for class_label in range(n_classes): | ||
fig, axes = plt.subplots(2, 1, figsize=(15, 5)) | ||
for ax_idx, acc in enumerate(["incorrect", "correct"]): | ||
# print(f"Most common words in {acc} inputs:") | ||
# print(label_subreddit_map[class_label]) | ||
# print(counter_dict[acc][class_label].most_common(50)) | ||
top_50 = counter_dict[acc][class_label].most_common(50) | ||
words, counts = zip(*top_50, strict=True) | ||
x_pos = np.arange(len(words)) | ||
axes[ax_idx].set_title(f"{acc} inputs") | ||
axes[ax_idx].bar(x_pos, counts, align="center") | ||
axes[ax_idx].set_xticks(x_pos, words, rotation=70) | ||
axes[ax_idx].set_ylabel("Counts") | ||
axes[ax_idx].set_xlabel("Words") | ||
fig.tight_layout() | ||
fig.savefig( | ||
experiment_dir | ||
+ f"/{label_subreddit_map[class_label].lstrip('r/')}_word_counts.pdf" | ||
) | ||
fig.clear() | ||
|
||
|
||
if __name__ == "__main__": | ||
parser = argparse.ArgumentParser( | ||
description="Evaluate an experiment and save outputs." | ||
) | ||
parser.add_argument( | ||
"experiment_dir", type=str, help="Path to the experiment directory." | ||
) | ||
args = parser.parse_args() | ||
main(args) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ideally I think changing the imbalance would be handled in the data scripts, and not the sampling script
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Would we want different levels of imbalance when training? And would this just be in the binary case?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Basically I just think that as far as the sampling script is concerned the dataset logic shouldn't be much more than
test_data = load_dataset(config)
or similar. We may want the option of imbalance in the training splits too, but that's separate to anything to do with this script (apart from making sure the test data doesn't overlap with the training data).There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I've made a change now to reflect this
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
In
arc_tigers.data.get_reddit_data
Ifbalanced
isFalse
, it checks for aclass_balance
argument and uses that to imbalance the train and test splits.