Revision 9e7b5d4c
Added by David Sorber over 12 years ago
| software/PMML_translator/neural_network_model/neuron.py | ||
|---|---|---|
|
import math
|
||
|
|
||
|
class Neuron(object):
|
||
|
|
||
|
def __init__(self, layer, index, bias=0):
|
||
|
self.layer = layer
|
||
|
self.index = index
|
||
|
self.bias = bias
|
||
|
|
||
|
# key: (from layer, from index)
|
||
|
# value: <weight>
|
||
|
self.edges = {}
|
||
|
|
||
|
# Activation Function (logistic/sigmoid in this case)
|
||
|
# this should be passed as a parameter
|
||
|
self.act_func = lambda x: (1 / (1 + math.exp(-x)))
|
||
|
|
||
|
self.value = 0
|
||
|
|
||
|
def add_edge(self, key, weight):
|
||
|
""" Add new edge connection """
|
||
|
if key in self.edges:
|
||
|
raise Exception('edge already present')
|
||
|
|
||
|
self.edges[key] = weight
|
||
|
|
||
|
def calculate(self, inputs):
|
||
|
""" Calculate and return the neuron's output"""
|
||
|
# make sure number of inputs matches the number of edges/weights
|
||
|
if len(self.edges) != len(inputs):
|
||
|
msg = 'The number of inputs ({:d}) does not match the '\
|
||
|
'number of expected edges ({:d})'\
|
||
|
.format(len(self.edges), len(inputs))
|
||
|
raise Exception(msg)
|
||
|
|
||
|
# multiply each input by its weight and sum them all
|
||
|
for key, input_ in zip(sorted(self.edges), inputs):
|
||
|
weight = self.edges[key]
|
||
|
self.value += weight * input_
|
||
|
|
||
|
# add in the bias
|
||
|
self.value += self.bias
|
||
|
|
||
|
# ACTIVATE!
|
||
|
self.value = self.act_func(self.value)
|
||
|
return self.value
|
||
| software/PMML_translator/neural_network_model/parser.py | ||
|---|---|---|
|
import sys
|
||
|
|
||
|
import lxml.etree as ET
|
||
|
|
||
|
from neuron import Neuron
|
||
|
|
||
|
pmml_ns = 'http://www.dmg.org/PMML-4_1'
|
||
|
|
||
|
def _(string):
|
||
|
return '{{{:s}}}{:s}'.format(pmml_ns, string)
|
||
|
|
||
|
def main():
|
||
|
if len(sys.argv) < 2:
|
||
|
print 'ERROR: not enough arguments specified'
|
||
|
return 1
|
||
|
|
||
|
tree = ET.parse(sys.argv[1])
|
||
|
root = tree.getroot()
|
||
|
|
||
|
network = root.findall(_('NeuralNetwork'))
|
||
|
|
||
|
print network
|
||
|
print _('NeuralNetwork')
|
||
|
|
||
|
if __name__ == '__main__':
|
||
|
sys.exit(main())
|
||
Adding work that I started on the PMML translator prototype.