我们从Python开源项目中,提取了以下2个代码示例,用于说明如何使用keras.backend.prod()。
def tf_normal(y, mu, sigma): oneDivSqrtTwoPI = 1 / math.sqrt(2*math.pi) result = y - mu result = K.permute_dimensions(result, [2,1,0]) result = result * (1 / (sigma + 1e-8)) result = -K.square(result)/2 result = K.exp(result) * (1/(sigma + 1e-8))*oneDivSqrtTwoPI result = K.prod(result, axis=[0]) return result
def call(self, x, mask=None): input_vector = x[0] target_classes = x[1] nb_req_classes = self.input_spec[1].shape[1] if nb_req_classes is None: nb_req_classes = K.shape(target_classes) if K.dtype(target_classes) != 'int32': target_classes = K.cast(target_classes, 'int32') if self.mode == 0: # One giant matrix mul input_dim = self.input_spec[0].shape[1] nb_req_classes = self.input_spec[1].shape[1] path_lengths = map(len, self.paths) huffman_codes = K.variable(np.array(self.huffman_codes)) req_nodes = K.gather(self.class_path_map, target_classes) req_W = K.gather(self.W, req_nodes) y = K.batch_dot(input_vector, req_W, axes=(1, 3)) if self.bias: req_b = K.gather(self.b, req_nodes) y += req_b y = K.sigmoid(y[:, :, :, 0]) req_huffman_codes = K.gather(huffman_codes, target_classes) return K.prod(req_huffman_codes + y - 2 * req_huffman_codes * y, axis=-1) # Thug life elif self.mode == 1: # Many tiny matrix muls probs = [] for i in range(len(self.paths)): huffman_code = self.huffman_codes[i] path = self.paths[i] prob = 1. for j in range(len(path)): node = path[j] node_index = self.node_indices[node] p = K.dot(input_vector, self.W[node_index, :, :])[:, 0] if self.bias: p += self.b[node_index, :][0] h = huffman_code[j] p = K.sigmoid(p) prob *= h + p - 2 * p * h probs += [prob] probs = K.pack(probs) req_probs = K.gather(probs, target_classes) req_probs = K.permute_dimensions(req_probs, (0, 2, 1)) req_probs = K.reshape(req_probs, (-1, nb_req_classes)) batch_size = K.shape(input_vector)[0] indices = arange(batch_size * batch_size, batch_size + 1) req_probs = K.gather(req_probs, indices) return req_probs