-
Notifications
You must be signed in to change notification settings - Fork 0
/
strategies.py
155 lines (126 loc) · 6.9 KB
/
strategies.py
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
def predict_accuracy(ml_model, x_test):
y_pred = ml_model.predict(x_test)
acc_1 = (y_pred[:,0])
acc_2 = (y_pred[:,1])
acc_3 = (y_pred[:,2])
acc_4 = (y_pred[:,3])
acc_5 = (y_pred[:,4])
return acc_1[0], acc_2[0], acc_3[0], acc_4[0], acc_5[0]
def predict_learning_time(data_size):
# Set the prediction time formula here
T = (0.000003615*data_size + 0.0289)
W = (0.00007*data_size + 0.887)
F = (0.002865*data_size + 0.183)
C = (0.002145*data_size + 1.64)
return T, T+C, T+W+C, T+F+C, T+W+F+C
def update_model_by_strategy(model, custom_tokenizer, evolving_event, base_model_wv, new_model_wv, chosen_strategy, config):
import numpy as np
from copy import deepcopy
import tensorflow as tf
from tensorflow.keras.preprocessing.sequence import pad_sequences
from tensorflow.keras.utils import to_categorical
from sklearn.model_selection import train_test_split
from gensim.models import KeyedVectors
text_list = evolving_event['text']
label_list = evolving_event['label']
if chosen_strategy == 1:
train_sequences = custom_tokenizer.texts_to_sequences(text_list)
x_train = pad_sequences(train_sequences, maxlen=200, padding='post')
y_train = to_categorical(label_list)
x_train, x_test, y_train, y_test = train_test_split(x_train, y_train, test_size=0.2, shuffle=True)
score = model.evaluate(x_test, y_test, verbose=0)
elif chosen_strategy == 2:
train_sequences = custom_tokenizer.texts_to_sequences(text_list)
x_train = pad_sequences(train_sequences, maxlen=200, padding='post')
y_train = to_categorical(label_list)
x_train, x_test, y_train, y_test = train_test_split(x_train, y_train, test_size=0.2, shuffle=True)
embedding_matrix = np.zeros((config.embedding_size, 100))
for word, i in custom_tokenizer.word_index.items():
if i == config.embedding_size:
break
if word in base_model_wv.vocab.keys():
embedding_matrix[i] = base_model_wv.word_vec(word)
model.layers[0].set_weights([embedding_matrix])
model.layers[0].trainable = False
for layer in model.layers[:-2]:
layer.trainable = False
optimizer = tf.keras.optimizers.Adam(learning_rate=0.003)
model.compile(loss='categorical_crossentropy', optimizer=optimizer, metrics=['acc'])
model.fit(x_train, y_train, validation_split=0.2, epochs=config.epochs, batch_size=config.batch_size, verbose=0)
score = model.evaluate(x_test, y_test, verbose=0)
elif chosen_strategy == 3:
train_sequences = custom_tokenizer.texts_to_sequences(text_list)
x_train = pad_sequences(train_sequences, maxlen=200, padding='post')
y_train = to_categorical(label_list)
x_train, x_test, y_train, y_test = train_test_split(x_train, y_train, test_size=0.2, shuffle=True)
# Word embedding update
vectorList = []
for word in new_model_wv.index2word:
vectorList.append(new_model_wv.get_vector(word))
kv = deepcopy(base_model_wv)
kv.add(new_model_wv.index2word, vectorList, replace=True)
embedding_matrix = np.zeros((config.embedding_size, 100))
for word, i in custom_tokenizer.word_index.items():
if i == config.embedding_size:
break
if word in kv.vocab.keys():
embedding_matrix[i] = kv.word_vec(word)
model.layers[0].set_weights([embedding_matrix])
model.layers[0].trainable = False
for layer in model.layers[:-2]:
layer.trainable = False
optimizer = tf.keras.optimizers.Adam(learning_rate=0.003)
model.compile(loss='categorical_crossentropy', optimizer=optimizer, metrics=['acc'])
model.fit(x_train, y_train, validation_split=0.2, epochs=config.epochs, batch_size=config.batch_size, verbose=0)
score = model.evaluate(x_test, y_test, verbose=0)
kv.save("./w2v/update.wordvectors")
base_model_wv = KeyedVectors.load("./w2v/update.wordvectors")
elif chosen_strategy == 4:
train_sequences = custom_tokenizer.texts_to_sequences(text_list)
x_train = pad_sequences(train_sequences, maxlen=200, padding='post')
y_train = to_categorical(label_list)
x_train, x_test, y_train, y_test = train_test_split(x_train, y_train, test_size=0.2, shuffle=True)
embedding_matrix = np.zeros((config.embedding_size, 100))
for word, i in custom_tokenizer.word_index.items():
if i == config.embedding_size:
break
if word in base_model_wv.vocab.keys():
embedding_matrix[i] = base_model_wv.word_vec(word)
model.layers[0].set_weights([embedding_matrix])
model.layers[0].trainable = False
for layer in model.layers[1:]:
layer.trainable = True
optimizer = tf.keras.optimizers.Adam(learning_rate=0.003)
model.compile(loss='categorical_crossentropy', optimizer=optimizer, metrics=['acc'])
model.fit(x_train, y_train, validation_split=0.2, epochs=config.epochs, batch_size=config.batch_size, verbose=0)
score = model.evaluate(x_test, y_test, verbose=0)
origin_keyword = deepcopy(list(custom_tokenizer.word_index.keys()))
elif chosen_strategy == 5:
train_sequences = custom_tokenizer.texts_to_sequences(text_list)
x_train = pad_sequences(train_sequences, maxlen=200, padding='post')
y_train = to_categorical(label_list)
x_train, x_test, y_train, y_test = train_test_split(x_train, y_train, test_size=0.2, shuffle=True)
# Word embedding update
vectorList = []
for word in new_model_wv.index2word:
vectorList.append(new_model_wv.get_vector(word))
kv = deepcopy(base_model_wv)
kv.add(new_model_wv.index2word, vectorList, replace=True)
embedding_matrix = np.zeros((config.embedding_size, 100))
for word, i in custom_tokenizer.word_index.items():
if i == config.embedding_size:
break
if word in kv.vocab.keys():
embedding_matrix[i] = kv.word_vec(word)
model.layers[0].set_weights([embedding_matrix])
model.layers[0].trainable = False
for layer in model.layers[1:]:
layer.trainable = True
optimizer = tf.keras.optimizers.Adam(learning_rate=0.003)
model.compile(loss='categorical_crossentropy', optimizer=optimizer, metrics=['acc'])
model.fit(x_train, y_train, validation_split=0.2, epochs=config.epochs, batch_size=config.batch_size, verbose=0)
score = model.evaluate(x_test, y_test, verbose=0)
kv.save("./w2v/update.wordvectors")
base_model_wv = KeyedVectors.load("./w2v/update.wordvectors")
origin_keyword = deepcopy(list(custom_tokenizer.word_index.keys()))
return model, custom_tokenizer, base_model_wv, origin_keyword, score