Spaces:
Sleeping
Sleeping
File size: 9,927 Bytes
0732d74 18eb789 762a449 18eb789 762a449 0732d74 762a449 18eb789 762a449 0732d74 762a449 18eb789 0732d74 |
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 |
from datasets import load_dataset
import numpy as np
from sklearn.svm import SVC
from tqdm.notebook import tqdm
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import classification_report
import nltk
from nltk.corpus import stopwords
from nltk import word_tokenize
from nltk import pos_tag
import pickle
import time
from nltk.corpus import names, gazetteers
from sklearn.model_selection import KFold
from itertools import chain
from sklearn.metrics import precision_score, recall_score, fbeta_score, confusion_matrix
import matplotlib.pyplot as plt
import seaborn as sns
from string import punctuation
nltk.download('stopwords')
stopwords = stopwords.words('english')
PUNCT = list(punctuation)
nltk.download('gazetteers')
nltk.download('names')
from nltk.corpus import names, gazetteers
places=set(gazetteers.words())
people=set(names.words())
countries=set(gazetteers.words('countries.txt'))
nationalities=set(gazetteers.words('nationalities.txt'))
pos_tags = [ 'CC', 'CD', 'DT', 'EX', 'FW', 'IN', 'JJ', 'JJR', 'JJS', 'LS', 'MD', 'NN', 'NNP', 'NNPS',
'NNS', 'NN|SYM', 'PDT', 'POS', 'PRP', 'PRP$', 'RB', 'RBR', 'RBS', 'RP', 'SYM', 'TO', 'UH', 'VB', 'VBD',
'VBG', 'VBN', 'VBP', 'VBZ', 'WDT', 'WP', 'WP$', 'WRB'
]
def feature_vector(word, scaled_pos, current_word_pos_tag, prev_word, next_word):
features = []
features.append(int(word.lower() in stopwords))
features.append(int(word.isupper()))
features.append(int(word in PUNCT))
features.append(int(word.istitle()))
features.append(int(word.isdigit()))
# features.append(len(word))
features.append(int(word in places))
features.append(int(word in people))
features.append(int(word in countries))
features.append(int(word in nationalities))
if (current_word_pos_tag==12) or (current_word_pos_tag==13): ##NNP, NNPS
features.append(1)
else:
features.append(0)
features.append(scaled_pos)
if 27 <= current_word_pos_tag <= 32: ##isVERB
features.append(1)
else:
features.append(0)
if prev_word!="":
features.append(int(prev_word.lower() in stopwords))
features.append(int(prev_word.isupper()))
features.append(int(prev_word in PUNCT))
features.append(int(prev_word.isdigit()))
features.append(len(prev_word))
features.append((prev_word in places))
features.append((prev_word in people))
features.append((prev_word in countries or prev_word in nationalities))
else:
for _ in range(8):
features.append(0)
if next_word!="":
features.append(int(next_word.lower() in stopwords))
features.append(int(next_word.isupper()))
features.append(int(next_word in PUNCT))
features.append(int(next_word.isdigit()))
features.append(len(next_word))
features.append((next_word in places))
features.append((next_word in people))
features.append((next_word in countries or prev_word in nationalities))
else:
for _ in range(8):
features.append(0)
return np.asarray(features, dtype=np.float32)
def feature_vector2(word, prev_word_pos_tag, next_word_pos_tag, current_word_pos_tag):
vec = np.zeros(9).astype('float32')
if(word.istitle()):
vec[0] = 1
if word.lower() in stopwords:
vec[1] = 1
if(word.isupper()):
vec[2] = 1
vec[3] = len(word)
vec[4] = word.isdigit()
# idx : -11, 0...36
# if prev_word_pos_tag!=-11:
# vec[5+prev_word_pos_tag] = 1
# if next_word_pos_tag!=-11:
# vec[42+next_word_pos_tag] = 1
# if current_word_pos_tag!=-11:
# vec[79+current_word_pos_tag] = 1
vec[5] = 1 if word in places else 0
vec[6] = 1 if word in people else 0
vec[7] = 1 if word in countries else 0
vec[8] = 1 if word in nationalities else 0
return vec
# This function is used to make dataset with features and target label
def create_data(data):
x_train = []
y_train = []
for x in data:
for y in range(len(x['tokens'])):
prev_pos = -1 if y==0 or x['pos_tags'][y-1]<10 else x['pos_tags'][y-1]
next_pos = -1 if y==len(x['tokens'])-1 or x['pos_tags'][y+1]<10 else x['pos_tags'][y+1]
current_pos = -1 if x['pos_tags'][y]<10 else x['pos_tags'][y]
wordVec = feature_vector(x['tokens'][y], prev_pos-10, next_pos-10, current_pos-10)
x_train.append(wordVec)
y_train.append(1 if x['ner_tags'][y]!=0 else 0)
return x_train, y_train
def evaluate_overall_metrics(predictions, folds):
precision, recall, f0_5_score, f1_score, f2_score = 0, 0, 0, 0, 0
for i, (test_label_flat, y_pred_flat) in enumerate(predictions):
# test_label_flat = list(chain.from_iterable(test_label))
# y_pred_flat = list(chain.from_iterable(y_pred))
# Calculate scores
f0_5_score += fbeta_score(test_label_flat, y_pred_flat, beta=0.5, average='weighted')
f1_score += fbeta_score(test_label_flat, y_pred_flat, beta=1, average='weighted')
f2_score += fbeta_score(test_label_flat, y_pred_flat, beta=2, average='weighted')
precision += precision_score(test_label_flat, y_pred_flat, average='weighted')
recall += recall_score(test_label_flat, y_pred_flat, average='weighted')
# Averaging across folds
f0_5_score /= folds
f1_score /= folds
f2_score /= folds
precision /= folds
recall /= folds
print(f'Overall Metrics:')
print(f'Precision : {precision:.3f}')
print(f'Recall : {recall:.3f}')
print(f'F0.5 Score : {f0_5_score:.3f}')
print(f'F1 Score : {f1_score:.3f}')
print(f'F2 Score : {f2_score:.3f}\n')
def evaluate_per_pos_metrics(predictions, labels):
combined_true = []
combined_pred = []
# Flatten the list of lists structure
for test_label, y_pred in predictions:
# for sentence_labels, sentence_preds in zip(test_label, y_pred):
combined_true.extend(test_label)
combined_pred.extend(y_pred)
for tag in labels:
true_binary = [1 if t == tag else 0 for t in combined_true]
pred_binary = [1 if p == tag else 0 for p in combined_pred]
# Calculate metrics for the tag
precision = precision_score(true_binary, pred_binary, average='binary', zero_division=0)
recall = recall_score(true_binary, pred_binary, average='binary', zero_division=0)
f1_score = fbeta_score(true_binary, pred_binary, beta=1, average='binary', zero_division=0)
print(f"Metrics for {tag}:")
print(f'Precision : {precision:.3f}')
print(f'Recall : {recall:.3f}')
print(f'F1 Score : {f1_score:.3f}\n')
def plot_confusion_matrix(predictions, labels, folds):
matrix = None
for i, (test_label_flat, y_pred_flat) in enumerate(predictions):
# test_label_flat = list(chain.from_iterable(test_label))
# y_pred_flat = list(chain.from_iterable(y_pred))
# Compute confusion matrix for this fold
cm = confusion_matrix(test_label_flat, y_pred_flat, labels=labels)
if i == 0:
matrix = cm
else:
matrix += cm
matrix = matrix.astype('float')
matrix = matrix / folds
matrix = matrix / np.sum(matrix, axis=1, keepdims=True) # Normalize
plt.figure(figsize=(10, 8))
sns.heatmap(matrix, annot=True, fmt=".2f", cmap='Blues', xticklabels=labels, yticklabels=labels)
plt.xlabel('Predicted')
plt.ylabel('Actual')
plt.title('Normalized Confusion Matrix for NER')
plt.show()
if __name__ == "__main__":
data = load_dataset("conll2003", trust_remote_code=True)
d_train = data['train']
d_validation = data['validation']
d_test = data['test']
nltk.download('gazetteers')
places=set(gazetteers.words())
people=set(names.words())
countries=set(gazetteers.words('countries.txt'))
nationalities=set(gazetteers.words('nationalities.txt'))
x_train, y_train = create_data(d_train)
x_val, y_val = create_data(d_validation)
x_test, y_test = create_data(d_test)
all_X_train = np.concatenate((x_train, x_val, x_test))
all_y_train = np.concatenate((y_train, y_val, y_test))
#K-Fold
num_fold = 5
kf = KFold(n_splits=num_fold, random_state=42, shuffle=True)
indices = np.arange(len(all_X_train))
predictions = []
all_models = []
for i, (train_index, test_index) in enumerate(kf.split(indices)):
print(f"Fold {i} Train Length: {len(train_index)} Test Length: {len(test_index)}")
# all_folds.append((train_index, test_index))# Standardize the features such that all features contribute equally to the distance metric computation of the SVM
X_train = all_X_train[train_index]
y_train = all_y_train[train_index]
X_test = all_X_train[test_index]
y_test = all_y_train[test_index]
# scaler = StandardScaler()
# Fit only on the training data (i.e. compute mean and std)
# X_train = scaler.fit_transform(X_train)
# Use the train data fit values to scale val and test
# X_train = scaler.transform(X_train)
# X_val = scaler.transform(X_val)
# X_test = scaler.transform(X_test)
model = SVC(random_state = 42, verbose = True)
model.fit(X_train, y_train)
y_pred_val = model.predict(X_test)
print("-------"*6)
print(classification_report(y_true=y_test, y_pred=y_pred_val))
print("-------"*6)
pickle.dump(model, open(f"ner_svm_{str(i)}.pkl", 'wb'))
predictions.append((y_test, y_pred_val))
all_models.append(model)
break
FOLDS = 5
labels = sorted(model.classes_)
evaluate_overall_metrics(predictions, FOLDS)
evaluate_per_pos_metrics(predictions, labels)
plot_confusion_matrix(predictions, labels, FOLDS)
|