Spaces:
Sleeping
Sleeping
File size: 45,667 Bytes
3139db4 3cff715 33e257e 3cff715 3139db4 3cff715 33e257e |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 |
<<<<<<< HEAD
<<<<<<< HEAD
=======
>>>>>>> 5058aea (Problems)
from datasets import load_dataset
import shutil
import json
from collections import defaultdict
import multiprocessing
import gensim
from sklearn.metrics import classification_report
from gensim import corpora
from gensim.test.utils import common_texts
from gensim.models import Word2Vec
from gensim.models import KeyedVectors
from gensim.models import fasttext
from gensim.test.utils import datapath
from wefe.datasets import load_bingliu
from wefe.metrics import RNSB
from wefe.query import Query
from wefe.word_embedding_model import WordEmbeddingModel
from wefe.utils import plot_queries_results, run_queries
import pandas as pd
import gensim.downloader as api
import glob
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.ensemble import RandomForestClassifier
from wefe.metrics import WEAT
from wefe.datasets import load_weat
from wefe.utils import run_queries
from wefe.utils import plot_queries_results
import random
from scipy.special import expit
import math
import sys
import os
import argparse
import nltk
import scipy.sparse
import numpy as np
import string
import io
from sklearn.model_selection import train_test_split
'''STEPS FOR CODE:
1. Train word embeddings on Simple English Wikipedia;
2. Compare these to other pre-trained embeddings;
3. Quantify biases that exist in these word embeddings;
4. Use your word embeddings as features in a simple text classifier;
'''
def load_vectors(fname):
fin = io.open(fname, 'r', encoding='utf-8', newline='\n', errors='ignore')
n, d = map(int, fin.readline().split())
data = {}
# print("Hello", n, d)
for line in fin:
tokens = line.rstrip().split(' ')
data[tokens[0]] = map(float, tokens[1:])
# print(data)
print(data)
return data
def train_embeddings():
'''TRAIN WORD EMBEDDINGS
This will be making use of the dataset from wikipedia and the first step'''
dataset = load_dataset("wikipedia", "20220301.simple")
cores = multiprocessing.cpu_count()
# check the first example of the training portion of the dataset :
# print(dataset['train'][0])
dataset_size = len(dataset)
### BUILD VOCAB ###
# print(type(dataset["train"][0]))
vocab = set()
vocab_size = 0
count = 0
## Generate vocab and split sentances and words?
data = []
for index, page in enumerate(dataset["train"]):
document = page["text"]
document = document.replace("\n", ". ")
# print(document)
for sent in document.split("."):
# print("Sentance:", sent)
new_sent = []
clean_sent =[s for s in sent if s.isalnum() or s.isspace()]
clean_sent = "".join(clean_sent)
for word in clean_sent.split(" "):
if len(word) > 0:
new_word = word.lower()
# print("Word:", new_word)
if new_word[0] not in string.punctuation:
new_sent.append(new_word)
if len(new_sent) > 0:
data.append(new_sent)
# print("New Sent:", new_sent)
for index, page in enumerate(dataset["train"]):
# print(page["text"])
# for text in page:
# print(text)
text = page["text"]
clean_text = [s for s in text if s.isalnum() or s.isspace()]
clean_text = "".join(clean_text)
clean_text = clean_text.replace("\n", " ")
# text = text.replace('; ', ' ').replace(", ", " ").replace("\n", " ").replace(":", " ").replace(". ", " ").replace("! ", " ").replace("? ", " ").replace()
for word in clean_text.split(" "):
# print(word)
if word != "\n" and word != " " and word not in vocab:
vocab.add(word)
vocab_size += 1
# if index == 10:
# break
# print(f"word #{index}/{count} is {word}")
count += 1
# print(f"There are {vocab_size} vocab words")
embeddings_model = Word2Vec(
data,
epochs= 10,
window=10,
vector_size= 50)
embeddings_model.save("word2vec.model")
skip_model = Word2Vec(
data,
epochs= 10,
window=10,
vector_size= 50,
sg=1)
skip_model.save("skip2vec.model")
embeddings_model = Word2Vec.load("word2vec.model")
skip_model = Word2Vec.load("skip2vec.model")
# embeddings_model.train(dataset, total_examples=dataset_size, epochs=15)
# print(embeddings_model['train'])
# print(embeddings_model.wv["france"])
return embeddings_model, skip_model
def get_data():
dataset = load_dataset("wikipedia", "20220301.simple")
cores = multiprocessing.cpu_count()
# check the first example of the training portion of the dataset :
# print(dataset['train'][0])
dataset_size = len(dataset)
### BUILD VOCAB ###
# print(type(dataset["train"][0]))
vocab = set()
vocab_size = 0
count = 0
## Generate vocab and split sentances and words?
data = []
num_sents = 0
for index, page in enumerate(dataset["train"]):
document = page["text"]
document = document.replace("\n", ". ")
# print(document)
for sent in document.split("."):
num_sents += 1
# print("Sentance:", sent)
new_sent = []
clean_sent =[s for s in sent if s.isalnum() or s.isspace()]
clean_sent = "".join(clean_sent)
for word in clean_sent.split(" "):
if len(word) > 0:
new_word = word.lower()
# print("Word:", new_word)
if new_word[0] not in string.punctuation:
new_sent.append(new_word)
if len(new_sent) > 0:
data.append(new_sent)
# print("New Sent:", new_sent)
return data, num_sents
def compare_embeddings(cbow, skip, urban, fasttext):
'''COMPARE EMBEDDINGS'''
print("Most Similar to dog")
print("cbow", cbow.wv.most_similar(positive=['dog'], negative=[], topn=2))
print("skip", skip.wv.most_similar(positive=['dog'], negative=[], topn=2))
print("urban", urban.most_similar(positive=['dog'], negative=[], topn=2))
print("fasttext", fasttext.most_similar(positive=['dog'], negative=[], topn=2))
print("\nMost Similar to Pizza - Pepperoni + Pretzel")
print("cbow", cbow.wv.most_similar(positive=['pizza', 'pretzel'], negative=['pepperoni'], topn=2))
print("skip", skip.wv.most_similar(positive=['pizza', 'pretzel'], negative=['pepperoni'], topn=2))
print("urban", urban.most_similar(positive=['pizza', 'pretzel'], negative=['pepperoni'], topn=2))
print("fasttext", fasttext.most_similar(positive=['pizza', 'pretzel'], negative=['pepperoni'], topn=2))
print("\nMost Similar to witch - woman + man")
print("cbow", cbow.wv.most_similar(positive=['witch', 'man'], negative=['woman'], topn=2))
print("skip", skip.wv.most_similar(positive=['witch', 'man'], negative=['woman'], topn=2))
print("urban", urban.most_similar(positive=['witch', 'man'], negative=['woman'], topn=2))
print("fasttext", fasttext.most_similar(positive=['witch', 'man'], negative=['woman'], topn=2))
print("\nMost Similar to mayor - town + country")
print("cbow", cbow.wv.most_similar(positive=['mayor', 'country'], negative=['town'], topn=2))
print("skip", skip.wv.most_similar(positive=['mayor', 'country'], negative=['town'], topn=2))
print("urban", urban.most_similar(positive=['mayor', 'country'], negative=['town'], topn=2))
print("fasttext", fasttext.most_similar(positive=['mayor', 'country'], negative=['town'], topn=2))
print("\nMost Similar to death")
print("cbow", cbow.wv.most_similar(positive=['death'], negative=[], topn=2))
print("skip", skip.wv.most_similar(positive=['death'], negative=[], topn=2))
print("urban", urban.most_similar(positive=['death'], negative=[], topn=2))
print("fasttext", fasttext.most_similar(positive=['death'], negative=[], topn=2))
def quantify_bias(cbow, skip, urban, fasttext):
'''QUANTIFY BIASES'''
'''Using WEFE, RNSB'''
RNSB_words = [
['christianity'],
['catholicism'],
['islam'],
['judaism'],
['hinduism'],
['buddhism'],
['mormonism'],
['scientology'],
['taoism']]
weat_wordset = load_weat()
models = [WordEmbeddingModel(cbow.wv, "CBOW"),
WordEmbeddingModel(skip.wv, "skip-gram"),
WordEmbeddingModel(urban, "urban dictionary"),
WordEmbeddingModel(fasttext, "fasttext")]
# Define the 10 Queries:
# print(weat_wordset["science"])
religions = ['christianity',
'catholicism',
'islam',
'judaism',
'hinduism',
'buddhism',
'mormonism',
'scientology',
'taoism',
'atheism']
queries = [
# Flowers vs Insects wrt Pleasant (5) and Unpleasant (5)
Query([religions, weat_wordset['arts']],
[weat_wordset['career'], weat_wordset['family']],
['Religion', 'Art'], ['Career', 'Family']),
Query([religions, weat_wordset['weapons']],
[weat_wordset['male_terms'], weat_wordset['female_terms']],
['Religion', 'Weapons'], ['Male terms', 'Female terms']),
]
wefe_results = run_queries(WEAT,
queries,
models,
metric_params ={
'preprocessors': [
{},
{'lowercase': True }
]
},
warn_not_found_words = True
).T.round(2)
print(wefe_results)
plot_queries_results(wefe_results).show()
def text_classifier(cbow):
'''SIMPLE TEXT CLASSIFIER'''
'''For each document, average together all embeddings for the
individual words in that document to get a new, d-dimensional representation
of that document (this is essentially a “continuous bag-of-words”). Note that
your input feature size is only d now, instead of the size of your entire vocabulary.
Compare the results of training a model using these “CBOW” input features to
your original (discrete) BOW model.'''
pos_train_files = glob.glob('aclImdb/train/pos/*')
neg_train_files = glob.glob('aclImdb/train/neg/*')
# print(pos_train_files[:5])
num_files_per_class = 1000
# bow_train_files = cbow
all_train_files = pos_train_files[:num_files_per_class] + neg_train_files[:num_files_per_class]
# vectorizer = TfidfVectorizer(input="filename", stop_words="english")
# vectors = vectorizer.fit_transform(all_train_files)
d = len(cbow.wv["man"])
vectors = np.empty([len(all_train_files), d])
count = 0
vocab = set()
for doc in all_train_files:
temp_array = avg_embeddings(doc, cbow, vocab)
if len(temp_array) > 0:
vectors[count] = temp_array
count += 1
else:
vectors = np.delete(vectors, count)
# vectors = np.array(avg_embeddings(doc, cbow) for doc in all_train_files)
# print(vectors)
# print(vocab)
# len(vectorizer.vocabulary_)
vectors[0].sum()
# print("Vector at 0", vectors[0])
X = vectors
y = [1] * num_files_per_class + [0] * num_files_per_class
len(y)
x_0 = X[0]
w = np.zeros(X.shape[1])
# x_0_dense = x_0.todense()
x_0.dot(w)
w,b = sgd_for_lr_with_ce(X,y)
# w
# sorted_vocab = sorted([(k,v) for k,v in vectorizer.vocabulary_.items()],key=lambda x:x[1])
sorted_vocab = sorted(vocab)
# sorted_vocab = [a for (a,b) in sorted_vocab]
sorted_words_weights = sorted([x for x in zip(sorted_vocab, w)], key=lambda x:x[1])
sorted_words_weights[-50:]
preds = predict_y_lr(w,b,X)
preds
w,b = sgd_for_lr_with_ce(X, y, num_passes=10)
y_pred = predict_y_lr(w,b,X)
print(classification_report(y, y_pred))
# compute for dev set
# pos_dev_files = glob.glob('aclImdb/test/pos/*')
# neg_dev_files = glob.glob('aclImdb/test/neg/*')
# num_dev_files_per_class = 100
# all_dev_files = pos_dev_files[:num_dev_files_per_class] + neg_dev_files[:num_dev_files_per_class]
# # use the same vectorizer from before! otherwise features won't line up
# # don't fit it again, just use it to transform!
# X_dev = vectorizer.transform(all_dev_files)
# y_dev = [1]* num_dev_files_per_class + [0]* num_dev_files_per_class
# # don't need new w and b, these are from out existing model
# y_dev_pred = predict_y_lr(w,b,X_dev)
# print(classification_report(y_dev, y_dev_pred))
def avg_embeddings(doc, model, vocab: set):
words = []
# remove out-of-vocabulary words
with open(doc, "r") as file:
for line in file:
for word in line.split():
words.append(word)
vocab.add(word)
words = [word for word in words if word in model.wv.index_to_key]
if len(words) >= 1:
return np.mean(model.wv[words], axis=0)
else:
return []
def sent_vec(sent, cbow):
vector_size = cbow.wv.vector_size
wv_res = np.zeros(vector_size)
# print(wv_res)
ctr = 1
for w in sent:
if w in cbow.wv:
ctr += 1
wv_res += cbow.wv[w]
wv_res = wv_res/ctr
return wv_res
def spacy_tokenizer(sentence):
# Creating our token object, which is used to create documents with linguistic annotations.
# doc = nlp(sentence)
# print(doc)
# print(type(doc))
# Lemmatizing each token and converting each token into lowercase
# mytokens = [ word.lemma_.lower().strip() for word in doc ]
# print(mytokens)
# Removing stop words
# mytokens = [ word for word in mytokens if word not in stop_words and word not in punctuations ]
# return preprocessed list of tokens
return 0
def cbow_classifier(cbow, data, num_sentances):
vocab_len = len(cbow.wv.index_to_key)
embeddings = []
embedding_dict = {}
vocab = set(cbow.wv.index_to_key)
# print("Data len", len(data))
# print("Data at 0", data[0])
X_temp = np.empty([len(data), 1])
X_train_vect = np.array([np.array([cbow.wv[i] for i in ls if i in vocab])
for ls in data])
X_test_vect = np.array([np.array([cbow.wv[i] for i in ls if i in vocab])
for ls in data])
# words = [word for word in words if word in cbow.wv.index_to_key]
for word in vocab:
# embedding[word] = cbow.wv[word]
embeddings.append(np.mean(cbow.wv[word], axis=0))
embedding_dict[word] = np.mean(cbow.wv[word], axis=0)
X = embeddings
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,stratify=y)
# print(embeddings)
# print(vocab_len)
# X_train_vect_avg = []
# for v in X_train_vect:
# if v.size:
# X_train_vect_avg.append(v.mean(axis=0))
# else:
# X_train_vect_avg.append(np.zeros(100, dtype=float))
# X_test_vect_avg = []
# for v in X_test_vect:
# if v.size:
# X_test_vect_avg.append(v.mean(axis=0))
# else:
# X_test_vect_avg.append(np.zeros(100, dtype=float))
# # for i, v in enumerate(X_train_vect_avg):
# # print(len(data.iloc[i]), len(v))
# x_0 = X_train_vect_avg[0]
# num_files_per_class = 100
# y = [1] * num_files_per_class + [0] * num_files_per_class
# w = np.zeros(X_train_vect_avg.shape[1])
# x_0_dense = x_0.todense()
# x_0.dot(w)
# w,b = sgd_for_lr_with_ce(X_train_vect_avg, y)
# w
# sorted_vocab = sorted([(k,v) for k,v in enumerate(embedding_dict)],key=lambda x:x[1])
# sorted_vocab = [a for (a,b) in sorted_vocab]
# sorted_words_weights = sorted([x for x in zip(sorted_vocab, w)], key=lambda x:x[1])
# sorted_words_weights[-50:]
# preds = predict_y_lr(w,b,X_train_vect_avg)
# preds
# w,b = sgd_for_lr_with_ce(X_train_vect_avg, y, num_passes=10)
# y_pred = predict_y_lr(w,b,X_train_vect_avg)
# print(classification_report(y, y_pred))
# # compute for dev set
# pos_dev_files = glob.glob('aclImdb/test/pos/*')
# neg_dev_files = glob.glob('aclImdb/test/neg/*')
# num_dev_files_per_class = 100
# all_dev_files = pos_dev_files[:num_dev_files_per_class] + neg_dev_files[:num_dev_files_per_class]
# # use the same vectorizer from before! otherwise features won't line up
# # don't fit it again, just use it to transform!
# # X_dev = vectorizer.transform(all_dev_files)
# # y_dev = [1]* num_dev_files_per_class + [0]* num_dev_files_per_class
# # # don't need new w and b, these are from out existing model
# # y_dev_pred = predict_y_lr(w,b,X_dev)
# # print(classification_report(y_dev, y_dev_pred))
def sgd_for_lr_with_ce(X, y, num_passes=5, learning_rate = 0.1):
num_data_points = X.shape[0]
# Initialize theta -> 0
num_features = X.shape[1]
w = np.zeros(num_features)
b = 0.0
# repeat until done
# how to define "done"? let's just make it num passes for now
# we can also do norm of gradient and when it is < epsilon (something tiny)
# we stop
for current_pass in range(num_passes):
# iterate through entire dataset in random order
order = list(range(num_data_points))
random.shuffle(order)
for i in order:
# compute y-hat for this value of i given y_i and x_i
x_i = X[i]
y_i = y[i]
# need to compute based on w and b
# sigmoid(w dot x + b)
z = x_i.dot(w) + b
y_hat_i = expit(z)
# for each w (and b), modify by -lr * (y_hat_i - y_i) * x_i
w = w - learning_rate * (y_hat_i - y_i) * x_i
b = b - learning_rate * (y_hat_i - y_i)
# return theta
return w,b
def predict_y_lr(w,b,X,threshold=0.5):
# use our matrix operation version of the logistic regression model
# X dot w + b
# need to make w a column vector so the dimensions line up correctly
y_hat = X.dot( w.reshape((-1,1)) ) + b
# then just check if it's > threshold
preds = np.where(y_hat > threshold,1,0)
return preds
def main():
parser = argparse.ArgumentParser(
prog='word_embedding',
description='This program will train a word embedding model using simple wikipedia.',
epilog='To skip training the model and to used the saved model "word2vec.model", use the command --skip or -s.'
)
parser.add_argument('-s', '--skip', action='store_true')
parser.add_argument('-e', '--extra', action='store_true')
parser.add_argument('-b', '--bias', action='store_true')
parser.add_argument('-c', '--compare', action='store_true')
parser.add_argument('-t', '--text', action='store_true')
args = parser.parse_args()
skip_model = None
cbow_model = None
ud_model = None
wiki_model = None
if args.compare:
if args.skip:
# print("Skipping")
cbow_model = Word2Vec.load("word2vec.model")
skip_model = Word2Vec.load("skip2vec.model")
ud_model = KeyedVectors.load("urban2vec.model")
wiki_model = KeyedVectors.load("wiki2vec.model")
elif args.extra:
# print("Extra mode")
cbow_model = Word2Vec.load("word2vec.model")
skip_model = Word2Vec.load("skip2vec.model")
wiki_model = KeyedVectors.load_word2vec_format("wiki-news-300d-1M-subwords.vec", binary=False)
ud_model = KeyedVectors.load_word2vec_format("ud_basic.vec", binary=False)
wiki_model.save("wiki2vec.model")
ud_model.save("urban2vec.model")
else:
cbow_model, skip_model = train_embeddings()
wiki_model = KeyedVectors.load_word2vec_format("wiki-news-300d-1M-subwords.vec", binary=False)
ud_model = KeyedVectors.load_word2vec_format("ud_basic.vec", binary=False)
wiki_model.save("wiki2vec.model")
ud_model.save("urban2vec.model")
compare_embeddings(cbow_model, skip_model, ud_model, wiki_model)
if args.bias:
if args.skip:
# print("Skipping")
cbow_model = Word2Vec.load("word2vec.model")
skip_model = Word2Vec.load("skip2vec.model")
ud_model = KeyedVectors.load("urban2vec.model")
wiki_model = KeyedVectors.load("wiki2vec.model")
elif args.extra:
# print("Extra mode")
cbow_model = Word2Vec.load("word2vec.model")
skip_model = Word2Vec.load("skip2vec.model")
wiki_model = KeyedVectors.load_word2vec_format("wiki-news-300d-1M-subwords.vec", binary=False)
ud_model = KeyedVectors.load_word2vec_format("ud_basic.vec", binary=False)
wiki_model.save("wiki2vec.model")
ud_model.save("urban2vec.model")
else:
cbow_model, skip_model = train_embeddings()
wiki_model = KeyedVectors.load_word2vec_format("wiki-news-300d-1M-subwords.vec", binary=False)
ud_model = KeyedVectors.load_word2vec_format("ud_basic.vec", binary=False)
wiki_model.save("wiki2vec.model")
ud_model.save("urban2vec.model")
quantify_bias(cbow_model, skip_model, ud_model, wiki_model)
if args.text:
if args.skip:
# print("Skipping")
cbow_model = Word2Vec.load("word2vec.model")
else:
cbow_model, skip_model = train_embeddings()
text_classifier(cbow_model)
# data, sents = get_data()
# cbow_classifier(cbow_model, data, sents)
# print("No errors?")
if __name__ == "__main__":
<<<<<<< HEAD
=======
from datasets import load_dataset
import shutil
import json
from collections import defaultdict
import multiprocessing
import gensim
from sklearn.metrics import classification_report
from gensim import corpora
from gensim.test.utils import common_texts
from gensim.models import Word2Vec
from gensim.models import KeyedVectors
from gensim.models import fasttext
from gensim.test.utils import datapath
from wefe.datasets import load_bingliu
from wefe.metrics import RNSB
from wefe.query import Query
from wefe.word_embedding_model import WordEmbeddingModel
from wefe.utils import plot_queries_results, run_queries
import pandas as pd
import gensim.downloader as api
import glob
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.ensemble import RandomForestClassifier
from wefe.metrics import WEAT
from wefe.datasets import load_weat
from wefe.utils import run_queries
from wefe.utils import plot_queries_results
import random
from scipy.special import expit
import math
import sys
import os
import argparse
import nltk
import scipy.sparse
import numpy as np
import string
import io
from sklearn.model_selection import train_test_split
'''STEPS FOR CODE:
1. Train word embeddings on Simple English Wikipedia;
2. Compare these to other pre-trained embeddings;
3. Quantify biases that exist in these word embeddings;
4. Use your word embeddings as features in a simple text classifier;
'''
def load_vectors(fname):
fin = io.open(fname, 'r', encoding='utf-8', newline='\n', errors='ignore')
n, d = map(int, fin.readline().split())
data = {}
# print("Hello", n, d)
for line in fin:
tokens = line.rstrip().split(' ')
data[tokens[0]] = map(float, tokens[1:])
# print(data)
print(data)
return data
def train_embeddings():
'''TRAIN WORD EMBEDDINGS
This will be making use of the dataset from wikipedia and the first step'''
dataset = load_dataset("wikipedia", "20220301.simple")
cores = multiprocessing.cpu_count()
# check the first example of the training portion of the dataset :
# print(dataset['train'][0])
dataset_size = len(dataset)
### BUILD VOCAB ###
# print(type(dataset["train"][0]))
vocab = set()
vocab_size = 0
count = 0
## Generate vocab and split sentances and words?
data = []
for index, page in enumerate(dataset["train"]):
document = page["text"]
document = document.replace("\n", ". ")
# print(document)
for sent in document.split("."):
# print("Sentance:", sent)
new_sent = []
clean_sent =[s for s in sent if s.isalnum() or s.isspace()]
clean_sent = "".join(clean_sent)
for word in clean_sent.split(" "):
if len(word) > 0:
new_word = word.lower()
# print("Word:", new_word)
if new_word[0] not in string.punctuation:
new_sent.append(new_word)
if len(new_sent) > 0:
data.append(new_sent)
# print("New Sent:", new_sent)
for index, page in enumerate(dataset["train"]):
# print(page["text"])
# for text in page:
# print(text)
text = page["text"]
clean_text = [s for s in text if s.isalnum() or s.isspace()]
clean_text = "".join(clean_text)
clean_text = clean_text.replace("\n", " ")
# text = text.replace('; ', ' ').replace(", ", " ").replace("\n", " ").replace(":", " ").replace(". ", " ").replace("! ", " ").replace("? ", " ").replace()
for word in clean_text.split(" "):
# print(word)
if word != "\n" and word != " " and word not in vocab:
vocab.add(word)
vocab_size += 1
# if index == 10:
# break
# print(f"word #{index}/{count} is {word}")
count += 1
# print(f"There are {vocab_size} vocab words")
embeddings_model = Word2Vec(
data,
epochs= 10,
window=10,
vector_size= 50)
embeddings_model.save("word2vec.model")
skip_model = Word2Vec(
data,
epochs= 10,
window=10,
vector_size= 50,
sg=1)
skip_model.save("skip2vec.model")
embeddings_model = Word2Vec.load("word2vec.model")
skip_model = Word2Vec.load("skip2vec.model")
# embeddings_model.train(dataset, total_examples=dataset_size, epochs=15)
# print(embeddings_model['train'])
# print(embeddings_model.wv["france"])
return embeddings_model, skip_model
def get_data():
dataset = load_dataset("wikipedia", "20220301.simple")
cores = multiprocessing.cpu_count()
# check the first example of the training portion of the dataset :
# print(dataset['train'][0])
dataset_size = len(dataset)
### BUILD VOCAB ###
# print(type(dataset["train"][0]))
vocab = set()
vocab_size = 0
count = 0
## Generate vocab and split sentances and words?
data = []
num_sents = 0
for index, page in enumerate(dataset["train"]):
document = page["text"]
document = document.replace("\n", ". ")
# print(document)
for sent in document.split("."):
num_sents += 1
# print("Sentance:", sent)
new_sent = []
clean_sent =[s for s in sent if s.isalnum() or s.isspace()]
clean_sent = "".join(clean_sent)
for word in clean_sent.split(" "):
if len(word) > 0:
new_word = word.lower()
# print("Word:", new_word)
if new_word[0] not in string.punctuation:
new_sent.append(new_word)
if len(new_sent) > 0:
data.append(new_sent)
# print("New Sent:", new_sent)
return data, num_sents
def compare_embeddings(cbow, skip, urban, fasttext):
'''COMPARE EMBEDDINGS'''
print("Most Similar to dog")
print("cbow", cbow.wv.most_similar(positive=['dog'], negative=[], topn=2))
print("skip", skip.wv.most_similar(positive=['dog'], negative=[], topn=2))
print("urban", urban.most_similar(positive=['dog'], negative=[], topn=2))
print("fasttext", fasttext.most_similar(positive=['dog'], negative=[], topn=2))
print("\nMost Similar to Pizza - Pepperoni + Pretzel")
print("cbow", cbow.wv.most_similar(positive=['pizza', 'pretzel'], negative=['pepperoni'], topn=2))
print("skip", skip.wv.most_similar(positive=['pizza', 'pretzel'], negative=['pepperoni'], topn=2))
print("urban", urban.most_similar(positive=['pizza', 'pretzel'], negative=['pepperoni'], topn=2))
print("fasttext", fasttext.most_similar(positive=['pizza', 'pretzel'], negative=['pepperoni'], topn=2))
print("\nMost Similar to witch - woman + man")
print("cbow", cbow.wv.most_similar(positive=['witch', 'man'], negative=['woman'], topn=2))
print("skip", skip.wv.most_similar(positive=['witch', 'man'], negative=['woman'], topn=2))
print("urban", urban.most_similar(positive=['witch', 'man'], negative=['woman'], topn=2))
print("fasttext", fasttext.most_similar(positive=['witch', 'man'], negative=['woman'], topn=2))
print("\nMost Similar to mayor - town + country")
print("cbow", cbow.wv.most_similar(positive=['mayor', 'country'], negative=['town'], topn=2))
print("skip", skip.wv.most_similar(positive=['mayor', 'country'], negative=['town'], topn=2))
print("urban", urban.most_similar(positive=['mayor', 'country'], negative=['town'], topn=2))
print("fasttext", fasttext.most_similar(positive=['mayor', 'country'], negative=['town'], topn=2))
print("\nMost Similar to death")
print("cbow", cbow.wv.most_similar(positive=['death'], negative=[], topn=2))
print("skip", skip.wv.most_similar(positive=['death'], negative=[], topn=2))
print("urban", urban.most_similar(positive=['death'], negative=[], topn=2))
print("fasttext", fasttext.most_similar(positive=['death'], negative=[], topn=2))
def quantify_bias(cbow, skip, urban, fasttext):
'''QUANTIFY BIASES'''
'''Using WEFE, RNSB'''
RNSB_words = [
['christianity'],
['catholicism'],
['islam'],
['judaism'],
['hinduism'],
['buddhism'],
['mormonism'],
['scientology'],
['taoism']]
weat_wordset = load_weat()
models = [WordEmbeddingModel(cbow.wv, "CBOW"),
WordEmbeddingModel(skip.wv, "skip-gram"),
WordEmbeddingModel(urban, "urban dictionary"),
WordEmbeddingModel(fasttext, "fasttext")]
# Define the 10 Queries:
# print(weat_wordset["science"])
religions = ['christianity',
'catholicism',
'islam',
'judaism',
'hinduism',
'buddhism',
'mormonism',
'scientology',
'taoism',
'atheism']
queries = [
# Flowers vs Insects wrt Pleasant (5) and Unpleasant (5)
Query([religions, weat_wordset['arts']],
[weat_wordset['career'], weat_wordset['family']],
['Religion', 'Art'], ['Career', 'Family']),
Query([religions, weat_wordset['weapons']],
[weat_wordset['male_terms'], weat_wordset['female_terms']],
['Religion', 'Weapons'], ['Male terms', 'Female terms']),
]
wefe_results = run_queries(WEAT,
queries,
models,
metric_params ={
'preprocessors': [
{},
{'lowercase': True }
]
},
warn_not_found_words = True
).T.round(2)
print(wefe_results)
plot_queries_results(wefe_results).show()
def text_classifier(cbow):
'''SIMPLE TEXT CLASSIFIER'''
'''For each document, average together all embeddings for the
individual words in that document to get a new, d-dimensional representation
of that document (this is essentially a “continuous bag-of-words”). Note that
your input feature size is only d now, instead of the size of your entire vocabulary.
Compare the results of training a model using these “CBOW” input features to
your original (discrete) BOW model.'''
pos_train_files = glob.glob('aclImdb/train/pos/*')
neg_train_files = glob.glob('aclImdb/train/neg/*')
# print(pos_train_files[:5])
num_files_per_class = 1000
# bow_train_files = cbow
all_train_files = pos_train_files[:num_files_per_class] + neg_train_files[:num_files_per_class]
# vectorizer = TfidfVectorizer(input="filename", stop_words="english")
# vectors = vectorizer.fit_transform(all_train_files)
d = len(cbow.wv["man"])
vectors = np.empty([len(all_train_files), d])
count = 0
vocab = set()
for doc in all_train_files:
temp_array = avg_embeddings(doc, cbow, vocab)
if len(temp_array) > 0:
vectors[count] = temp_array
count += 1
else:
vectors = np.delete(vectors, count)
# vectors = np.array(avg_embeddings(doc, cbow) for doc in all_train_files)
# print(vectors)
# print(vocab)
# len(vectorizer.vocabulary_)
vectors[0].sum()
# print("Vector at 0", vectors[0])
X = vectors
y = [1] * num_files_per_class + [0] * num_files_per_class
len(y)
x_0 = X[0]
w = np.zeros(X.shape[1])
# x_0_dense = x_0.todense()
x_0.dot(w)
w,b = sgd_for_lr_with_ce(X,y)
# w
# sorted_vocab = sorted([(k,v) for k,v in vectorizer.vocabulary_.items()],key=lambda x:x[1])
sorted_vocab = sorted(vocab)
# sorted_vocab = [a for (a,b) in sorted_vocab]
sorted_words_weights = sorted([x for x in zip(sorted_vocab, w)], key=lambda x:x[1])
sorted_words_weights[-50:]
preds = predict_y_lr(w,b,X)
preds
w,b = sgd_for_lr_with_ce(X, y, num_passes=10)
y_pred = predict_y_lr(w,b,X)
print(classification_report(y, y_pred))
# compute for dev set
# pos_dev_files = glob.glob('aclImdb/test/pos/*')
# neg_dev_files = glob.glob('aclImdb/test/neg/*')
# num_dev_files_per_class = 100
# all_dev_files = pos_dev_files[:num_dev_files_per_class] + neg_dev_files[:num_dev_files_per_class]
# # use the same vectorizer from before! otherwise features won't line up
# # don't fit it again, just use it to transform!
# X_dev = vectorizer.transform(all_dev_files)
# y_dev = [1]* num_dev_files_per_class + [0]* num_dev_files_per_class
# # don't need new w and b, these are from out existing model
# y_dev_pred = predict_y_lr(w,b,X_dev)
# print(classification_report(y_dev, y_dev_pred))
def avg_embeddings(doc, model, vocab: set):
words = []
# remove out-of-vocabulary words
with open(doc, "r") as file:
for line in file:
for word in line.split():
words.append(word)
vocab.add(word)
words = [word for word in words if word in model.wv.index_to_key]
if len(words) >= 1:
return np.mean(model.wv[words], axis=0)
else:
return []
def sent_vec(sent, cbow):
vector_size = cbow.wv.vector_size
wv_res = np.zeros(vector_size)
# print(wv_res)
ctr = 1
for w in sent:
if w in cbow.wv:
ctr += 1
wv_res += cbow.wv[w]
wv_res = wv_res/ctr
return wv_res
def spacy_tokenizer(sentence):
# Creating our token object, which is used to create documents with linguistic annotations.
# doc = nlp(sentence)
# print(doc)
# print(type(doc))
# Lemmatizing each token and converting each token into lowercase
# mytokens = [ word.lemma_.lower().strip() for word in doc ]
# print(mytokens)
# Removing stop words
# mytokens = [ word for word in mytokens if word not in stop_words and word not in punctuations ]
# return preprocessed list of tokens
return 0
def cbow_classifier(cbow, data, num_sentances):
vocab_len = len(cbow.wv.index_to_key)
embeddings = []
embedding_dict = {}
vocab = set(cbow.wv.index_to_key)
# print("Data len", len(data))
# print("Data at 0", data[0])
X_temp = np.empty([len(data), 1])
X_train_vect = np.array([np.array([cbow.wv[i] for i in ls if i in vocab])
for ls in data])
X_test_vect = np.array([np.array([cbow.wv[i] for i in ls if i in vocab])
for ls in data])
# words = [word for word in words if word in cbow.wv.index_to_key]
for word in vocab:
# embedding[word] = cbow.wv[word]
embeddings.append(np.mean(cbow.wv[word], axis=0))
embedding_dict[word] = np.mean(cbow.wv[word], axis=0)
X = embeddings
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,stratify=y)
# print(embeddings)
# print(vocab_len)
# X_train_vect_avg = []
# for v in X_train_vect:
# if v.size:
# X_train_vect_avg.append(v.mean(axis=0))
# else:
# X_train_vect_avg.append(np.zeros(100, dtype=float))
# X_test_vect_avg = []
# for v in X_test_vect:
# if v.size:
# X_test_vect_avg.append(v.mean(axis=0))
# else:
# X_test_vect_avg.append(np.zeros(100, dtype=float))
# # for i, v in enumerate(X_train_vect_avg):
# # print(len(data.iloc[i]), len(v))
# x_0 = X_train_vect_avg[0]
# num_files_per_class = 100
# y = [1] * num_files_per_class + [0] * num_files_per_class
# w = np.zeros(X_train_vect_avg.shape[1])
# x_0_dense = x_0.todense()
# x_0.dot(w)
# w,b = sgd_for_lr_with_ce(X_train_vect_avg, y)
# w
# sorted_vocab = sorted([(k,v) for k,v in enumerate(embedding_dict)],key=lambda x:x[1])
# sorted_vocab = [a for (a,b) in sorted_vocab]
# sorted_words_weights = sorted([x for x in zip(sorted_vocab, w)], key=lambda x:x[1])
# sorted_words_weights[-50:]
# preds = predict_y_lr(w,b,X_train_vect_avg)
# preds
# w,b = sgd_for_lr_with_ce(X_train_vect_avg, y, num_passes=10)
# y_pred = predict_y_lr(w,b,X_train_vect_avg)
# print(classification_report(y, y_pred))
# # compute for dev set
# pos_dev_files = glob.glob('aclImdb/test/pos/*')
# neg_dev_files = glob.glob('aclImdb/test/neg/*')
# num_dev_files_per_class = 100
# all_dev_files = pos_dev_files[:num_dev_files_per_class] + neg_dev_files[:num_dev_files_per_class]
# # use the same vectorizer from before! otherwise features won't line up
# # don't fit it again, just use it to transform!
# # X_dev = vectorizer.transform(all_dev_files)
# # y_dev = [1]* num_dev_files_per_class + [0]* num_dev_files_per_class
# # # don't need new w and b, these are from out existing model
# # y_dev_pred = predict_y_lr(w,b,X_dev)
# # print(classification_report(y_dev, y_dev_pred))
def sgd_for_lr_with_ce(X, y, num_passes=5, learning_rate = 0.1):
num_data_points = X.shape[0]
# Initialize theta -> 0
num_features = X.shape[1]
w = np.zeros(num_features)
b = 0.0
# repeat until done
# how to define "done"? let's just make it num passes for now
# we can also do norm of gradient and when it is < epsilon (something tiny)
# we stop
for current_pass in range(num_passes):
# iterate through entire dataset in random order
order = list(range(num_data_points))
random.shuffle(order)
for i in order:
# compute y-hat for this value of i given y_i and x_i
x_i = X[i]
y_i = y[i]
# need to compute based on w and b
# sigmoid(w dot x + b)
z = x_i.dot(w) + b
y_hat_i = expit(z)
# for each w (and b), modify by -lr * (y_hat_i - y_i) * x_i
w = w - learning_rate * (y_hat_i - y_i) * x_i
b = b - learning_rate * (y_hat_i - y_i)
# return theta
return w,b
def predict_y_lr(w,b,X,threshold=0.5):
# use our matrix operation version of the logistic regression model
# X dot w + b
# need to make w a column vector so the dimensions line up correctly
y_hat = X.dot( w.reshape((-1,1)) ) + b
# then just check if it's > threshold
preds = np.where(y_hat > threshold,1,0)
return preds
def main():
parser = argparse.ArgumentParser(
prog='word_embedding',
description='This program will train a word embedding model using simple wikipedia.',
epilog='To skip training the model and to used the saved model "word2vec.model", use the command --skip or -s.'
)
parser.add_argument('-s', '--skip', action='store_true')
parser.add_argument('-e', '--extra', action='store_true')
parser.add_argument('-b', '--bias', action='store_true')
parser.add_argument('-c', '--compare', action='store_true')
parser.add_argument('-t', '--text', action='store_true')
args = parser.parse_args()
skip_model = None
cbow_model = None
ud_model = None
wiki_model = None
if args.compare:
if args.skip:
# print("Skipping")
cbow_model = Word2Vec.load("word2vec.model")
skip_model = Word2Vec.load("skip2vec.model")
ud_model = KeyedVectors.load("urban2vec.model")
wiki_model = KeyedVectors.load("wiki2vec.model")
elif args.extra:
# print("Extra mode")
cbow_model = Word2Vec.load("word2vec.model")
skip_model = Word2Vec.load("skip2vec.model")
wiki_model = KeyedVectors.load_word2vec_format("wiki-news-300d-1M-subwords.vec", binary=False)
ud_model = KeyedVectors.load_word2vec_format("ud_basic.vec", binary=False)
wiki_model.save("wiki2vec.model")
ud_model.save("urban2vec.model")
else:
cbow_model, skip_model = train_embeddings()
wiki_model = KeyedVectors.load_word2vec_format("wiki-news-300d-1M-subwords.vec", binary=False)
ud_model = KeyedVectors.load_word2vec_format("ud_basic.vec", binary=False)
wiki_model.save("wiki2vec.model")
ud_model.save("urban2vec.model")
compare_embeddings(cbow_model, skip_model, ud_model, wiki_model)
if args.bias:
if args.skip:
# print("Skipping")
cbow_model = Word2Vec.load("word2vec.model")
skip_model = Word2Vec.load("skip2vec.model")
ud_model = KeyedVectors.load("urban2vec.model")
wiki_model = KeyedVectors.load("wiki2vec.model")
elif args.extra:
# print("Extra mode")
cbow_model = Word2Vec.load("word2vec.model")
skip_model = Word2Vec.load("skip2vec.model")
wiki_model = KeyedVectors.load_word2vec_format("wiki-news-300d-1M-subwords.vec", binary=False)
ud_model = KeyedVectors.load_word2vec_format("ud_basic.vec", binary=False)
wiki_model.save("wiki2vec.model")
ud_model.save("urban2vec.model")
else:
cbow_model, skip_model = train_embeddings()
wiki_model = KeyedVectors.load_word2vec_format("wiki-news-300d-1M-subwords.vec", binary=False)
ud_model = KeyedVectors.load_word2vec_format("ud_basic.vec", binary=False)
wiki_model.save("wiki2vec.model")
ud_model.save("urban2vec.model")
quantify_bias(cbow_model, skip_model, ud_model, wiki_model)
if args.text:
if args.skip:
# print("Skipping")
cbow_model = Word2Vec.load("word2vec.model")
else:
cbow_model, skip_model = train_embeddings()
text_classifier(cbow_model)
# data, sents = get_data()
# cbow_classifier(cbow_model, data, sents)
# print("No errors?")
if __name__ == "__main__":
>>>>>>> 7d5b505 (New in-context model with working UI System)
=======
>>>>>>> 5058aea (Problems)
main() |