- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcallback.py
More file actions
Latest commit
45 lines (36 loc) · 1.61 KB
/
Copy pathcallback.py
File metadata and controls
45 lines (36 loc) · 1.61 KB
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
# Importing dependencies
importnumpyasnp
importtensorflow.kerasaskeras
# Class CustomCallback
classCustomCallback(keras.callbacks.Callback):
# This method intriduces some randomness in the prediction
defsample(self, preds, temperature=1.0):
preds=np.asarray(preds).astype('float64')
preds=np.log(preds) /temperature
exp_preds=np.exp(preds)
preds=exp_preds/np.sum(exp_preds)
probas=np.random.multinomial(1, preds, 1)
returnnp.argmax(probas)
# This method runs after each epoch
defon_epoch_end(self, epoch, logs={}):
sample_text="""#if UINTPTR_MAX == 0xffffffff
#define UPB_SIZE(size32, size64) size32
#else
#define UPB_SIZE(size32, size64) size64
#endif"""
# Printing some info and predicted text
print('\nCurrently at epoch {}'.format(epoch+1))
print('Starter text : {}'.format(sample_text))
fortemperaturein [0.2, 0.5, 1.0, 1.2]:
# Selecting first 40 characters
review=sample_text[0:40]
review= [ord(i) foriinreview]
# Predicting the next characters for 500 times
forkinrange(500):
# Predicting using the model
temp=self.model.predict(np.array([review[k: k+40]]))
# Calling the sample method
temp=self.sample(temp[0], temperature)
# Appending the predicted charcter
review.append(temp)
print('\nGenerated text with temperature {}: {}'.format(temperature, ''.join([chr(i) foriinreview])))