keras 0.2.0__py2.7.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.
Files changed (116) hide show
  1. EGG-INFO/PKG-INFO +11 -0
  2. EGG-INFO/SOURCES.txt +51 -0
  3. EGG-INFO/dependency_links.txt +1 -0
  4. EGG-INFO/requires.txt +6 -0
  5. EGG-INFO/top_level.txt +1 -0
  6. EGG-INFO/zip-safe +1 -0
  7. keras/__init__.py +15 -0
  8. keras/__init__.pyc +0 -0
  9. keras/activations.py +49 -0
  10. keras/activations.pyc +0 -0
  11. keras/backend/__init__.py +39 -0
  12. keras/backend/__init__.pyc +0 -0
  13. keras/backend/common.py +31 -0
  14. keras/backend/common.pyc +0 -0
  15. keras/backend/tensorflow_backend.py +602 -0
  16. keras/backend/tensorflow_backend.pyc +0 -0
  17. keras/backend/theano_backend.py +622 -0
  18. keras/backend/theano_backend.pyc +0 -0
  19. keras/callbacks.py +295 -0
  20. keras/callbacks.pyc +0 -0
  21. keras/constraints.py +45 -0
  22. keras/constraints.pyc +0 -0
  23. keras/datasets/__init__.py +0 -0
  24. keras/datasets/__init__.pyc +0 -0
  25. keras/datasets/cifar.py +22 -0
  26. keras/datasets/cifar.pyc +0 -0
  27. keras/datasets/cifar10.py +31 -0
  28. keras/datasets/cifar10.pyc +0 -0
  29. keras/datasets/cifar100.py +28 -0
  30. keras/datasets/cifar100.pyc +0 -0
  31. keras/datasets/data_utils.py +50 -0
  32. keras/datasets/data_utils.pyc +0 -0
  33. keras/datasets/imdb.py +66 -0
  34. keras/datasets/imdb.pyc +0 -0
  35. keras/datasets/mnist.py +23 -0
  36. keras/datasets/mnist.pyc +0 -0
  37. keras/datasets/reuters.py +148 -0
  38. keras/datasets/reuters.pyc +0 -0
  39. keras/initializations.py +86 -0
  40. keras/initializations.pyc +0 -0
  41. keras/layers/__init__.py +0 -0
  42. keras/layers/__init__.pyc +0 -0
  43. keras/layers/advanced_activations.py +156 -0
  44. keras/layers/advanced_activations.pyc +0 -0
  45. keras/layers/containers.py +405 -0
  46. keras/layers/containers.pyc +0 -0
  47. keras/layers/convolutional.py +505 -0
  48. keras/layers/convolutional.pyc +0 -0
  49. keras/layers/core.py +1428 -0
  50. keras/layers/core.pyc +0 -0
  51. keras/layers/embeddings.py +88 -0
  52. keras/layers/embeddings.pyc +0 -0
  53. keras/layers/noise.py +55 -0
  54. keras/layers/noise.pyc +0 -0
  55. keras/layers/normalization.py +123 -0
  56. keras/layers/normalization.pyc +0 -0
  57. keras/layers/ntm.py +326 -0
  58. keras/layers/ntm.pyc +0 -0
  59. keras/layers/recurrent.py +354 -0
  60. keras/layers/recurrent.pyc +0 -0
  61. keras/models.py +743 -0
  62. keras/models.pyc +0 -0
  63. keras/objectives.py +59 -0
  64. keras/objectives.pyc +0 -0
  65. keras/optimizers.py +229 -0
  66. keras/optimizers.pyc +0 -0
  67. keras/preprocessing/__init__.py +0 -0
  68. keras/preprocessing/__init__.pyc +0 -0
  69. keras/preprocessing/image.py +246 -0
  70. keras/preprocessing/image.pyc +0 -0
  71. keras/preprocessing/sequence.py +124 -0
  72. keras/preprocessing/sequence.pyc +0 -0
  73. keras/preprocessing/text.py +176 -0
  74. keras/preprocessing/text.pyc +0 -0
  75. keras/regularizers.py +86 -0
  76. keras/regularizers.pyc +0 -0
  77. keras/utils/__init__.py +0 -0
  78. keras/utils/__init__.pyc +0 -0
  79. keras/utils/generic_utils.py +133 -0
  80. keras/utils/generic_utils.pyc +0 -0
  81. keras/utils/io_utils.py +71 -0
  82. keras/utils/io_utils.pyc +0 -0
  83. keras/utils/layer_utils.py +93 -0
  84. keras/utils/layer_utils.pyc +0 -0
  85. keras/utils/np_utils.py +53 -0
  86. keras/utils/np_utils.pyc +0 -0
  87. keras/utils/test_utils.py +27 -0
  88. keras/utils/test_utils.pyc +0 -0
  89. keras/utils/theano_utils.py +44 -0
  90. keras/utils/theano_utils.pyc +0 -0
  91. keras/utils/visualize_util.py +41 -0
  92. keras/utils/visualize_util.pyc +0 -0
  93. keras/wrappers/__init__.py +0 -0
  94. keras/wrappers/__init__.pyc +0 -0
  95. keras/wrappers/scikit_learn.py +266 -0
  96. keras/wrappers/scikit_learn.pyc +0 -0
  97. tests/__init__.py +0 -0
  98. tests/__init__.pyc +0 -0
  99. tests/manual/__init__.py +0 -0
  100. tests/manual/__init__.pyc +0 -0
  101. tests/manual/check_autoencoder.py +134 -0
  102. tests/manual/check_autoencoder.pyc +0 -0
  103. tests/manual/check_callbacks.py +236 -0
  104. tests/manual/check_callbacks.pyc +0 -0
  105. tests/manual/check_constraints.py +100 -0
  106. tests/manual/check_constraints.pyc +0 -0
  107. tests/manual/check_masked_recurrent.py +130 -0
  108. tests/manual/check_masked_recurrent.pyc +0 -0
  109. tests/manual/check_model_utils.py +44 -0
  110. tests/manual/check_model_utils.pyc +0 -0
  111. tests/manual/check_save_weights.py +40 -0
  112. tests/manual/check_save_weights.pyc +0 -0
  113. tests/manual/check_wrappers.py +126 -0
  114. tests/manual/check_wrappers.pyc +0 -0
  115. tests/manual/check_yaml.py +101 -0
  116. tests/manual/check_yaml.pyc +0 -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
Binary file
keras/regularizers.py ADDED
@@ -0,0 +1,86 @@
1
+ from __future__ import absolute_import
2
+ from . import backend as K
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 += K.sum(K.abs(self.p)) * self.l1
29
+ loss += K.sum(K.square(self.p)) * 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
+ output = self.layer.get_output(True)
48
+ loss += self.l1 * K.sum(K.mean(K.abs(output), axis=0))
49
+ loss += self.l2 * K.sum(K.mean(K.square(output), axis=0))
50
+ return loss
51
+
52
+ def get_config(self):
53
+ return {"name": self.__class__.__name__,
54
+ "l1": self.l1,
55
+ "l2": self.l2}
56
+
57
+
58
+ def l1(l=0.01):
59
+ return WeightRegularizer(l1=l)
60
+
61
+
62
+ def l2(l=0.01):
63
+ return WeightRegularizer(l2=l)
64
+
65
+
66
+ def l1l2(l1=0.01, l2=0.01):
67
+ return WeightRegularizer(l1=l1, l2=l2)
68
+
69
+
70
+ def activity_l1(l=0.01):
71
+ return ActivityRegularizer(l1=l)
72
+
73
+
74
+ def activity_l2(l=0.01):
75
+ return ActivityRegularizer(l2=l)
76
+
77
+
78
+ def activity_l1l2(l1=0.01, l2=0.01):
79
+ return ActivityRegularizer(l1=l1, l2=l2)
80
+
81
+ identity = Regularizer
82
+
83
+ from .utils.generic_utils import get_from_module
84
+ def get(identifier, kwargs=None):
85
+ return get_from_module(identifier, globals(), 'regularizer',
86
+ instantiate=True, kwargs=kwargs)
keras/regularizers.pyc ADDED
Binary file
File without changes
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)
Binary file
@@ -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
Binary file
@@ -0,0 +1,93 @@
1
+ from __future__ import print_function
2
+ import inspect
3
+ import numpy as np
4
+ import copy
5
+
6
+ from ..layers.advanced_activations import *
7
+ from ..layers.core import *
8
+ from ..layers.convolutional import *
9
+ from ..layers.embeddings import *
10
+ from ..layers.noise import *
11
+ from ..layers.normalization import *
12
+ from ..layers.recurrent import *
13
+ from ..layers import containers
14
+ from .. import regularizers
15
+ from .. import constraints
16
+
17
+
18
+ def container_from_config(original_layer_dict, custom_objects={}):
19
+ layer_dict = copy.deepcopy(original_layer_dict)
20
+ name = layer_dict.get('name')
21
+
22
+ # Insert custom layers into globals so they can
23
+ # be accessed by `get_from_module`.
24
+ for cls_key in custom_objects:
25
+ globals()[cls_key] = custom_objects[cls_key]
26
+
27
+ if name == 'Merge':
28
+ mode = layer_dict.get('mode')
29
+ layers = layer_dict.get('layers')
30
+ layer_list = []
31
+ for layer in layers:
32
+ init_layer = container_from_config(layer)
33
+ layer_list.append(init_layer)
34
+ merge_layer = Merge(layer_list, mode)
35
+ return merge_layer
36
+
37
+ elif name == 'Sequential':
38
+ layers = layer_dict.get('layers')
39
+ layer_list = []
40
+ for layer in layers:
41
+ init_layer = container_from_config(layer)
42
+ layer_list.append(init_layer)
43
+ seq_layer = containers.Sequential(layer_list)
44
+ return seq_layer
45
+
46
+ elif name == 'Graph':
47
+ graph_layer = containers.Graph()
48
+ inputs = layer_dict.get('input_config')
49
+
50
+ for input in inputs:
51
+ graph_layer.add_input(**input)
52
+
53
+ nodes = layer_dict.get('node_config')
54
+ for node in nodes:
55
+ layer = container_from_config(layer_dict['nodes'].get(node['name']))
56
+ node['layer'] = layer
57
+ graph_layer.add_node(**node)
58
+
59
+ outputs = layer_dict.get('output_config')
60
+ for output in outputs:
61
+ graph_layer.add_output(**output)
62
+ return graph_layer
63
+
64
+ elif name == 'AutoEncoder':
65
+ kwargs = {'encoder': container_from_config(layer_dict.get('encoder_config')),
66
+ 'decoder': container_from_config(layer_dict.get('decoder_config'))}
67
+ for kwarg in ['output_reconstruction', 'weights']:
68
+ if kwarg in layer_dict:
69
+ kwargs[kwarg] = layer_dict[kwarg]
70
+ return AutoEncoder(**kwargs)
71
+
72
+ else:
73
+ layer_dict.pop('name')
74
+
75
+ for k, v in layer_dict.items():
76
+ if isinstance(v, dict):
77
+ vname = v.pop('name')
78
+ if vname in [x for x, y in inspect.getmembers(constraints, predicate=inspect.isclass)]:
79
+ layer_dict[k] = constraints.get(vname, v)
80
+ elif vname in [x for x, y in inspect.getmembers(regularizers, predicate=inspect.isclass)]:
81
+ layer_dict[k] = regularizers.get(vname, v)
82
+ else:
83
+ # 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
+ from .generic_utils import get_from_module
91
+ def get_layer(identifier, kwargs=None):
92
+ return get_from_module(identifier, globals(), 'layer',
93
+ instantiate=True, kwargs=kwargs)
Binary file
@@ -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)
Binary file
@@ -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:])
Binary file