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,148 @@
1
+ # -*- coding: utf-8 -*-
2
+ from __future__ import absolute_import
3
+ from __future__ import print_function
4
+ from .data_utils import get_file
5
+ import string
6
+ import random
7
+ import os
8
+ from six.moves import cPickle
9
+ from six.moves import zip
10
+ import numpy as np
11
+
12
+
13
+ def make_reuters_dataset(path=os.path.join('datasets', 'temp', 'reuters21578'), min_samples_per_topic=15):
14
+ import re
15
+ from ..preprocessing.text import Tokenizer
16
+
17
+ wire_topics = []
18
+ topic_counts = {}
19
+ wire_bodies = []
20
+
21
+ for fname in os.listdir(path):
22
+ if 'sgm' in fname:
23
+ s = open(os.path.join(path, fname)).read()
24
+ tag = '<TOPICS>'
25
+ while tag in s:
26
+ s = s[s.find(tag)+len(tag):]
27
+ topics = s[:s.find('</')]
28
+ if topics and '</D><D>' not in topics:
29
+ topic = topics.replace('<D>', '').replace('</D>', '')
30
+ wire_topics.append(topic)
31
+ topic_counts[topic] = topic_counts.get(topic, 0) + 1
32
+ else:
33
+ continue
34
+
35
+ bodytag = '<BODY>'
36
+ body = s[s.find(bodytag)+len(bodytag):]
37
+ body = body[:body.find('</')]
38
+ wire_bodies.append(body)
39
+
40
+ # only keep most common topics
41
+ items = list(topic_counts.items())
42
+ items.sort(key=lambda x: x[1])
43
+ kept_topics = set()
44
+ for x in items:
45
+ print(x[0] + ': ' + str(x[1]))
46
+ if x[1] >= min_samples_per_topic:
47
+ kept_topics.add(x[0])
48
+ print('-')
49
+ print('Kept topics:', len(kept_topics))
50
+
51
+ # filter wires with rare topics
52
+ kept_wires = []
53
+ labels = []
54
+ topic_indexes = {}
55
+ for t, b in zip(wire_topics, wire_bodies):
56
+ if t in kept_topics:
57
+ if t not in topic_indexes:
58
+ topic_index = len(topic_indexes)
59
+ topic_indexes[t] = topic_index
60
+ else:
61
+ topic_index = topic_indexes[t]
62
+
63
+ labels.append(topic_index)
64
+ kept_wires.append(b)
65
+
66
+ # vectorize wires
67
+ tokenizer = Tokenizer()
68
+ tokenizer.fit_on_texts(kept_wires)
69
+ X = tokenizer.texts_to_sequences(kept_wires)
70
+
71
+ print('Sanity check:')
72
+ for w in ["banana", "oil", "chocolate", "the", "dsft"]:
73
+ print('...index of', w, ':', tokenizer.word_index.get(w))
74
+ print('text reconstruction:')
75
+ reverse_word_index = dict([(v, k) for k, v in tokenizer.word_index.items()])
76
+ print(' '.join(reverse_word_index[i] for i in X[10]))
77
+
78
+ dataset = (X, labels)
79
+ print('-')
80
+ print('Saving...')
81
+ cPickle.dump(dataset, open(os.path.join('datasets', 'data', 'reuters.pkl'), 'w'))
82
+ cPickle.dump(tokenizer.word_index, open(os.path.join('datasets', 'data', 'reuters_word_index.pkl'), 'w'))
83
+
84
+
85
+ def load_data(path="reuters.pkl", nb_words=None, skip_top=0, maxlen=None, test_split=0.2, seed=113,
86
+ start_char=1, oov_char=2, index_from=3):
87
+
88
+ path = get_file(path, origin="https://s3.amazonaws.com/text-datasets/reuters.pkl")
89
+ f = open(path, 'rb')
90
+
91
+ X, labels = cPickle.load(f)
92
+ f.close()
93
+
94
+ np.random.seed(seed)
95
+ np.random.shuffle(X)
96
+ np.random.seed(seed)
97
+ np.random.shuffle(labels)
98
+
99
+ if start_char is not None:
100
+ X = [[start_char] + [w + index_from for w in x] for x in X]
101
+ elif index_from:
102
+ X = [[w + index_from for w in x] for x in X]
103
+
104
+ if maxlen:
105
+ new_X = []
106
+ new_labels = []
107
+ for x, y in zip(X, labels):
108
+ if len(x) < maxlen:
109
+ new_X.append(x)
110
+ new_labels.append(y)
111
+ X = new_X
112
+ labels = new_labels
113
+
114
+ if not nb_words:
115
+ nb_words = max([max(x) for x in X])
116
+
117
+ # by convention, use 2 as OOV word
118
+ # reserve 'index_from' (=3 by default) characters: 0 (padding), 1 (start), 2 (OOV)
119
+ if oov_char is not None:
120
+ X = [[oov_char if (w >= nb_words or w < skip_top) else w for w in x] for x in X]
121
+ else:
122
+ nX = []
123
+ for x in X:
124
+ nx = []
125
+ for w in x:
126
+ if (w >= nb_words or w < skip_top):
127
+ nx.append(w)
128
+ nX.append(nx)
129
+ X = nX
130
+
131
+ X_train = X[:int(len(X)*(1-test_split))]
132
+ y_train = labels[:int(len(X)*(1-test_split))]
133
+
134
+ X_test = X[int(len(X)*(1-test_split)):]
135
+ y_test = labels[int(len(X)*(1-test_split)):]
136
+
137
+ return (X_train, y_train), (X_test, y_test)
138
+
139
+
140
+ def get_word_index(path="reuters_word_index.pkl"):
141
+ path = get_file(path, origin="https://s3.amazonaws.com/text-datasets/reuters_word_index.pkl")
142
+ f = open(path, 'rb')
143
+ return cPickle.load(f)
144
+
145
+
146
+ if __name__ == "__main__":
147
+ make_reuters_dataset()
148
+ (X_train, y_train), (X_test, y_test) = load_data()
Binary file
@@ -0,0 +1,86 @@
1
+ from __future__ import absolute_import
2
+ import numpy as np
3
+ from . import backend as K
4
+
5
+
6
+ def get_fans(shape):
7
+ fan_in = shape[0] if len(shape) == 2 else np.prod(shape[1:])
8
+ fan_out = shape[1] if len(shape) == 2 else shape[0]
9
+ return fan_in, fan_out
10
+
11
+
12
+ def uniform(shape, scale=0.05):
13
+ return K.variable(np.random.uniform(low=-scale, high=scale, size=shape))
14
+
15
+
16
+ def normal(shape, scale=0.05):
17
+ return K.variable(np.random.randn(*shape) * scale)
18
+
19
+
20
+ def lecun_uniform(shape):
21
+ ''' Reference: LeCun 98, Efficient Backprop
22
+ http://yann.lecun.com/exdb/publis/pdf/lecun-98b.pdf
23
+ '''
24
+ fan_in, fan_out = get_fans(shape)
25
+ scale = np.sqrt(3. / fan_in)
26
+ return uniform(shape, scale)
27
+
28
+
29
+ def glorot_normal(shape):
30
+ ''' Reference: Glorot & Bengio, AISTATS 2010
31
+ '''
32
+ fan_in, fan_out = get_fans(shape)
33
+ s = np.sqrt(2. / (fan_in + fan_out))
34
+ return normal(shape, s)
35
+
36
+
37
+ def glorot_uniform(shape):
38
+ fan_in, fan_out = get_fans(shape)
39
+ s = np.sqrt(6. / (fan_in + fan_out))
40
+ return uniform(shape, s)
41
+
42
+
43
+ def he_normal(shape):
44
+ ''' Reference: He et al., http://arxiv.org/abs/1502.01852
45
+ '''
46
+ fan_in, fan_out = get_fans(shape)
47
+ s = np.sqrt(2. / fan_in)
48
+ return normal(shape, s)
49
+
50
+
51
+ def he_uniform(shape):
52
+ fan_in, fan_out = get_fans(shape)
53
+ s = np.sqrt(6. / fan_in)
54
+ return uniform(shape, s)
55
+
56
+
57
+ def orthogonal(shape, scale=1.1):
58
+ ''' From Lasagne. Reference: Saxe et al., http://arxiv.org/abs/1312.6120
59
+ '''
60
+ flat_shape = (shape[0], np.prod(shape[1:]))
61
+ a = np.random.normal(0.0, 1.0, flat_shape)
62
+ u, _, v = np.linalg.svd(a, full_matrices=False)
63
+ # pick the one with the correct shape
64
+ q = u if u.shape == flat_shape else v
65
+ q = q.reshape(shape)
66
+ return K.variable(scale * q[:shape[0], :shape[1]])
67
+
68
+
69
+ def identity(shape, scale=1):
70
+ if len(shape) != 2 or shape[0] != shape[1]:
71
+ raise Exception("Identity matrix initialization can only be used for 2D square matrices")
72
+ else:
73
+ return K.variable(scale * np.identity(shape[0]))
74
+
75
+
76
+ def zero(shape):
77
+ return K.zeros(shape)
78
+
79
+
80
+ def one(shape):
81
+ return K.ones(shape)
82
+
83
+
84
+ from .utils.generic_utils import get_from_module
85
+ def get(identifier):
86
+ return get_from_module(identifier, globals(), 'initialization')
Binary file
File without changes
Binary file
@@ -0,0 +1,156 @@
1
+ from .. import initializations
2
+ from ..layers.core import Layer, MaskedLayer
3
+ from .. import backend as K
4
+ import numpy as np
5
+
6
+
7
+ class LeakyReLU(MaskedLayer):
8
+ def __init__(self, alpha=0.3, **kwargs):
9
+ super(LeakyReLU, self).__init__(**kwargs)
10
+ self.alpha = alpha
11
+
12
+ def get_output(self, train):
13
+ X = self.get_input(train)
14
+ return K.relu(X, alpha=self.alpha)
15
+
16
+ def get_config(self):
17
+ config = {"name": self.__class__.__name__,
18
+ "alpha": self.alpha}
19
+ base_config = super(LeakyReLU, self).get_config()
20
+ return dict(list(base_config.items()) + list(config.items()))
21
+
22
+
23
+ class PReLU(MaskedLayer):
24
+ '''
25
+ Reference:
26
+ Delving Deep into Rectifiers: Surpassing Human-Level
27
+ Performance on ImageNet Classification
28
+ http://arxiv.org/pdf/1502.01852v1.pdf
29
+ '''
30
+ def __init__(self, init='zero', weights=None, **kwargs):
31
+ self.init = initializations.get(init)
32
+ self.initial_weights = weights
33
+ super(PReLU, self).__init__(**kwargs)
34
+
35
+ def build(self):
36
+ input_shape = self.input_shape[1:]
37
+ self.alphas = self.init(input_shape)
38
+ self.params = [self.alphas]
39
+
40
+ if self.initial_weights is not None:
41
+ self.set_weights(self.initial_weights)
42
+ del self.initial_weights
43
+
44
+ def get_output(self, train):
45
+ X = self.get_input(train)
46
+ pos = K.relu(X)
47
+ neg = self.alphas * (X - abs(X)) * 0.5
48
+ return pos + neg
49
+
50
+ def get_config(self):
51
+ config = {"name": self.__class__.__name__,
52
+ "init": self.init.__name__}
53
+ base_config = super(PReLU, self).get_config()
54
+ return dict(list(base_config.items()) + list(config.items()))
55
+
56
+
57
+ class ELU(MaskedLayer):
58
+ def __init__(self, alpha=1.0, **kwargs):
59
+ super(ELU, self).__init__(**kwargs)
60
+ self.alpha = alpha
61
+
62
+ def get_output(self, train):
63
+ X = self.get_input(train)
64
+ pos = K.relu(X)
65
+ neg = (X - abs(X)) * 0.5
66
+ return pos + self.alpha * (K.exp(neg) - 1.)
67
+
68
+ def get_config(self):
69
+ config = {"name": self.__class__.__name__,
70
+ "alpha": self.alpha}
71
+ base_config = super(ELU, self).get_config()
72
+ return dict(list(base_config.items()) + list(config.items()))
73
+
74
+
75
+ class ParametricSoftplus(MaskedLayer):
76
+ '''
77
+ Parametric Softplus of the form: alpha * log(1 + exp(beta * X))
78
+
79
+ Reference:
80
+ Inferring Nonlinear Neuronal Computation
81
+ Based on Physiologically Plausible Inputs
82
+ http://journals.plos.org/ploscompbiol/article?id=10.1371/journal.pcbi.1003143
83
+ '''
84
+ def __init__(self, alpha_init=0.2, beta_init=5.0,
85
+ weights=None, **kwargs):
86
+ self.alpha_init = alpha_init
87
+ self.beta_init = beta_init
88
+ self.initial_weights = weights
89
+ super(ParametricSoftplus, self).__init__(**kwargs)
90
+
91
+ def build(self):
92
+ input_shape = self.input_shape[1:]
93
+ self.alphas = K.variable(self.alpha_init * np.ones(input_shape))
94
+ self.betas = K.variable(self.beta_init * np.ones(input_shape))
95
+ self.params = [self.alphas, self.betas]
96
+
97
+ if self.initial_weights is not None:
98
+ self.set_weights(self.initial_weights)
99
+ del self.initial_weights
100
+
101
+ def get_output(self, train):
102
+ X = self.get_input(train)
103
+ return K.softplus(self.betas * X) * self.alphas
104
+
105
+ def get_config(self):
106
+ config = {"name": self.__class__.__name__,
107
+ "alpha_init": self.alpha_init,
108
+ "beta_init": self.beta_init}
109
+ base_config = super(ParametricSoftplus, self).get_config()
110
+ return dict(list(base_config.items()) + list(config.items()))
111
+
112
+
113
+ class ThresholdedLinear(MaskedLayer):
114
+ '''
115
+ Thresholded Linear Activation
116
+
117
+ Reference:
118
+ Zero-Bias Autoencoders and the Benefits of Co-Adapting Features
119
+ http://arxiv.org/pdf/1402.3337.pdf
120
+ '''
121
+ def __init__(self, theta=1.0, **kwargs):
122
+ super(ThresholdedLinear, self).__init__(**kwargs)
123
+ self.theta = theta
124
+
125
+ def get_output(self, train):
126
+ X = self.get_input(train)
127
+ return K.switch(K.abs(X) < self.theta, 0, X)
128
+
129
+ def get_config(self):
130
+ config = {"name": self.__class__.__name__,
131
+ "theta": self.theta}
132
+ base_config = super(ThresholdedLinear, self).get_config()
133
+ return dict(list(base_config.items()) + list(config.items()))
134
+
135
+
136
+ class ThresholdedReLU(MaskedLayer):
137
+ '''
138
+ Thresholded Rectified Activation
139
+
140
+ Reference:
141
+ Zero-Bias Autoencoders and the Benefits of Co-Adapting Features
142
+ http://arxiv.org/pdf/1402.3337.pdf
143
+ '''
144
+ def __init__(self, theta=1.0, **kwargs):
145
+ super(ThresholdedReLU, self).__init__(**kwargs)
146
+ self.theta = theta
147
+
148
+ def get_output(self, train):
149
+ X = self.get_input(train)
150
+ return K.switch(X > self.theta, X, 0)
151
+
152
+ def get_config(self):
153
+ config = {"name": self.__class__.__name__,
154
+ "theta": self.theta}
155
+ base_config = super(ThresholdedReLU, self).get_config()
156
+ return dict(list(base_config.items()) + list(config.items()))
Binary file