keras 0.2.0__py3.5.egg
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- EGG-INFO/PKG-INFO +11 -0
- EGG-INFO/SOURCES.txt +57 -0
- EGG-INFO/dependency_links.txt +1 -0
- EGG-INFO/requires.txt +6 -0
- EGG-INFO/top_level.txt +2 -0
- EGG-INFO/zip-safe +1 -0
- keras/__init__.py +15 -0
- keras/__pycache__/__init__.cpython-35.pyc +0 -0
- keras/__pycache__/activations.cpython-35.pyc +0 -0
- keras/__pycache__/callbacks.cpython-35.pyc +0 -0
- keras/__pycache__/constraints.cpython-35.pyc +0 -0
- keras/__pycache__/initializations.cpython-35.pyc +0 -0
- keras/__pycache__/models.cpython-35.pyc +0 -0
- keras/__pycache__/objectives.cpython-35.pyc +0 -0
- keras/__pycache__/optimizers.cpython-35.pyc +0 -0
- keras/__pycache__/regularizers.cpython-35.pyc +0 -0
- keras/activations.py +44 -0
- keras/callbacks.py +293 -0
- keras/constraints.py +48 -0
- keras/datasets/__init__.py +0 -0
- keras/datasets/__pycache__/__init__.cpython-35.pyc +0 -0
- keras/datasets/__pycache__/cifar.cpython-35.pyc +0 -0
- keras/datasets/__pycache__/cifar10.cpython-35.pyc +0 -0
- keras/datasets/__pycache__/cifar100.cpython-35.pyc +0 -0
- keras/datasets/__pycache__/data_utils.cpython-35.pyc +0 -0
- keras/datasets/__pycache__/imdb.cpython-35.pyc +0 -0
- keras/datasets/__pycache__/mnist.cpython-35.pyc +0 -0
- keras/datasets/__pycache__/reuters.cpython-35.pyc +0 -0
- keras/datasets/cifar.py +22 -0
- keras/datasets/cifar10.py +31 -0
- keras/datasets/cifar100.py +28 -0
- keras/datasets/data_utils.py +50 -0
- keras/datasets/imdb.py +66 -0
- keras/datasets/mnist.py +23 -0
- keras/datasets/reuters.py +148 -0
- keras/initializations.py +89 -0
- keras/layers/__init__.py +0 -0
- keras/layers/__pycache__/__init__.cpython-35.pyc +0 -0
- keras/layers/__pycache__/advanced_activations.cpython-35.pyc +0 -0
- keras/layers/__pycache__/containers.cpython-35.pyc +0 -0
- keras/layers/__pycache__/convolutional.cpython-35.pyc +0 -0
- keras/layers/__pycache__/core.cpython-35.pyc +0 -0
- keras/layers/__pycache__/embeddings.cpython-35.pyc +0 -0
- keras/layers/__pycache__/noise.cpython-35.pyc +0 -0
- keras/layers/__pycache__/normalization.cpython-35.pyc +0 -0
- keras/layers/__pycache__/recurrent.cpython-35.pyc +0 -0
- keras/layers/advanced_activations.py +137 -0
- keras/layers/containers.py +318 -0
- keras/layers/convolutional.py +504 -0
- keras/layers/core.py +963 -0
- keras/layers/embeddings.py +153 -0
- keras/layers/noise.py +57 -0
- keras/layers/normalization.py +117 -0
- keras/layers/recurrent.py +837 -0
- keras/models.py +733 -0
- keras/objectives.py +67 -0
- keras/optimizers.py +228 -0
- keras/preprocessing/__init__.py +0 -0
- keras/preprocessing/__pycache__/__init__.cpython-35.pyc +0 -0
- keras/preprocessing/__pycache__/image.cpython-35.pyc +0 -0
- keras/preprocessing/__pycache__/sequence.cpython-35.pyc +0 -0
- keras/preprocessing/__pycache__/text.cpython-35.pyc +0 -0
- keras/preprocessing/image.py +251 -0
- keras/preprocessing/sequence.py +124 -0
- keras/preprocessing/text.py +176 -0
- keras/regularizers.py +84 -0
- keras/utils/__init__.py +0 -0
- keras/utils/__pycache__/__init__.cpython-35.pyc +0 -0
- keras/utils/__pycache__/generic_utils.cpython-35.pyc +0 -0
- keras/utils/__pycache__/io_utils.cpython-35.pyc +0 -0
- keras/utils/__pycache__/layer_utils.cpython-35.pyc +0 -0
- keras/utils/__pycache__/np_utils.cpython-35.pyc +0 -0
- keras/utils/__pycache__/test_utils.cpython-35.pyc +0 -0
- keras/utils/__pycache__/theano_utils.cpython-35.pyc +0 -0
- keras/utils/__pycache__/visualize_util.cpython-35.pyc +0 -0
- keras/utils/generic_utils.py +133 -0
- keras/utils/io_utils.py +71 -0
- keras/utils/layer_utils.py +129 -0
- keras/utils/np_utils.py +53 -0
- keras/utils/test_utils.py +27 -0
- keras/utils/theano_utils.py +44 -0
- keras/utils/visualize_util.py +41 -0
- keras/wrappers/__init__.py +0 -0
- keras/wrappers/__pycache__/__init__.cpython-35.pyc +0 -0
- keras/wrappers/__pycache__/scikit_learn.cpython-35.pyc +0 -0
- keras/wrappers/scikit_learn.py +266 -0
- tests/__init__.py +0 -0
- tests/__pycache__/__init__.cpython-35.pyc +0 -0
- tests/manual/__init__.py +0 -0
- tests/manual/__pycache__/__init__.cpython-35.pyc +0 -0
- tests/manual/__pycache__/check_autoencoder.cpython-35.pyc +0 -0
- tests/manual/__pycache__/check_callbacks.cpython-35.pyc +0 -0
- tests/manual/__pycache__/check_constraints.cpython-35.pyc +0 -0
- tests/manual/__pycache__/check_masked_recurrent.cpython-35.pyc +0 -0
- tests/manual/__pycache__/check_model_utils.cpython-35.pyc +0 -0
- tests/manual/__pycache__/check_save_weights.cpython-35.pyc +0 -0
- tests/manual/__pycache__/check_wrappers.cpython-35.pyc +0 -0
- tests/manual/__pycache__/check_yaml.cpython-35.pyc +0 -0
- tests/manual/check_autoencoder.py +134 -0
- tests/manual/check_callbacks.py +236 -0
- tests/manual/check_constraints.py +100 -0
- tests/manual/check_masked_recurrent.py +130 -0
- tests/manual/check_model_utils.py +44 -0
- tests/manual/check_save_weights.py +40 -0
- tests/manual/check_wrappers.py +126 -0
- tests/manual/check_yaml.py +101 -0
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
'''
|
|
3
|
+
These preprocessing utils would greatly benefit
|
|
4
|
+
from a fast Cython rewrite.
|
|
5
|
+
'''
|
|
6
|
+
from __future__ import absolute_import
|
|
7
|
+
|
|
8
|
+
import string, sys
|
|
9
|
+
import numpy as np
|
|
10
|
+
from six.moves import range
|
|
11
|
+
from six.moves import zip
|
|
12
|
+
|
|
13
|
+
if sys.version_info < (3,):
|
|
14
|
+
maketrans = string.maketrans
|
|
15
|
+
else:
|
|
16
|
+
maketrans = str.maketrans
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def base_filter():
|
|
20
|
+
f = string.punctuation
|
|
21
|
+
f = f.replace("'", '')
|
|
22
|
+
f += '\t\n'
|
|
23
|
+
return f
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def text_to_word_sequence(text, filters=base_filter(), lower=True, split=" "):
|
|
27
|
+
'''prune: sequence of characters to filter out
|
|
28
|
+
'''
|
|
29
|
+
if lower:
|
|
30
|
+
text = text.lower()
|
|
31
|
+
text = text.translate(maketrans(filters, split*len(filters)))
|
|
32
|
+
seq = text.split(split)
|
|
33
|
+
return [_f for _f in seq if _f]
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def one_hot(text, n, filters=base_filter(), lower=True, split=" "):
|
|
37
|
+
seq = text_to_word_sequence(text, filters=filters, lower=lower, split=split)
|
|
38
|
+
return [(abs(hash(w)) % (n - 1) + 1) for w in seq]
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class Tokenizer(object):
|
|
42
|
+
def __init__(self, nb_words=None, filters=base_filter(), lower=True, split=" "):
|
|
43
|
+
self.word_counts = {}
|
|
44
|
+
self.word_docs = {}
|
|
45
|
+
self.filters = filters
|
|
46
|
+
self.split = split
|
|
47
|
+
self.lower = lower
|
|
48
|
+
self.nb_words = nb_words
|
|
49
|
+
self.document_count = 0
|
|
50
|
+
|
|
51
|
+
def fit_on_texts(self, texts):
|
|
52
|
+
'''
|
|
53
|
+
required before using texts_to_sequences or texts_to_matrix
|
|
54
|
+
@param texts: can be a list or a generator (for memory-efficiency)
|
|
55
|
+
'''
|
|
56
|
+
self.document_count = 0
|
|
57
|
+
for text in texts:
|
|
58
|
+
self.document_count += 1
|
|
59
|
+
seq = text_to_word_sequence(text, self.filters, self.lower, self.split)
|
|
60
|
+
for w in seq:
|
|
61
|
+
if w in self.word_counts:
|
|
62
|
+
self.word_counts[w] += 1
|
|
63
|
+
else:
|
|
64
|
+
self.word_counts[w] = 1
|
|
65
|
+
for w in set(seq):
|
|
66
|
+
if w in self.word_docs:
|
|
67
|
+
self.word_docs[w] += 1
|
|
68
|
+
else:
|
|
69
|
+
self.word_docs[w] = 1
|
|
70
|
+
|
|
71
|
+
wcounts = list(self.word_counts.items())
|
|
72
|
+
wcounts.sort(key=lambda x: x[1], reverse=True)
|
|
73
|
+
sorted_voc = [wc[0] for wc in wcounts]
|
|
74
|
+
self.word_index = dict(list(zip(sorted_voc, list(range(1, len(sorted_voc) + 1)))))
|
|
75
|
+
|
|
76
|
+
self.index_docs = {}
|
|
77
|
+
for w, c in list(self.word_docs.items()):
|
|
78
|
+
self.index_docs[self.word_index[w]] = c
|
|
79
|
+
|
|
80
|
+
def fit_on_sequences(self, sequences):
|
|
81
|
+
'''
|
|
82
|
+
required before using sequences_to_matrix
|
|
83
|
+
(if fit_on_texts was never called)
|
|
84
|
+
'''
|
|
85
|
+
self.document_count = len(sequences)
|
|
86
|
+
self.index_docs = {}
|
|
87
|
+
for seq in sequences:
|
|
88
|
+
seq = set(seq)
|
|
89
|
+
for i in seq:
|
|
90
|
+
if i not in self.index_docs:
|
|
91
|
+
self.index_docs[i] = 1
|
|
92
|
+
else:
|
|
93
|
+
self.index_docs[i] += 1
|
|
94
|
+
|
|
95
|
+
def texts_to_sequences(self, texts):
|
|
96
|
+
'''
|
|
97
|
+
Transform each text in texts in a sequence of integers.
|
|
98
|
+
Only top "nb_words" most frequent words will be taken into account.
|
|
99
|
+
Only words known by the tokenizer will be taken into account.
|
|
100
|
+
|
|
101
|
+
Returns a list of sequences.
|
|
102
|
+
'''
|
|
103
|
+
res = []
|
|
104
|
+
for vect in self.texts_to_sequences_generator(texts):
|
|
105
|
+
res.append(vect)
|
|
106
|
+
return res
|
|
107
|
+
|
|
108
|
+
def texts_to_sequences_generator(self, texts):
|
|
109
|
+
'''
|
|
110
|
+
Transform each text in texts in a sequence of integers.
|
|
111
|
+
Only top "nb_words" most frequent words will be taken into account.
|
|
112
|
+
Only words known by the tokenizer will be taken into account.
|
|
113
|
+
|
|
114
|
+
Yields individual sequences.
|
|
115
|
+
'''
|
|
116
|
+
nb_words = self.nb_words
|
|
117
|
+
for text in texts:
|
|
118
|
+
seq = text_to_word_sequence(text, self.filters, self.lower, self.split)
|
|
119
|
+
vect = []
|
|
120
|
+
for w in seq:
|
|
121
|
+
i = self.word_index.get(w)
|
|
122
|
+
if i is not None:
|
|
123
|
+
if nb_words and i >= nb_words:
|
|
124
|
+
pass
|
|
125
|
+
else:
|
|
126
|
+
vect.append(i)
|
|
127
|
+
yield vect
|
|
128
|
+
|
|
129
|
+
def texts_to_matrix(self, texts, mode="binary"):
|
|
130
|
+
'''
|
|
131
|
+
modes: binary, count, tfidf, freq
|
|
132
|
+
'''
|
|
133
|
+
sequences = self.texts_to_sequences(texts)
|
|
134
|
+
return self.sequences_to_matrix(sequences, mode=mode)
|
|
135
|
+
|
|
136
|
+
def sequences_to_matrix(self, sequences, mode="binary"):
|
|
137
|
+
'''
|
|
138
|
+
modes: binary, count, tfidf, freq
|
|
139
|
+
'''
|
|
140
|
+
if not self.nb_words:
|
|
141
|
+
if self.word_index:
|
|
142
|
+
nb_words = len(self.word_index) + 1
|
|
143
|
+
else:
|
|
144
|
+
raise Exception("Specify a dimension (nb_words argument), or fit on some text data first")
|
|
145
|
+
else:
|
|
146
|
+
nb_words = self.nb_words
|
|
147
|
+
|
|
148
|
+
if mode == "tfidf" and not self.document_count:
|
|
149
|
+
raise Exception("Fit the Tokenizer on some data before using tfidf mode")
|
|
150
|
+
|
|
151
|
+
X = np.zeros((len(sequences), nb_words))
|
|
152
|
+
for i, seq in enumerate(sequences):
|
|
153
|
+
if not seq:
|
|
154
|
+
pass
|
|
155
|
+
counts = {}
|
|
156
|
+
for j in seq:
|
|
157
|
+
if j >= nb_words:
|
|
158
|
+
pass
|
|
159
|
+
if j not in counts:
|
|
160
|
+
counts[j] = 1.
|
|
161
|
+
else:
|
|
162
|
+
counts[j] += 1
|
|
163
|
+
for j, c in list(counts.items()):
|
|
164
|
+
if mode == "count":
|
|
165
|
+
X[i][j] = c
|
|
166
|
+
elif mode == "freq":
|
|
167
|
+
X[i][j] = c / len(seq)
|
|
168
|
+
elif mode == "binary":
|
|
169
|
+
X[i][j] = 1
|
|
170
|
+
elif mode == "tfidf":
|
|
171
|
+
tf = np.log(c / len(seq))
|
|
172
|
+
df = (1 + np.log(1 + self.index_docs.get(j, 0) / (1 + self.document_count)))
|
|
173
|
+
X[i][j] = tf / df
|
|
174
|
+
else:
|
|
175
|
+
raise Exception("Unknown vectorization mode: " + str(mode))
|
|
176
|
+
return X
|
keras/regularizers.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
from __future__ import absolute_import
|
|
2
|
+
import theano.tensor as T
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class Regularizer(object):
|
|
6
|
+
def set_param(self, p):
|
|
7
|
+
self.p = p
|
|
8
|
+
|
|
9
|
+
def set_layer(self, layer):
|
|
10
|
+
self.layer = layer
|
|
11
|
+
|
|
12
|
+
def __call__(self, loss):
|
|
13
|
+
return loss
|
|
14
|
+
|
|
15
|
+
def get_config(self):
|
|
16
|
+
return {"name": self.__class__.__name__}
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class WeightRegularizer(Regularizer):
|
|
20
|
+
def __init__(self, l1=0., l2=0.):
|
|
21
|
+
self.l1 = l1
|
|
22
|
+
self.l2 = l2
|
|
23
|
+
|
|
24
|
+
def set_param(self, p):
|
|
25
|
+
self.p = p
|
|
26
|
+
|
|
27
|
+
def __call__(self, loss):
|
|
28
|
+
loss += T.sum(abs(self.p)) * self.l1
|
|
29
|
+
loss += T.sum(self.p ** 2) * self.l2
|
|
30
|
+
return loss
|
|
31
|
+
|
|
32
|
+
def get_config(self):
|
|
33
|
+
return {"name": self.__class__.__name__,
|
|
34
|
+
"l1": self.l1,
|
|
35
|
+
"l2": self.l2}
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class ActivityRegularizer(Regularizer):
|
|
39
|
+
def __init__(self, l1=0., l2=0.):
|
|
40
|
+
self.l1 = l1
|
|
41
|
+
self.l2 = l2
|
|
42
|
+
|
|
43
|
+
def set_layer(self, layer):
|
|
44
|
+
self.layer = layer
|
|
45
|
+
|
|
46
|
+
def __call__(self, loss):
|
|
47
|
+
loss += self.l1 * T.sum(T.mean(abs(self.layer.get_output(True)), axis=0))
|
|
48
|
+
loss += self.l2 * T.sum(T.mean(self.layer.get_output(True) ** 2, axis=0))
|
|
49
|
+
return loss
|
|
50
|
+
|
|
51
|
+
def get_config(self):
|
|
52
|
+
return {"name": self.__class__.__name__,
|
|
53
|
+
"l1": self.l1,
|
|
54
|
+
"l2": self.l2}
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def l1(l=0.01):
|
|
58
|
+
return WeightRegularizer(l1=l)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def l2(l=0.01):
|
|
62
|
+
return WeightRegularizer(l2=l)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def l1l2(l1=0.01, l2=0.01):
|
|
66
|
+
return WeightRegularizer(l1=l1, l2=l2)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def activity_l1(l=0.01):
|
|
70
|
+
return ActivityRegularizer(l1=l)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def activity_l2(l=0.01):
|
|
74
|
+
return ActivityRegularizer(l2=l)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def activity_l1l2(l1=0.01, l2=0.01):
|
|
78
|
+
return ActivityRegularizer(l1=l1, l2=l2)
|
|
79
|
+
|
|
80
|
+
identity = Regularizer
|
|
81
|
+
|
|
82
|
+
from .utils.generic_utils import get_from_module
|
|
83
|
+
def get(identifier, kwargs=None):
|
|
84
|
+
return get_from_module(identifier, globals(), 'regularizer', instantiate=True, kwargs=kwargs)
|
keras/utils/__init__.py
ADDED
|
File without changes
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
from __future__ import absolute_import
|
|
2
|
+
import numpy as np
|
|
3
|
+
import time
|
|
4
|
+
import sys
|
|
5
|
+
import six
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def get_from_module(identifier, module_params, module_name, instantiate=False, kwargs=None):
|
|
9
|
+
if isinstance(identifier, six.string_types):
|
|
10
|
+
res = module_params.get(identifier)
|
|
11
|
+
if not res:
|
|
12
|
+
raise Exception('Invalid ' + str(module_name) + ': ' + str(identifier))
|
|
13
|
+
if instantiate and not kwargs:
|
|
14
|
+
return res()
|
|
15
|
+
elif instantiate and kwargs:
|
|
16
|
+
return res(**kwargs)
|
|
17
|
+
else:
|
|
18
|
+
return res
|
|
19
|
+
return identifier
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def make_tuple(*args):
|
|
23
|
+
return args
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def printv(v, prefix=''):
|
|
27
|
+
if type(v) == dict:
|
|
28
|
+
if 'name' in v:
|
|
29
|
+
print(prefix + '#' + v['name'])
|
|
30
|
+
del v['name']
|
|
31
|
+
prefix += '...'
|
|
32
|
+
for nk, nv in v.items():
|
|
33
|
+
if type(nv) in [dict, list]:
|
|
34
|
+
print(prefix + nk + ':')
|
|
35
|
+
printv(nv, prefix)
|
|
36
|
+
else:
|
|
37
|
+
print(prefix + nk + ':' + str(nv))
|
|
38
|
+
elif type(v) == list:
|
|
39
|
+
prefix += '...'
|
|
40
|
+
for i, nv in enumerate(v):
|
|
41
|
+
print(prefix + '#' + str(i))
|
|
42
|
+
printv(nv, prefix)
|
|
43
|
+
else:
|
|
44
|
+
prefix += '...'
|
|
45
|
+
print(prefix + str(v))
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class Progbar(object):
|
|
49
|
+
def __init__(self, target, width=30, verbose=1):
|
|
50
|
+
'''
|
|
51
|
+
@param target: total number of steps expected
|
|
52
|
+
'''
|
|
53
|
+
self.width = width
|
|
54
|
+
self.target = target
|
|
55
|
+
self.sum_values = {}
|
|
56
|
+
self.unique_values = []
|
|
57
|
+
self.start = time.time()
|
|
58
|
+
self.total_width = 0
|
|
59
|
+
self.seen_so_far = 0
|
|
60
|
+
self.verbose = verbose
|
|
61
|
+
|
|
62
|
+
def update(self, current, values=[]):
|
|
63
|
+
'''
|
|
64
|
+
@param current: index of current step
|
|
65
|
+
@param values: list of tuples (name, value_for_last_step).
|
|
66
|
+
The progress bar will display averages for these values.
|
|
67
|
+
'''
|
|
68
|
+
for k, v in values:
|
|
69
|
+
if k not in self.sum_values:
|
|
70
|
+
self.sum_values[k] = [v * (current - self.seen_so_far), current - self.seen_so_far]
|
|
71
|
+
self.unique_values.append(k)
|
|
72
|
+
else:
|
|
73
|
+
self.sum_values[k][0] += v * (current - self.seen_so_far)
|
|
74
|
+
self.sum_values[k][1] += (current - self.seen_so_far)
|
|
75
|
+
self.seen_so_far = current
|
|
76
|
+
|
|
77
|
+
now = time.time()
|
|
78
|
+
if self.verbose == 1:
|
|
79
|
+
prev_total_width = self.total_width
|
|
80
|
+
sys.stdout.write("\b" * prev_total_width)
|
|
81
|
+
sys.stdout.write("\r")
|
|
82
|
+
|
|
83
|
+
numdigits = int(np.floor(np.log10(self.target))) + 1
|
|
84
|
+
barstr = '%%%dd/%%%dd [' % (numdigits, numdigits)
|
|
85
|
+
bar = barstr % (current, self.target)
|
|
86
|
+
prog = float(current)/self.target
|
|
87
|
+
prog_width = int(self.width*prog)
|
|
88
|
+
if prog_width > 0:
|
|
89
|
+
bar += ('='*(prog_width-1))
|
|
90
|
+
if current < self.target:
|
|
91
|
+
bar += '>'
|
|
92
|
+
else:
|
|
93
|
+
bar += '='
|
|
94
|
+
bar += ('.'*(self.width-prog_width))
|
|
95
|
+
bar += ']'
|
|
96
|
+
sys.stdout.write(bar)
|
|
97
|
+
self.total_width = len(bar)
|
|
98
|
+
|
|
99
|
+
if current:
|
|
100
|
+
time_per_unit = (now - self.start) / current
|
|
101
|
+
else:
|
|
102
|
+
time_per_unit = 0
|
|
103
|
+
eta = time_per_unit*(self.target - current)
|
|
104
|
+
info = ''
|
|
105
|
+
if current < self.target:
|
|
106
|
+
info += ' - ETA: %ds' % eta
|
|
107
|
+
else:
|
|
108
|
+
info += ' - %ds' % (now - self.start)
|
|
109
|
+
for k in self.unique_values:
|
|
110
|
+
if type(self.sum_values[k]) is list:
|
|
111
|
+
info += ' - %s: %.4f' % (k, self.sum_values[k][0] / max(1, self.sum_values[k][1]))
|
|
112
|
+
else:
|
|
113
|
+
info += ' - %s: %s' % (k, self.sum_values[k])
|
|
114
|
+
|
|
115
|
+
self.total_width += len(info)
|
|
116
|
+
if prev_total_width > self.total_width:
|
|
117
|
+
info += ((prev_total_width-self.total_width) * " ")
|
|
118
|
+
|
|
119
|
+
sys.stdout.write(info)
|
|
120
|
+
sys.stdout.flush()
|
|
121
|
+
|
|
122
|
+
if current >= self.target:
|
|
123
|
+
sys.stdout.write("\n")
|
|
124
|
+
|
|
125
|
+
if self.verbose == 2:
|
|
126
|
+
if current >= self.target:
|
|
127
|
+
info = '%ds' % (now - self.start)
|
|
128
|
+
for k in self.unique_values:
|
|
129
|
+
info += ' - %s: %.4f' % (k, self.sum_values[k][0] / max(1, self.sum_values[k][1]))
|
|
130
|
+
sys.stdout.write(info + "\n")
|
|
131
|
+
|
|
132
|
+
def add(self, n, values=[]):
|
|
133
|
+
self.update(self.seen_so_far+n, values)
|
keras/utils/io_utils.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
from __future__ import absolute_import
|
|
2
|
+
import h5py
|
|
3
|
+
import numpy as np
|
|
4
|
+
from collections import defaultdict
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class HDF5Matrix():
|
|
8
|
+
refs = defaultdict(int)
|
|
9
|
+
|
|
10
|
+
def __init__(self, datapath, dataset, start, end, normalizer=None):
|
|
11
|
+
if datapath not in list(self.refs.keys()):
|
|
12
|
+
f = h5py.File(datapath)
|
|
13
|
+
self.refs[datapath] = f
|
|
14
|
+
else:
|
|
15
|
+
f = self.refs[datapath]
|
|
16
|
+
self.start = start
|
|
17
|
+
self.end = end
|
|
18
|
+
self.data = f[dataset]
|
|
19
|
+
self.normalizer = normalizer
|
|
20
|
+
|
|
21
|
+
def __len__(self):
|
|
22
|
+
return self.end - self.start
|
|
23
|
+
|
|
24
|
+
def __getitem__(self, key):
|
|
25
|
+
if isinstance(key, slice):
|
|
26
|
+
if key.stop + self.start <= self.end:
|
|
27
|
+
idx = slice(key.start+self.start, key.stop + self.start)
|
|
28
|
+
else:
|
|
29
|
+
raise IndexError
|
|
30
|
+
elif isinstance(key, int):
|
|
31
|
+
if key + self.start < self.end:
|
|
32
|
+
idx = key+self.start
|
|
33
|
+
else:
|
|
34
|
+
raise IndexError
|
|
35
|
+
elif isinstance(key, np.ndarray):
|
|
36
|
+
if np.max(key) + self.start < self.end:
|
|
37
|
+
idx = (self.start + key).tolist()
|
|
38
|
+
else:
|
|
39
|
+
raise IndexError
|
|
40
|
+
elif isinstance(key, list):
|
|
41
|
+
if max(key) + self.start < self.end:
|
|
42
|
+
idx = [x + self.start for x in key]
|
|
43
|
+
else:
|
|
44
|
+
raise IndexError
|
|
45
|
+
if self.normalizer is not None:
|
|
46
|
+
return self.normalizer(self.data[idx])
|
|
47
|
+
else:
|
|
48
|
+
return self.data[idx]
|
|
49
|
+
|
|
50
|
+
@property
|
|
51
|
+
def shape(self):
|
|
52
|
+
return tuple([self.end - self.start, self.data.shape[1]])
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def save_array(array, name):
|
|
56
|
+
import tables
|
|
57
|
+
f = tables.open_file(name, 'w')
|
|
58
|
+
atom = tables.Atom.from_dtype(array.dtype)
|
|
59
|
+
ds = f.createCArray(f.root, 'data', atom, array.shape)
|
|
60
|
+
ds[:] = array
|
|
61
|
+
f.close()
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def load_array(name):
|
|
65
|
+
import tables
|
|
66
|
+
f = tables.open_file(name)
|
|
67
|
+
array = f.root.data
|
|
68
|
+
a = np.empty(shape=array.shape, dtype=array.dtype)
|
|
69
|
+
a[:] = array[:]
|
|
70
|
+
f.close()
|
|
71
|
+
return a
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
from __future__ import print_function
|
|
2
|
+
import inspect
|
|
3
|
+
import numpy as np
|
|
4
|
+
import theano
|
|
5
|
+
import copy
|
|
6
|
+
|
|
7
|
+
from ..layers.advanced_activations import LeakyReLU, PReLU
|
|
8
|
+
from ..layers.core import Dense, Merge, Dropout, Activation, Reshape, Flatten, RepeatVector, Layer, AutoEncoder, Masking, Permute
|
|
9
|
+
from ..layers.core import ActivityRegularization, TimeDistributedDense, TimeDistributedMerge, AutoEncoder, MaxoutDense
|
|
10
|
+
from ..layers.convolutional import Convolution1D, Convolution2D, MaxPooling1D, MaxPooling2D, ZeroPadding2D
|
|
11
|
+
from ..layers.embeddings import Embedding, WordContextProduct
|
|
12
|
+
from ..layers.noise import GaussianNoise, GaussianDropout
|
|
13
|
+
from ..layers.normalization import BatchNormalization, LRN2D
|
|
14
|
+
from ..layers.recurrent import SimpleRNN, SimpleDeepRNN, GRU, LSTM, JZS1, JZS2, JZS3
|
|
15
|
+
from ..layers import containers
|
|
16
|
+
from .. import regularizers
|
|
17
|
+
from .. import constraints
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def container_from_config(original_layer_dict, custom_objects={}):
|
|
21
|
+
layer_dict = copy.deepcopy(original_layer_dict)
|
|
22
|
+
name = layer_dict.get('name')
|
|
23
|
+
|
|
24
|
+
# Insert custom layers into globals so they can be accessed by `get_from_module`.
|
|
25
|
+
for cls_key in custom_objects:
|
|
26
|
+
globals()[cls_key] = custom_objects[cls_key]
|
|
27
|
+
|
|
28
|
+
if name == 'Merge':
|
|
29
|
+
mode = layer_dict.get('mode')
|
|
30
|
+
layers = layer_dict.get('layers')
|
|
31
|
+
layer_list = []
|
|
32
|
+
for layer in layers:
|
|
33
|
+
init_layer = container_from_config(layer)
|
|
34
|
+
layer_list.append(init_layer)
|
|
35
|
+
merge_layer = Merge(layer_list, mode)
|
|
36
|
+
return merge_layer
|
|
37
|
+
|
|
38
|
+
elif name == 'Sequential':
|
|
39
|
+
layers = layer_dict.get('layers')
|
|
40
|
+
layer_list = []
|
|
41
|
+
for layer in layers:
|
|
42
|
+
init_layer = container_from_config(layer)
|
|
43
|
+
layer_list.append(init_layer)
|
|
44
|
+
seq_layer = containers.Sequential(layer_list)
|
|
45
|
+
return seq_layer
|
|
46
|
+
|
|
47
|
+
elif name == 'Graph':
|
|
48
|
+
graph_layer = containers.Graph()
|
|
49
|
+
inputs = layer_dict.get('input_config')
|
|
50
|
+
|
|
51
|
+
for input in inputs:
|
|
52
|
+
graph_layer.add_input(**input)
|
|
53
|
+
|
|
54
|
+
nodes = layer_dict.get('node_config')
|
|
55
|
+
for node in nodes:
|
|
56
|
+
layer = container_from_config(layer_dict['nodes'].get(node['name']))
|
|
57
|
+
node['layer'] = layer
|
|
58
|
+
graph_layer.add_node(**node)
|
|
59
|
+
|
|
60
|
+
outputs = layer_dict.get('output_config')
|
|
61
|
+
for output in outputs:
|
|
62
|
+
graph_layer.add_output(**output)
|
|
63
|
+
return graph_layer
|
|
64
|
+
|
|
65
|
+
elif name == 'AutoEncoder':
|
|
66
|
+
kwargs = {'encoder': container_from_config(layer_dict.get('encoder_config')),
|
|
67
|
+
'decoder': container_from_config(layer_dict.get('decoder_config'))}
|
|
68
|
+
for kwarg in ['output_reconstruction', 'weights']:
|
|
69
|
+
if kwarg in layer_dict:
|
|
70
|
+
kwargs[kwarg] = layer_dict[kwarg]
|
|
71
|
+
return AutoEncoder(**kwargs)
|
|
72
|
+
|
|
73
|
+
else:
|
|
74
|
+
layer_dict.pop('name')
|
|
75
|
+
|
|
76
|
+
for k, v in layer_dict.items():
|
|
77
|
+
if isinstance(v, dict):
|
|
78
|
+
vname = v.pop('name')
|
|
79
|
+
if vname in [x for x, y in inspect.getmembers(constraints, predicate=inspect.isclass)]:
|
|
80
|
+
layer_dict[k] = constraints.get(vname, v)
|
|
81
|
+
elif vname in [x for x, y in inspect.getmembers(regularizers, predicate=inspect.isclass)]:
|
|
82
|
+
layer_dict[k] = regularizers.get(vname, v)
|
|
83
|
+
else: # not a regularizer of constraint, don't touch it
|
|
84
|
+
v['name'] = vname
|
|
85
|
+
|
|
86
|
+
base_layer = get_layer(name, layer_dict)
|
|
87
|
+
return base_layer
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def print_layer_shapes(model, input_shapes):
|
|
91
|
+
"""
|
|
92
|
+
Utility function to print the shape of the output at each layer of a Model
|
|
93
|
+
|
|
94
|
+
Arguments:
|
|
95
|
+
model: instance of Model / Merge
|
|
96
|
+
input_shapes: dict (Graph), list of tuples (Merge) or tuple (Sequential)
|
|
97
|
+
"""
|
|
98
|
+
if model.__class__.__name__ in ['Sequential', 'Merge']:
|
|
99
|
+
# in this case input_shapes is a tuple, or a list [shape1, shape2]
|
|
100
|
+
if not isinstance(input_shapes[0], tuple):
|
|
101
|
+
input_shapes = [input_shapes]
|
|
102
|
+
|
|
103
|
+
inputs = model.get_input(train=False)
|
|
104
|
+
if not isinstance(inputs, list):
|
|
105
|
+
inputs = [inputs]
|
|
106
|
+
input_dummy = [np.zeros(shape, dtype=np.float32)
|
|
107
|
+
for shape in input_shapes]
|
|
108
|
+
layers = model.layers
|
|
109
|
+
|
|
110
|
+
elif model.__class__.__name__ == 'Graph':
|
|
111
|
+
# in this case input_shapes is a dictionary
|
|
112
|
+
inputs = [model.inputs[name].input
|
|
113
|
+
for name in model.input_order]
|
|
114
|
+
input_dummy = [np.zeros(input_shapes[name], dtype=np.float32)
|
|
115
|
+
for name in model.input_order]
|
|
116
|
+
layers = [model.nodes[c['name']] for c in model.node_config]
|
|
117
|
+
|
|
118
|
+
print("input shapes : ", input_shapes)
|
|
119
|
+
for l in layers:
|
|
120
|
+
shape_f = theano.function(inputs, l.get_output(train=False).shape,
|
|
121
|
+
on_unused_input='ignore')
|
|
122
|
+
out_shape = tuple(shape_f(*input_dummy))
|
|
123
|
+
config = l.get_config()
|
|
124
|
+
print('shape after %s: %s' % (config['name'], out_shape))
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
from .generic_utils import get_from_module
|
|
128
|
+
def get_layer(identifier, kwargs=None):
|
|
129
|
+
return get_from_module(identifier, globals(), 'layer', instantiate=True, kwargs=kwargs)
|
keras/utils/np_utils.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
from __future__ import absolute_import
|
|
2
|
+
import numpy as np
|
|
3
|
+
import scipy as sp
|
|
4
|
+
from six.moves import range
|
|
5
|
+
from six.moves import zip
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def to_categorical(y, nb_classes=None):
|
|
9
|
+
'''Convert class vector (integers from 0 to nb_classes)
|
|
10
|
+
to binary class matrix, for use with categorical_crossentropy
|
|
11
|
+
'''
|
|
12
|
+
y = np.asarray(y, dtype='int32')
|
|
13
|
+
if not nb_classes:
|
|
14
|
+
nb_classes = np.max(y)+1
|
|
15
|
+
Y = np.zeros((len(y), nb_classes))
|
|
16
|
+
for i in range(len(y)):
|
|
17
|
+
Y[i, y[i]] = 1.
|
|
18
|
+
return Y
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def normalize(a, axis=-1, order=2):
|
|
22
|
+
l2 = np.atleast_1d(np.linalg.norm(a, order, axis))
|
|
23
|
+
l2[l2 == 0] = 1
|
|
24
|
+
return a / np.expand_dims(l2, axis)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def binary_logloss(p, y):
|
|
28
|
+
epsilon = 1e-15
|
|
29
|
+
p = sp.maximum(epsilon, p)
|
|
30
|
+
p = sp.minimum(1-epsilon, p)
|
|
31
|
+
res = sum(y * sp.log(p) + sp.subtract(1, y) * sp.log(sp.subtract(1, p)))
|
|
32
|
+
res *= -1.0/len(y)
|
|
33
|
+
return res
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def multiclass_logloss(P, Y):
|
|
37
|
+
npreds = [P[i][Y[i]-1] for i in range(len(Y))]
|
|
38
|
+
score = -(1. / len(Y)) * np.sum(np.log(npreds))
|
|
39
|
+
return score
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def accuracy(p, y):
|
|
43
|
+
return np.mean([a == b for a, b in zip(p, y)])
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def probas_to_classes(y_pred):
|
|
47
|
+
if len(y_pred.shape) > 1 and y_pred.shape[1] > 1:
|
|
48
|
+
return categorical_probas_to_classes(y_pred)
|
|
49
|
+
return np.array([1 if p > 0.5 else 0 for p in y_pred])
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def categorical_probas_to_classes(p):
|
|
53
|
+
return np.argmax(p, axis=1)
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
def get_test_data(nb_train=1000, nb_test=500, input_shape=(10,), output_shape=(2,),
|
|
5
|
+
classification=True, nb_class=2):
|
|
6
|
+
'''
|
|
7
|
+
classification=True overrides output_shape
|
|
8
|
+
(i.e. output_shape is set to (1,)) and the output
|
|
9
|
+
consists in integers in [0, nb_class-1].
|
|
10
|
+
|
|
11
|
+
Otherwise: float output with shape output_shape.
|
|
12
|
+
'''
|
|
13
|
+
nb_sample = nb_train + nb_test
|
|
14
|
+
if classification:
|
|
15
|
+
y = np.random.randint(0, nb_class, size=(nb_sample, 1))
|
|
16
|
+
X = np.zeros((nb_sample,) + input_shape)
|
|
17
|
+
for i in range(nb_sample):
|
|
18
|
+
X[i] = np.random.normal(loc=y[i], scale=1.0, size=input_shape)
|
|
19
|
+
else:
|
|
20
|
+
y_loc = np.random.random((nb_sample,))
|
|
21
|
+
X = np.zeros((nb_sample,) + input_shape)
|
|
22
|
+
y = np.zeros((nb_sample,) + output_shape)
|
|
23
|
+
for i in range(nb_sample):
|
|
24
|
+
X[i] = np.random.normal(loc=y_loc[i], scale=1.0, size=input_shape)
|
|
25
|
+
y[i] = np.random.normal(loc=y_loc[i], scale=1.0, size=output_shape)
|
|
26
|
+
|
|
27
|
+
return (X[:nb_train], y[:nb_train]), (X[nb_train:], y[nb_train:])
|