Skip to content

Commit

Permalink
Merge pull request #100 from ricardomourarpm/master
Browse files Browse the repository at this point in the history
Changes in hitmap mainly, done by me to correct positions
  • Loading branch information
sevamoo authored Mar 4, 2019
2 parents 5b5f08d + a66426e commit 304b49d
Show file tree
Hide file tree
Showing 14 changed files with 261 additions and 187 deletions.
5 changes: 4 additions & 1 deletion sompy/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from logging.config import dictConfig

from logging.config import dictConfig
import matplotlib

#matplotlib.use('Agg') # Use whatever backend is available

dictConfig({
Expand All @@ -24,5 +25,7 @@
}
})



from .sompy import SOMFactory
from .visualization import *
26 changes: 13 additions & 13 deletions sompy/codebook.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import numpy as np
import scipy as sp
from sklearn.decomposition import PCA

from sklearn.decomposition import PCA
#from sklearn.decomposition import RandomizedPCA# (randomizedpca is deprecated)
from .decorators import timeit


Expand All @@ -12,14 +13,13 @@ class InvalidNodeIndexError(Exception):
class InvalidMapsizeError(Exception):
pass


def generate_hex_lattice(n_rows, n_columns):
x_coord = []
y_coord = []
for i in range(n_rows):
for j in range(n_columns):
x_coord.append(i * 1.5)
y_coord.append(np.sqrt(2 / 3) * (2 * j + (1 + i) % 2))
x_coord.append(i*1.5)
y_coord.append(np.sqrt(2/3)*(2*j+(1+i)%2))
coordinates = np.column_stack([x_coord, y_coord])
return coordinates

Expand All @@ -35,13 +35,13 @@ def __init__(self, mapsize, lattice='rect'):
elif 1 == len(mapsize):
_size = [1, mapsize[0]]
print('input was considered as the numbers of nodes')
print('map size is [{dlen},{dlen}]'.format(dlen=int(mapsize[0] / 2)))
print('map size is [{dlen},{dlen}]'.format(dlen=int(mapsize[0]/2)))
else:
raise InvalidMapsizeError(
"Mapsize is expected to be a 2 element list or a single int")

self.mapsize = _size
self.nnodes = mapsize[0] * mapsize[1]
self.nnodes = mapsize[0]*mapsize[1]
self.matrix = np.asarray(self.mapsize)
self.initialized = False

Expand All @@ -59,7 +59,7 @@ def random_initialization(self, data):
"""
mn = np.tile(np.min(data, axis=0), (self.nnodes, 1))
mx = np.tile(np.max(data, axis=0), (self.nnodes, 1))
self.matrix = mn + (mx - mn) * (np.random.rand(self.nnodes, data.shape[1]))
self.matrix = mn + (mx-mn)*(np.random.rand(self.nnodes, data.shape[1]))
self.initialized = True

@timeit()
Expand Down Expand Up @@ -108,8 +108,8 @@ def pca_linear_initialization(self, data):

mx = np.max(coord, axis=0)
mn = np.min(coord, axis=0)
coord = (coord - mn) / (mx - mn)
coord = (coord - .5) * 2
coord = (coord - mn)/(mx-mn)
coord = (coord - .5)*2
me = np.mean(data, 0)
data = (data - me)
tmp_matrix = np.tile(me, (self.nnodes, 1))
Expand All @@ -122,11 +122,11 @@ def pca_linear_initialization(self, data):
eigvec = pca.components_
eigval = pca.explained_variance_
norms = np.sqrt(np.einsum('ij,ij->i', eigvec, eigvec))
eigvec = ((eigvec.T / norms) * eigval).T
eigvec = ((eigvec.T/norms)*eigval).T

for j in range(self.nnodes):
for i in range(eigvec.shape[0]):
tmp_matrix[j, :] = tmp_matrix[j, :] + coord[j, i] * eigvec[i, :]
tmp_matrix[j, :] = tmp_matrix[j, :] + coord[j, i]*eigvec[i, :]

self.matrix = np.around(tmp_matrix, decimals=6)
self.initialized = True
Expand Down Expand Up @@ -169,7 +169,7 @@ def _rect_dist(self, node_ind):
dist = None

# bmu should be an integer between 0 to no_nodes
if 0 <= node_ind <= (rows * cols):
if 0 <= node_ind <= (rows*cols):
node_col = int(node_ind % cols)
node_row = int(node_ind / cols)
else:
Expand All @@ -179,7 +179,7 @@ def _rect_dist(self, node_ind):
if rows > 0 and cols > 0:
r = np.arange(0, rows, 1)[:, np.newaxis]
c = np.arange(0, cols, 1)
dist2 = (r - node_row)**2 + (c - node_col)**2
dist2 = (r-node_row)**2 + (c-node_col)**2

dist = dist2.ravel()
else:
Expand Down
6 changes: 2 additions & 4 deletions sompy/examples/AirFlights_hexagonal_grid.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -354,12 +354,10 @@
]
},
{
"cell_type": "code",
"execution_count": null,
"cell_type": "raw",
"metadata": {},
"outputs": [],
"source": [
"%time\n",
"%%time\n",
"# Train the model with different parameters. The more, the better. Each iteration is stored in disk for further study\n",
"for i in range(1000):\n",
" sm = SOMFactory().build(data, mapsize=[random.choice(list(range(15, 25))), \n",
Expand Down
7 changes: 3 additions & 4 deletions sompy/neighborhood.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import numpy as np
import inspect
import sys

import numpy as np

small = .000000000001


Expand All @@ -25,7 +24,7 @@ class GaussianNeighborhood(object):

@staticmethod
def calculate(distance_matrix, radius, dim):
return np.exp(-1.0 * distance_matrix / (2.0 * radius**2)).reshape(dim, dim)
return np.exp(-1.0*distance_matrix/(2.0*radius**2)).reshape(dim, dim)

def __call__(self, *args, **kwargs):
return self.calculate(*args)
Expand All @@ -39,7 +38,7 @@ class BubbleNeighborhood(object):
def calculate(distance_matrix, radius, dim):
def l(a, b):
c = np.zeros(b.shape)
c[a - b >= 0] = 1
c[a-b >= 0] = 1
return c

return l(radius,
Expand Down
9 changes: 4 additions & 5 deletions sompy/normalization.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import inspect
import sys

import numpy as np
import sys
import inspect


class NormalizerFactory(object):
Expand Down Expand Up @@ -38,12 +37,12 @@ def _mean_and_standard_dev(self, data):
def normalize(self, data):
me, st = self._mean_and_standard_dev(data)
st[st == 0] = 1 # prevent: when sd = 0, normalized result = NaN
return (data - me) / st
return (data-me)/st

def normalize_by(self, raw_data, data):
me, st = self._mean_and_standard_dev(raw_data)
st[st == 0] = 1 # prevent: when sd = 0, normalized result = NaN
return (data - me) / st
return (data-me)/st

def denormalize_by(self, data_by, n_vect):
me, st = self._mean_and_standard_dev(data_by)
Expand Down
Loading

0 comments on commit 304b49d

Please sign in to comment.