From 4a5afaf23ebe02e5604b68776ebbed4b340f3236 Mon Sep 17 00:00:00 2001 From: Erin Wild Date: Mon, 18 Feb 2019 19:40:57 -0500 Subject: [PATCH 1/8] Delete compiled files --- .directory | 11 ----------- sompy/visualization/__init__.pyc | Bin 258 -> 0 bytes sompy/visualization/dotmap.pyc | Bin 2554 -> 0 bytes sompy/visualization/histogram.pyc | Bin 2631 -> 0 bytes sompy/visualization/hitmap.pyc | Bin 1498 -> 0 bytes sompy/visualization/mapview.pyc | Bin 5188 -> 0 bytes sompy/visualization/umatrix.pyc | Bin 3962 -> 0 bytes sompy/visualization/view.pyc | Bin 2790 -> 0 bytes 8 files changed, 11 deletions(-) delete mode 100644 .directory delete mode 100644 sompy/visualization/__init__.pyc delete mode 100644 sompy/visualization/dotmap.pyc delete mode 100644 sompy/visualization/histogram.pyc delete mode 100644 sompy/visualization/hitmap.pyc delete mode 100644 sompy/visualization/mapview.pyc delete mode 100644 sompy/visualization/umatrix.pyc delete mode 100644 sompy/visualization/view.pyc diff --git a/.directory b/.directory deleted file mode 100644 index ae11fe3..0000000 --- a/.directory +++ /dev/null @@ -1,11 +0,0 @@ -[Dolphin] -<<<<<<< HEAD -Timestamp=2017,2,7,17,30,1 -Version=3 - -[Settings] -HiddenFilesShown=true -======= -Timestamp=2017,2,8,12,4,41 -Version=3 ->>>>>>> 503c114584bd9cb91d18379b03a6c9f494d8b4fc diff --git a/sompy/visualization/__init__.pyc b/sompy/visualization/__init__.pyc deleted file mode 100644 index b79a07683264c8f0dfb137923d771c8c4f166e7e..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 258 zcmYk0O-{ow5QU%f0|kjQu+0KB7eG}{&_!5O@+PuKMMlcRQ9KDv55^%lO1E5qanwaE zzt3a6d1I%4FVEMX-{U84E75bW3U7)=w?PN6fi>U+HUX!wDL8}8z&UIV(JH&mufg-Mlrx3Nb#!q;zAx*VdXl={4vTEG=be2sb*Eh%8C3WO-YhW! diff --git a/sompy/visualization/dotmap.pyc b/sompy/visualization/dotmap.pyc deleted file mode 100644 index df31810204fa9bc9ec3ac76331b0595c366dd97a..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 2554 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 diff --git a/sompy/visualization/mapview.pyc b/sompy/visualization/mapview.pyc deleted file mode 100644 index dd70a4430ae375e62bd4e7837c8d40aa2fb7f013..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 5188 zcmb`LOOGR0701slyFIqs{eDjfj|n73%47(L1jIlOGf@(d#v0W`8PXc5sCJdR%Uyn? z>h^T^$SooDWEru^Ciw!04H7~^;R}FZ5d{{k*|J249RmLUbE|DLfM|xeUDx-X`#$%c z-#OK#KhM?QZ~XRNTZ&H!zc=vY?;(lsHIj<#Amd3?lGI4glO0bC>&mR_m1L*v%4j*!l$uWpU)ZC#6Il36>gY13J%epHi=Cuc?=j4(}^l2xdB)x$KHtp7`~4bF!) zc21}K1COGZZ=QK}$4qlYv(XF}aXqTaeXQM$@`I^S7Ic*Fn^9T1i|oI3S{J)i^ya|R zYp!$n|F~xEdAaE6HvI2*0sU5GRFXAJw{bcvBkX=g4vb`H1~sP*=~q~f4Ay>%tzg~r zGJ;|kWP}XT8TJ}M8FSL9;Lg-=bS=xf9j0l5AKB~Z=l9zQk5_L}!b5JdQLEKzdK6RQ z#4E_@EeraCtQV%q!#K0^5JvG>5bU1VDn+3UgDgDKLVFO!yMw`jR!A8MO03;TPqv-?R{Mj7uz1BLH^LE>1b`zkL)1d9~|jw z^Echk>pBAWz_n(fO$Is})~X{>NBu#N4UU4OAE+@FB94D9qT0gaBoF$BZlI$iviqu! z{W#g%w@ow`faQFZQ{=)FYZlX=l4%7Bw8rnGMBzuQh z91Nk`Ue2B7*O7=>Fbm#-*Dy7+X4dg+ddsE)=_2IIX3jKJx(xX|@-?r*KU47*jNTJH z;2`LSy*LP93YatK4Wh#oMgLh8C#$~j(tTb9>O5zr;;9bEtuMbaCKok*lTDsRGA0)= z15EJi$)mFDlt?jNH9bO~7rV`K<@s0f+`^OpoIC@}lxnaln9f;A?!&^c84wOBj7&)e za|e3ZxJ0BIVh~&aV8DcmbRE;co|<%lg}QWS*$zy=f+&PNP6<~xvDAyU-2f{}hYmI! z*qsGWnf4~bl!E>Ss(i9SEtc^OH?s~H3oB91Qw8Hv?+3jJKT1P~SGQB-J9 zqr}mnX%P`^fLd?q9oGXGbUNy|{g)v3zk$T5N6(qW)N}6T55IJtd2ynqi)cvieZX7C zE9hgyoJbY3h0}P9v#XHvn&>8ff_uSeOXQ#`8R(#aSl_`{Bgx0%3nl@+fY&s9r;v-7 zY}lRxuZs;46}mPx4e4gdK1%8eJdNQQi+*HqI)E8d#7l@p5k~@Lpv}grgFXOyE}Sof za1S^qrMfx(n?e|)k0JaUg>Xe7%!YH)1*4}q3@k57cY!f7kIUD%>58r;pcbN4v1@t+AL}^l1V3Ijwnj_f zJC+2Dve|}24SDHwMH_8O1ZS}#?~=nG3%>Vwa8TyF#>ek@Cuq1uJx8E57FkD&6){F{ z>}4VwqP~&uMT@HSCDl3t+htk9ba1h71LuWlEpsiZMx2fN(w$*bb@_DnLTV`#f~EYc zLa+-u?x!Szrf?bH*06r@oNbZREscIP&hewS(wm1trnh|WgZKIQ#r7T=;Zwe${>Og} zdG$8RM*rI^vfgo*B&X?j28df}8twEjw?!ab4U6xjIK`Xsvs$u_ZRtd*1p>fpG! ztgTAH%HTUQzs2_If6S? zrbj+G=@VN1D@<-9`QIR^?&lu5DIkUMwRaVsY||_w(rzHauE3MQpQ%q<9J`VRj&CR~{+`~P!%uVR=xc$DUFd^2!; z1Up^di=R~B&Hr5R)~iGK6*4qQq(IIS2j0iIVi*)1WB5Z2bB&9IH7K8Eu))PEplb@~ zg00igomJ>EW=3b=L*KLE#^Ec@JY(K|6_F@voErdhonLqVjnS8us|R|y)1)8kYg}Q= zf81^|ns_YobY@1i_*Et}IOo0@7r3a9_NOr-10?+i(34*O@wI+}8~sB}p40X;GV>aG zdslFC*KuDz**Gl3B=2%M?woO0lM%Lm4T%Djuel69#K-HKQGf~^19wlU`Tzg` diff --git a/sompy/visualization/umatrix.pyc b/sompy/visualization/umatrix.pyc deleted file mode 100644 index 91fffb986dc514f2ee8fc495c1920a3fcdefd8d7..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 3962 zcmb7HOLH7a5zguvjij+glJ&A=JuDfocXqui6FvdqV8JWkK;R(SYaFXsM{iG8&rFZ{ zG3u_7W*psIWPSjDg##yU-1rNe;lODlIB|k6vqq8?I07S2S65|c<*UBROxOO|YX0Mo ze|Z(q^sk2ZPw*6D3>rU0F;SxESdr2W=^DijB{e#(+jX7d8A=*-+@NHZj%O`(hT=I& z=IMCet{W6L>G&401k4xcc!BgRg^Ie0^c=kWD9 z8#42kLh3B@==HZ$VH@_((H3iN%Fz=2&SAA%75MA&QP=5S>Cg!bY08EszTV;!7%b4B zMI|_I(S<{UMLw_+*3Qw>(+R!8bg*=(cA3?_XtVdvB_MJzNoe|+HXNlhKacRD_H7Ji z1w-J+!6^1k=q3Kp(@|jzpJ+NXEagp@XN8$#zD$RmEISd2X^K^0h0Afu(Ryi?Cw?4Z zli@?ST6&!cyeIlfWafU_3k4==cvysoKQBtPSqICzv`hA)jSnP4v4PbsikV?vfIh=pkX4vdISM$<50nKoSb=Ham@nRl)tt0usc*9X4NP zyQIOmLmCsNI?C+v$7+MKWggY_9_f1&-=k!osyirFSnpGOK*@coHnE11Ia;q^J?v&H zNtK&C(+8yQll~s*2c$nD{g6GVU^%?GI<=M@kpUBMreNrQeSG@AA$w)=xUC@I==HAR z($J77Z&S5H)viSO0hK#cZnMr34u4F#P5Kjo$ERdI0sv~&9+fQ`JfsqFfG_4_8nkKf z$xX1q{?=u2;H&Z}ONH#7)F`Grx^|LriO5&?sKjqqipRd#^VvQ6c~UTCkQn!+Mgj6J$JV;x}3gjWkOb>0BKv2 zv#Y<3pN+g+N`W5_`@WQ^h--l4+&Dt9h_vY!y{`QI{R`oJ7LQPfxVRJ%*R38N{C)R@ z&;lt1zsUWGWb(w%Pf(kfJCoWl2u)PO3WXc}hVF$y79-U&DeHEn5RNBi70Z5>M{m&8 z_%V`oFHOSKh{ymFh~#8@hIfQ=dXu4#au$SBv!IDPrE{UZ(@t^D&U>9FJy>d+CZ=@a ztmDO5PpnJ)u~$UB#E-aI3Mm~WQxeBgNT$z4F^hHYumAe(;7{hyHcHoS<)IeFt9VL; zx=|b#9KOT6{TMIz0S{bn+)WHp&4+n5Kqd6FZ+u%&G4XQ$+_b>bNk&}!Jd=5d7zc0| z8(}L(9qtngm*q=H16z>M1b7SpmxC``lE@bJF8UFJz_J+lE$_l;dxoKo{M40G;~>Ei ziKcBG0^XR5PtsX%V7|&np&XE{rfk0#`<*Z@MDUx)LeNK31JA;#HVegWoIxU^uzSfYm$woOjBPyUk^s;q*#5-Eft5TIEfO!7aq!CxIX~J3Z9a?p>IZc z=>8BNTscsN%9l|d#Gyd_=Y9+$I9R^c9-5?}?=m#qH6FO@u(u}%h+J;%L_Nn|0_P8h zA-WTm%zb*Bdjxljhr7(naxYt?Cvr`N#H`mxE`5E58^Tf;o+5b~Or~-FVvntOW7PvS zVpf1{w$bWFJ%IrZmLZX(_BD2YiItse*&=e~wvJ_-2sP(UNpb>OJa3o*GlfJ`A}1^o zXPL2$_L$M}iD8Jo2+Q3^td5PArkDM{64=J#gF7|117>OH&|(oeE9k=()CxMYO?BUC zsP*Z;MRlMyu>PsqQpr@pW5gVF-u0c5uD z9AVez>QFrZN1O2>SIqNLKM6fgqT+c;rbjWB?rSjEtNd%8v7OhR$?O9fQJ3?LM2Gb? zoTb%y)#m0@Vt0oB$GKS8EREA=yv0$+H0-ZUK%!U(5 f1s2py`~QuVa6GjE__0(4zNd&NV!MpkE!6%4Lt!BG diff --git a/sompy/visualization/view.pyc b/sompy/visualization/view.pyc deleted file mode 100644 index 41d15778e51b21977dca29d3a20efd240380eea4..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 2790 zcmbtW!EPf(5UrW99orDd1_%-f5(o(l2UZ;50$Qy=AR&Q~I%pBTj3zVfc$~3kG~He& ztDH!#Aijo=;8VEr0q|ap69;J_ad6V*>YkqNs#jI79R0c7|Kqpce@JEZiSYdx!%<}T z52O&81u_aH$U?D^j04FcxfHn&`Ek^etR=RktL^L6wqzYS9Bko`{4ab40W{x%sLraQ z^u7i4Np6?d7xUTY817RDD>4ei;<}JVP~y^1F55DSR<}1d!;BFw)0;;fF^2;lbUfBi z=W)(i+JkrjBgFU)!+isB9>}>!3?)K5ni&SyCNfT~xSzXs(=9XAhs|ZjluE zv&84+95cK8usTx%;y9n@K8|^X+u^%mFSz-aGRQQA--`1#6t9W$6XLf9O0(e=JRFw( z>seLUnVox^eOcFKJy2)*cxdRUc@bg*OX+r1+bXFoZFIy(f|Oqzy!i_Z_g|)&m#|}? z$kGn=ew-I}p3Lk9rZ6Bbd1~qCl^q*F)Y$P)JTzramUXgG{L~a=-QL<1EzVV7=~x_l zIvdBcGFud!@}=+Vg*C*=yiDX9jE%D*rL&C(2h1O*xFl`JkonSvdlLxLT^3t$9r z0Z0LK(3A7N{L%$af>eMcsBxY0tQw^Ox2SAwUdL2%Rg{P2+^Q0f^J6V=L*wpR-1jLI zz5D=|xGsc*`zYn@Kueghx~>zJ0-Tv@71OgTvg3{>W748@RxRh6TE0$?Td9Qw8^@U~ z;`kk?Hw%Twu?n?d--6N@QXeoLj6`EsAi-Rl)s<;lF>heMr&bjW|EihF)Ek;;$d2z~ zxE6!}sB5NUR5ee=P}VRt=AmbCNxRAv9Wq4646p(Q1!rkCG1qf&!T66#i zMF(V1eHTI0;K85_l}LP@%pI8@5D=5B%60wds60jUN+;Getgg911WC^ Date: Mon, 18 Feb 2019 19:43:28 -0500 Subject: [PATCH 2/8] Use github's gitignore template for python --- .gitignore | 117 ++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 116 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 8d1c8b6..0447b8b 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,116 @@ - +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +pip-wheel-metadata/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +.hypothesis/ +.pytest_cache/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +.python-version + +# celery beat schedule file +celerybeat-schedule + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ From 81a1e945dfc761898695eb3311b38f9e9bf971d9 Mon Sep 17 00:00:00 2001 From: Erin Wild Date: Mon, 18 Feb 2019 19:47:20 -0500 Subject: [PATCH 3/8] Remove trailing whitespace and add whitespace around operators --- sompy/codebook.py | 22 ++++---- sompy/neighborhood.py | 4 +- sompy/normalization.py | 4 +- sompy/sompy.py | 88 +++++++++++++++---------------- sompy/visualization/bmuhits.py | 6 +-- sompy/visualization/dotmap.py | 16 +++--- sompy/visualization/histogram.py | 8 +-- sompy/visualization/hitmap.py | 6 +-- sompy/visualization/mapview.py | 27 +++++----- sompy/visualization/plot_tools.py | 2 +- sompy/visualization/umatrix.py | 6 +-- 11 files changed, 92 insertions(+), 97 deletions(-) diff --git a/sompy/codebook.py b/sompy/codebook.py index 1195347..f343da0 100644 --- a/sompy/codebook.py +++ b/sompy/codebook.py @@ -18,8 +18,8 @@ def generate_hex_lattice(n_rows, n_columns): 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 @@ -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 @@ -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() @@ -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)) @@ -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 @@ -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: @@ -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: diff --git a/sompy/neighborhood.py b/sompy/neighborhood.py index a4d2c9c..08d35e2 100644 --- a/sompy/neighborhood.py +++ b/sompy/neighborhood.py @@ -24,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) @@ -38,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, diff --git a/sompy/normalization.py b/sompy/normalization.py index cf833ca..1a6f3d4 100644 --- a/sompy/normalization.py +++ b/sompy/normalization.py @@ -37,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) diff --git a/sompy/sompy.py b/sompy/sompy.py index 5a32675..54b3547 100644 --- a/sompy/sompy.py +++ b/sompy/sompy.py @@ -155,7 +155,7 @@ def component_names(self, compnames): 'size as the data dimension/features') def build_component_names(self): - cc = ['Variable-' + str(i+1) for i in range(0, self._dim)] + cc = ['Variable-' + str(i + 1) for i in range(0, self._dim)] return np.asarray(cc)[np.newaxis, :] @property @@ -243,9 +243,9 @@ def train(self, self.codebook.pca_linear_initialization(self._data) self.rough_train(njob=n_job, shared_memory=shared_memory, trainlen=train_rough_len, - radiusin=train_rough_radiusin, radiusfin=train_rough_radiusfin,trainlen_factor=train_len_factor,maxtrainlen=maxtrainlen) + radiusin=train_rough_radiusin, radiusfin=train_rough_radiusfin, trainlen_factor=train_len_factor, maxtrainlen=maxtrainlen) self.finetune_train(njob=n_job, shared_memory=shared_memory, trainlen=train_finetune_len, - radiusin=train_finetune_radiusin, radiusfin=train_finetune_radiusfin,trainlen_factor=train_len_factor,maxtrainlen=maxtrainlen) + radiusin=train_finetune_radiusin, radiusfin=train_finetune_radiusfin, trainlen_factor=train_len_factor, maxtrainlen=maxtrainlen) logging.debug( " --------------------------------------------------------------") logging.info(" Final quantization error: %f" % np.mean(self._bmu[1])) @@ -255,55 +255,54 @@ def _calculate_ms_and_mpd(self): max_s = max(self.codebook.mapsize[0], self.codebook.mapsize[1]) if mn == 1: - mpd = float(self.codebook.nnodes*10)/float(self._dlen) + mpd = float(self.codebook.nnodes * 10) / float(self._dlen) else: - mpd = float(self.codebook.nnodes)/float(self._dlen) - ms = max_s/2.0 if mn == 1 else max_s + mpd = float(self.codebook.nnodes) / float(self._dlen) + ms = max_s / 2.0 if mn == 1 else max_s return ms, mpd - def rough_train(self, njob=1, shared_memory=False, trainlen=None, radiusin=None, radiusfin=None,trainlen_factor=1,maxtrainlen=np.Inf): + def rough_train(self, njob=1, shared_memory=False, trainlen=None, radiusin=None, radiusfin=None, trainlen_factor=1, maxtrainlen=np.Inf): logging.info(" Rough training...") ms, mpd = self._calculate_ms_and_mpd() #lbugnon: add maxtrainlen - trainlen = min(int(np.ceil(30*mpd)),maxtrainlen) if not trainlen else trainlen + trainlen = min(int(np.ceil(30 * mpd)), maxtrainlen) if not trainlen else trainlen #print("maxtrainlen %d",maxtrainlen) #lbugnon: add trainlen_factor - trainlen=int(trainlen*trainlen_factor) - + trainlen = int(trainlen * trainlen_factor) + if self.initialization == 'random': - radiusin = max(1, np.ceil(ms/3.)) if not radiusin else radiusin - radiusfin = max(1, radiusin/6.) if not radiusfin else radiusfin + radiusin = max(1, np.ceil(ms / 3.)) if not radiusin else radiusin + radiusfin = max(1, radiusin / 6.) if not radiusfin else radiusfin elif self.initialization == 'pca': - radiusin = max(1, np.ceil(ms/8.)) if not radiusin else radiusin - radiusfin = max(1, radiusin/4.) if not radiusfin else radiusfin + radiusin = max(1, np.ceil(ms / 8.)) if not radiusin else radiusin + radiusfin = max(1, radiusin / 4.) if not radiusfin else radiusfin self._batchtrain(trainlen, radiusin, radiusfin, njob, shared_memory) - def finetune_train(self, njob=1, shared_memory=False, trainlen=None, radiusin=None, radiusfin=None,trainlen_factor=1,maxtrainlen=np.Inf): + def finetune_train(self, njob=1, shared_memory=False, trainlen=None, radiusin=None, radiusfin=None, trainlen_factor=1, maxtrainlen=np.Inf): logging.info(" Finetune training...") ms, mpd = self._calculate_ms_and_mpd() #lbugnon: add maxtrainlen if self.initialization == 'random': - trainlen = min(int(np.ceil(50*mpd)),maxtrainlen) if not trainlen else trainlen - radiusin = max(1, ms/12.) if not radiusin else radiusin # from radius fin in rough training - radiusfin = max(1, radiusin/25.) if not radiusfin else radiusfin + trainlen = min(int(np.ceil(50 * mpd)), maxtrainlen) if not trainlen else trainlen + radiusin = max(1, ms / 12.) if not radiusin else radiusin # from radius fin in rough training + radiusfin = max(1, radiusin / 25.) if not radiusfin else radiusfin elif self.initialization == 'pca': - trainlen = min(int(np.ceil(40*mpd)),maxtrainlen) if not trainlen else trainlen - radiusin = max(1, np.ceil(ms/8.)/4) if not radiusin else radiusin + trainlen = min(int(np.ceil(40 * mpd)), maxtrainlen) if not trainlen else trainlen + radiusin = max(1, np.ceil(ms / 8.) / 4) if not radiusin else radiusin radiusfin = 1 if not radiusfin else radiusfin # max(1, ms/128) #print("maxtrainlen %d",maxtrainlen) - + #lbugnon: add trainlen_factor - trainlen=int(trainlen_factor*trainlen) - - + trainlen = int(trainlen_factor * trainlen) + self._batchtrain(trainlen, radiusin, radiusfin, njob, shared_memory) def _batchtrain(self, trainlen, radiusin, radiusfin, njob=1, @@ -350,9 +349,9 @@ def _batchtrain(self, trainlen, radiusin, radiusfin, njob=1, qerror) if np.any(np.isnan(qerror)): logging.info("nan quantization error, exit train\n") - + #sys.exit("quantization error=nan, exit train") - + bmu[1] = np.sqrt(bmu[1] + fixed_euclidean_x2) self._bmu = bmu @@ -380,7 +379,7 @@ def row_chunk(part): return part * dlen // njb def col_chunk(part): - return min((part+1)*dlen // njb, dlen) + return min((part + 1) * dlen // njb, dlen) chunks = [input_matrix[row_chunk(i):col_chunk(i)] for i in range(njb)] b = pool.map(lambda chk: chunk_bmu_finder(chk, self.codebook.matrix, y2, nth=nth), chunks) @@ -465,7 +464,7 @@ def predict_by(self, data, target, k=5, wt='distance'): data = self._normalizer.normalize_by(self.data_raw, data) data = data[:, indX] - elif dimdata == dim-1: + elif dimdata == dim - 1: data = self._normalizer.normalize_by(self.data_raw[:, indX], data) predicted_values = clf.predict(data) @@ -485,7 +484,7 @@ def predict(self, x_test, k=5, wt='distance'): (more detail in KNeighborsRegressor docs) :returns: predicted values for the input data """ - target = self.data_raw.shape[1]-1 + target = self.data_raw.shape[1] - 1 x_train = self.codebook.matrix[:, :target] y_train = self.codebook.matrix[:, target] clf = neighbors.KNeighborsRegressor(k, weights=wt) @@ -528,7 +527,7 @@ def bmu_ind_to_xy(self, bmu_ind): # bmu should be an integer between 0 to no_nodes out = np.zeros((bmu_ind.shape[0], 3)) out[:, 2] = bmu_ind - out[:, 0] = rows-1-bmu_ind / cols + out[:, 0] = rows - 1 - bmu_ind / cols out[:, 0] = bmu_ind / cols out[:, 1] = bmu_ind % cols @@ -571,14 +570,14 @@ def predict_probability(self, data, target, k=5): data = self._normalizer.normalize_by(self.data_raw, data) data = data[:, indx] - elif dimdata == dim-1: + elif dimdata == dim - 1: data = self._normalizer.normalize_by(self.data_raw[:, indx], data) weights, ind = clf.kneighbors(data, n_neighbors=k, return_distance=True) - weights = 1./weights + weights = 1. / weights sum_ = np.sum(weights, axis=1) - weights = weights/sum_[:, np.newaxis] + weights = weights / sum_[:, np.newaxis] labels = np.sign(self.codebook.matrix[ind, target]) labels[labels >= 0] = 1 @@ -612,7 +611,7 @@ def node_activation(self, data, target=None, wt='distance'): weights, ind = clf.kneighbors(data) # Softmax function - weights = 1./weights + weights = 1. / weights return weights, ind @@ -620,10 +619,10 @@ def calculate_topographic_error(self): bmus1 = self.find_bmu(self.data_raw, njb=1, nth=1) bmus2 = self.find_bmu(self.data_raw, njb=1, nth=2) topographic_error = None - if self.codebook.lattice=="rect": + if self.codebook.lattice == "rect": bmus_gap = np.abs((self.bmu_ind_to_xy(np.array(bmus1[0]))[:, 0:2] - self.bmu_ind_to_xy(np.array(bmus2[0]))[:, 0:2]).sum(axis=1)) topographic_error = np.mean(bmus_gap != 1) - elif self.codebook.lattice=="hexa": + elif self.codebook.lattice == "hexa": dist_matrix_1 = self.codebook.lattice_distances[bmus1[0].astype(int)].reshape(len(bmus1[0]), -1) topographic_error = (np.array( [distances[bmu2] for bmu2, distances in zip(bmus2[0].astype(int), dist_matrix_1)]) > 2).mean() @@ -666,7 +665,7 @@ def calculate_map_size(self, lattice): if lattice == "rect": size1 = min(munits, round(np.sqrt(munits / ratio))) else: - size1 = min(munits, round(np.sqrt(munits / ratio*np.sqrt(0.75)))) + size1 = min(munits, round(np.sqrt(munits / ratio * np.sqrt(0.75)))) size2 = round(munits / size1) @@ -699,19 +698,16 @@ def _chunk_based_bmu_find(input_matrix, codebook, y2, nth=1): blen = min(50, dlen) i0 = 0 - while i0+1 <= dlen: + while i0 + 1 <= dlen: low = i0 - high = min(dlen, i0+blen) - i0 = i0+blen - ddata = input_matrix[low:high+1] + high = min(dlen, i0 + blen) + i0 = i0 + blen + ddata = input_matrix[low:high + 1] d = np.dot(codebook, ddata.T) d *= -2 d += y2.reshape(nnodes, 1) - bmu[low:high+1, 0] = np.argpartition(d, nth, axis=0)[nth-1] - bmu[low:high+1, 1] = np.partition(d, nth, axis=0)[nth-1] + bmu[low:high + 1, 0] = np.argpartition(d, nth, axis=0)[nth - 1] + bmu[low:high + 1, 1] = np.partition(d, nth, axis=0)[nth - 1] del ddata return bmu - - - diff --git a/sompy/visualization/bmuhits.py b/sompy/visualization/bmuhits.py index d382fc6..bd265d7 100644 --- a/sompy/visualization/bmuhits.py +++ b/sompy/visualization/bmuhits.py @@ -19,13 +19,13 @@ def _set_labels(self, cents, ax, labels, onlyzeros, fontsize, hex=False): c = cents[i] if hex else (cents[i, 1] + 0.5, cents[-(i + 1), 0] + 0.5) ax.annotate(txt, c, va="center", ha="center", size=fontsize) - def show(self, som, anotate=True, onlyzeros=False, labelsize=7, cmap="jet", logaritmic = False): + def show(self, som, anotate=True, onlyzeros=False, labelsize=7, cmap="jet", logaritmic=False): org_w = self.width org_h = self.height (self.width, self.height, indtoshow, no_row_in_plot, no_col_in_plot, axis_num) = self._calculate_figure_params(som, 1, 1) - self.width /= (self.width/org_w) if self.width > self.height else (self.height/org_h) - self.height /= (self.width / org_w) if self.width > self.height else (self.height / org_h) + self.width /= (self.width / org_w) if self.width > self.height else (self.height / org_h) + self.height /= (self.width / org_w) if self.width > self.height else (self.height / org_h) counts = Counter(som._bmu[0]) counts = [counts.get(x, 0) for x in range(som.codebook.mapsize[0] * som.codebook.mapsize[1])] diff --git a/sompy/visualization/dotmap.py b/sompy/visualization/dotmap.py index 7ba10ff..8f38441 100644 --- a/sompy/visualization/dotmap.py +++ b/sompy/visualization/dotmap.py @@ -6,17 +6,17 @@ class DotMapView(MatplotView): def init_figure(self, dim, cols): - no_row_in_plot = dim/cols + 1 + no_row_in_plot = dim / cols + 1 no_col_in_plot = dim if no_row_in_plot <= 1 else cols h = .1 w = .1 - self.width = no_col_in_plot*2.5*(1+w) - self.height = no_row_in_plot*2.5*(1+h) + self.width = no_col_in_plot * 2.5 * (1 + w) + self.height = no_row_in_plot * 2.5 * (1 + h) self.prepare() def plot(self, data, coords, msz0, msz1, colormap, dlen, dim, rows, cols): for i in range(dim): - plt.subplot(rows, cols, i+1) + plt.subplot(rows, cols, i + 1) # This uses the colors uniquely for each record, while in normal # views, it is based on the values within each dimensions. This is @@ -28,7 +28,7 @@ def plot(self, data, coords, msz0, msz1, colormap, dlen, dim, rows, cols): for j in range(dlen): plt.scatter(coords[j, 1], - msz0-1-coords[j, 0], + msz0 - 1 - coords[j, 0], c=data[j, i], vmax=mx[j], vmin=mn[j], s=90, @@ -38,8 +38,8 @@ def plot(self, data, coords, msz0, msz1, colormap, dlen, dim, rows, cols): alpha=1) eps = .0075 - plt.xlim(0-eps, msz1-1+eps) - plt.ylim(0-eps, msz0-1+eps) + plt.xlim(0 - eps, msz1 - 1 + eps) + plt.ylim(0 - eps, msz0 - 1 + eps) plt.xticks([]) plt.yticks([]) @@ -50,7 +50,7 @@ def show(self, som, which_dim='all', colormap=None, cols=None): msz0, msz1 = som.codebook.mapsize coords = som.bmu_ind_to_xy(som.project_data(data))[:, :2] cols = cols if cols else 8 # 8 is arbitrary - rows = data.shape[1]/cols+1 + rows = data.shape[1] / cols + 1 if which_dim == 'all': dim = data.shape[0] diff --git a/sompy/visualization/histogram.py b/sompy/visualization/histogram.py index cc71996..bde155f 100644 --- a/sompy/visualization/histogram.py +++ b/sompy/visualization/histogram.py @@ -8,8 +8,8 @@ class Hist2d(MatplotView): def _fill_hist(self, x, y, mapsize, data_coords, what='train'): - x = np.arange(.5, mapsize[1]+.5, 1) - y = np.arange(.5, mapsize[0]+.5, 1) + x = np.arange(.5, mapsize[1] + .5, 1) + y = np.arange(.5, mapsize[0] + .5, 1) X, Y = np.meshgrid(x, y) if what == 'train': @@ -23,12 +23,12 @@ def _fill_hist(self, x, y, mapsize, data_coords, what='train'): else: a = plt.hist2d(x, y, bins=(mapsize[1], mapsize[0]), alpha=.0, cmap=cm.jet, norm=LogNorm()) - area = a[0].T*50 + area = a[0].T * 50 plt.scatter(data_coords[:, 1] + .5, mapsize[0] - .5 - data_coords[:, 0], s=area, alpha=0.9, c='None', marker='o', cmap='jet', linewidths=3, edgecolor='r') - plt.scatter(data_coords[:, 1]+.5, mapsize[0]-.5-data_coords[:, 0], + plt.scatter(data_coords[:, 1] + .5, mapsize[0] - .5 - data_coords[:, 0], s=area, alpha=0.2, c='b', marker='o', cmap='jet', linewidths=3, edgecolor='r') diff --git a/sompy/visualization/hitmap.py b/sompy/visualization/hitmap.py index 6227ff3..8cad393 100644 --- a/sompy/visualization/hitmap.py +++ b/sompy/visualization/hitmap.py @@ -44,7 +44,7 @@ def show(self, som, data=None, anotate=True, onlyzeros=False, labelsize=7, cmap= self._set_labels(cents, ax, clusters[proj], onlyzeros, labelsize, hex=False) else: - cents = som.bmu_ind_to_xy(np.arange(0, msz[0]*msz[1])) + cents = som.bmu_ind_to_xy(np.arange(0, msz[0] * msz[1])) if anotate: # TODO: Fix position of the labels self._set_labels(cents, ax, clusters, onlyzeros, labelsize, hex=False) @@ -52,6 +52,6 @@ def show(self, som, data=None, anotate=True, onlyzeros=False, labelsize=7, cmap= plt.imshow(clusters.reshape(msz[0], msz[1])[::], alpha=.5) elif som.codebook.lattice == "hexa": - ax, cents = plot_hex_map(np.flip(clusters.reshape(msz[0], msz[1])[::], axis=1), fig=self._fig, colormap=cmap, colorbar=False) + ax, cents = plot_hex_map(np.flip(clusters.reshape(msz[0], msz[1])[::], axis=1), fig=self._fig, colormap=cmap, colorbar=False) if anotate: - self._set_labels(cents, ax, clusters, onlyzeros, labelsize, hex=True) \ No newline at end of file + self._set_labels(cents, ax, clusters, onlyzeros, labelsize, hex=True) diff --git a/sompy/visualization/mapview.py b/sompy/visualization/mapview.py index 1dd5485..d077536 100644 --- a/sompy/visualization/mapview.py +++ b/sompy/visualization/mapview.py @@ -26,7 +26,7 @@ def _calculate_figure_params(self, som, which_dim, col_sz): ratio_hitmap = msz_row / float(msz_col) ratio_fig = row_sz / float(col_sz) indtoshow = np.arange(0, dim).T - sH, sV = 16, 16*ratio_fig*ratio_hitmap + sH, sV = 16, 16 * ratio_fig * ratio_hitmap elif type(which_dim) == int: dim = 1 @@ -44,7 +44,7 @@ def _calculate_figure_params(self, som, which_dim, col_sz): ratio_hitmap = msz_row / float(msz_col) ratio_fig = row_sz / float(col_sz) indtoshow = np.asarray(which_dim).T - sH, sV = 16, 16*ratio_fig*ratio_hitmap + sH, sV = 16, 16 * ratio_fig * ratio_hitmap no_row_in_plot = dim / col_sz + 1 # 6 is arbitrarily selected if no_row_in_plot <= 1: @@ -81,11 +81,11 @@ def show(self, som, what='codebook', which_dim='all', cmap=None, elif type(which_dim) == list: names = som._component_names[0][which_dim] - if som.codebook.lattice=="rect": + if som.codebook.lattice == "rect": while axis_num < len(indtoshow): axis_num += 1 ax = plt.subplot(no_row_in_plot, no_col_in_plot, axis_num) - ind = int(indtoshow[axis_num-1]) + ind = int(indtoshow[axis_num - 1]) min_color_scale = np.mean(codebook[:, ind].flatten()) - 1 * np.std(codebook[:, ind].flatten()) max_color_scale = np.mean(codebook[:, ind].flatten()) + 1 * np.std(codebook[:, ind].flatten()) @@ -103,12 +103,11 @@ def show(self, som, what='codebook', which_dim='all', cmap=None, ax.set_yticklabels([]) ax.set_xticklabels([]) plt.colorbar(pl) - elif som.codebook.lattice=="hexa": + elif som.codebook.lattice == "hexa": plot_hex_map(codebook.reshape(som.codebook.mapsize + [som.codebook.matrix.shape[-1]]), titles=names, shape=[no_row_in_plot, no_col_in_plot], colormap=cmap, fig=self._fig) - class View2DPacked(MapView): def _set_axis(self, ax, msz0, msz1): @@ -130,8 +129,8 @@ def show(self, som, what='codebook', which_dim='all', cmap=None, if what == 'codebook': h = .1 w = .1 - self.width = no_col_in_plot*2.5*(1+w) - self.height = no_row_in_plot*2.5*(1+h) + self.width = no_col_in_plot * 2.5 * (1 + w) + self.height = no_row_in_plot * 2.5 * (1 + h) self.prepare() while axis_num < len(indtoshow): @@ -139,7 +138,7 @@ def show(self, som, what='codebook', which_dim='all', cmap=None, ax = self._fig.add_subplot(no_row_in_plot, no_col_in_plot, axis_num) ax.axis('off') - ind = int(indtoshow[axis_num-1]) + ind = int(indtoshow[axis_num - 1]) mp = codebook[:, ind].reshape(msz0, msz1) plt.imshow(mp[::-1], norm=None, cmap=cmap) self._set_axis(ax, msz0, msz1) @@ -156,8 +155,8 @@ def show(self, som, what='codebook', which_dim='all', cmap=None, h = .2 w = .001 - self.width = msz0/2 - self.height = msz1/2 + self.width = msz0 / 2 + self.height = msz1 / 2 self.prepare() ax = self._fig.add_subplot(1, 1, 1) @@ -169,8 +168,8 @@ def show(self, som, what='codebook', which_dim='all', cmap=None, plt.subplots_adjust(hspace=h, wspace=w) plt.show() - - + + class View1D(MapView): def show(self, som, what='codebook', which_dim='all', cmap=None, @@ -184,7 +183,7 @@ def show(self, som, what='codebook', which_dim='all', cmap=None, while axis_num < len(indtoshow): axis_num += 1 plt.subplot(no_row_in_plot, no_col_in_plot, axis_num) - ind = int(indtoshow[axis_num-1]) + ind = int(indtoshow[axis_num - 1]) mp = codebook[:, ind] plt.plot(mp, '-k', linewidth=0.8) diff --git a/sompy/visualization/plot_tools.py b/sompy/visualization/plot_tools.py index b610a7d..e54a676 100644 --- a/sompy/visualization/plot_tools.py +++ b/sompy/visualization/plot_tools.py @@ -79,4 +79,4 @@ def create_grid_coordinates(x, y): #cbar.ax.tick_params(labelsize=3 * comp_width) - return ax, list(reversed(n_centers)) \ No newline at end of file + return ax, list(reversed(n_centers)) diff --git a/sompy/visualization/umatrix.py b/sompy/visualization/umatrix.py index 6665401..76198c9 100644 --- a/sompy/visualization/umatrix.py +++ b/sompy/visualization/umatrix.py @@ -43,7 +43,7 @@ def show(self, som, distance2=1, row_normalized=False, show_data=True, mx = np.max(umat.flatten()) std = np.std(umat.flatten()) md = np.median(umat.flatten()) - mx = md + 0*std + mx = md + 0 * std contour(umat, np.linspace(mn, mx, 15), linewidths=0.7, cmap=plt.cm.get_cmap('Blues')) @@ -60,8 +60,8 @@ def show(self, som, distance2=1, row_normalized=False, show_data=True, horizontalalignment='center', verticalalignment='center') - ratio = float(msz[0])/(msz[0]+msz[1]) - self._fig.set_size_inches((1-ratio)*15, ratio*15) + ratio = float(msz[0]) / (msz[0] + msz[1]) + self._fig.set_size_inches((1 - ratio) * 15, ratio * 15) plt.tight_layout() plt.subplots_adjust(hspace=.00, wspace=.000) sel_points = list() From 5318d92f2d3dd1003772ba394a268dd671b457d2 Mon Sep 17 00:00:00 2001 From: Erin Wild Date: Mon, 18 Feb 2019 20:04:10 -0500 Subject: [PATCH 4/8] Sort and remove unused mports --- sompy/__init__.py | 5 +---- sompy/codebook.py | 4 ++-- sompy/neighborhood.py | 3 ++- sompy/normalization.py | 5 +++-- sompy/sompy.py | 16 +++++++--------- sompy/visualization/bmuhits.py | 4 +--- sompy/visualization/dotmap.py | 5 +++-- sompy/visualization/histogram.py | 8 ++++---- sompy/visualization/hitmap.py | 6 ++---- sompy/visualization/mapview.py | 9 +++------ sompy/visualization/umatrix.py | 16 +++++++++------- 11 files changed, 37 insertions(+), 44 deletions(-) diff --git a/sompy/__init__.py b/sompy/__init__.py index 3b1e899..6abcd49 100644 --- a/sompy/__init__.py +++ b/sompy/__init__.py @@ -1,7 +1,6 @@ - from logging.config import dictConfig -import matplotlib +import matplotlib #matplotlib.use('Agg') # Use whatever backend is available dictConfig({ @@ -25,7 +24,5 @@ } }) - - from .sompy import SOMFactory from .visualization import * diff --git a/sompy/codebook.py b/sompy/codebook.py index f343da0..7c8b340 100644 --- a/sompy/codebook.py +++ b/sompy/codebook.py @@ -1,8 +1,7 @@ import numpy as np import scipy as sp - from sklearn.decomposition import PCA -#from sklearn.decomposition import RandomizedPCA# (randomizedpca is deprecated) + from .decorators import timeit @@ -13,6 +12,7 @@ class InvalidNodeIndexError(Exception): class InvalidMapsizeError(Exception): pass + def generate_hex_lattice(n_rows, n_columns): x_coord = [] y_coord = [] diff --git a/sompy/neighborhood.py b/sompy/neighborhood.py index 08d35e2..fc35407 100644 --- a/sompy/neighborhood.py +++ b/sompy/neighborhood.py @@ -1,7 +1,8 @@ -import numpy as np import inspect import sys +import numpy as np + small = .000000000001 diff --git a/sompy/normalization.py b/sompy/normalization.py index 1a6f3d4..78f5ab9 100644 --- a/sompy/normalization.py +++ b/sompy/normalization.py @@ -1,6 +1,7 @@ -import numpy as np -import sys import inspect +import sys + +import numpy as np class NormalizerFactory(object): diff --git a/sompy/sompy.py b/sompy/sompy.py index 54b3547..6f4bf1e 100644 --- a/sompy/sompy.py +++ b/sompy/sompy.py @@ -8,23 +8,21 @@ # Contributor: Sebastian Packmann (sebastian.packmann@gmail.com) -import tempfile -import os import itertools import logging +import os +import tempfile +from multiprocessing import cpu_count +from multiprocessing.dummy import Pool +from time import time import numpy as np - -from time import time -from multiprocessing.dummy import Pool -from multiprocessing import cpu_count from scipy.sparse import csr_matrix from sklearn import neighbors -from sklearn.externals.joblib import Parallel, delayed, load, dump -import sys +from sklearn.externals.joblib import dump, load -from .decorators import timeit from .codebook import Codebook +from .decorators import timeit from .neighborhood import NeighborhoodFactory from .normalization import NormalizerFactory diff --git a/sompy/visualization/bmuhits.py b/sompy/visualization/bmuhits.py index bd265d7..3dd3946 100644 --- a/sompy/visualization/bmuhits.py +++ b/sompy/visualization/bmuhits.py @@ -5,9 +5,7 @@ from matplotlib import pyplot as plt from .mapview import MapView - -from sompy.visualization.plot_tools import plot_hex_map - +from .plot_tools import plot_hex_map class BmuHitsView(MapView): diff --git a/sompy/visualization/dotmap.py b/sompy/visualization/dotmap.py index 8f38441..8a0697a 100644 --- a/sompy/visualization/dotmap.py +++ b/sompy/visualization/dotmap.py @@ -1,6 +1,7 @@ -from .view import MatplotView -from matplotlib import pyplot as plt import numpy as np +from matplotlib import pyplot as plt + +from .view import MatplotView class DotMapView(MatplotView): diff --git a/sompy/visualization/histogram.py b/sompy/visualization/histogram.py index bde155f..d89e8f0 100644 --- a/sompy/visualization/histogram.py +++ b/sompy/visualization/histogram.py @@ -1,8 +1,8 @@ -from .view import MatplotView -from matplotlib import pyplot as plt -from matplotlib import cm -from matplotlib.colors import LogNorm import numpy as np +from matplotlib import cm, pyplot as plt +from matplotlib.colors import LogNorm + +from .view import MatplotView class Hist2d(MatplotView): diff --git a/sompy/visualization/hitmap.py b/sompy/visualization/hitmap.py index 8cad393..52f6675 100644 --- a/sompy/visualization/hitmap.py +++ b/sompy/visualization/hitmap.py @@ -1,10 +1,8 @@ -from .view import MatplotView -from sompy.visualization.plot_tools import plot_hex_map -from matplotlib import pyplot as plt import numpy as np +from matplotlib import pyplot as plt from .mapview import MapView - +from .plot_tools import plot_hex_map class HitMapView(MapView): diff --git a/sompy/visualization/mapview.py b/sompy/visualization/mapview.py index d077536..4290d5b 100644 --- a/sompy/visualization/mapview.py +++ b/sompy/visualization/mapview.py @@ -1,10 +1,9 @@ -from matplotlib import colors import matplotlib +import numpy as np +from matplotlib import pyplot as plt -from sompy.visualization.plot_tools import plot_hex_map +from .plot_tools import plot_hex_map from .view import MatplotView -from matplotlib import pyplot as plt -import numpy as np class MapView(MatplotView): @@ -188,5 +187,3 @@ def show(self, som, what='codebook', which_dim='all', cmap=None, plt.plot(mp, '-k', linewidth=0.8) #plt.show() - - diff --git a/sompy/visualization/umatrix.py b/sompy/visualization/umatrix.py index 76198c9..6a97631 100644 --- a/sompy/visualization/umatrix.py +++ b/sompy/visualization/umatrix.py @@ -1,9 +1,11 @@ -from .view import MatplotView -from matplotlib import pyplot as plt -from pylab import imshow, contour from math import sqrt + import numpy as np +import pylab import scipy +from matplotlib import pyplot as plt + +from .view import MatplotView class UMatrixView(MatplotView): @@ -36,7 +38,7 @@ def show(self, som, distance2=1, row_normalized=False, show_data=True, coord = som.bmu_ind_to_xy(proj) self._fig, ax = plt.subplots(1, 1) - imshow(umat, cmap=plt.cm.get_cmap('RdYlBu_r'), alpha=1) + pylab.imshow(umat, cmap=plt.cm.get_cmap('RdYlBu_r'), alpha=1) if contooor: mn = np.min(umat.flatten()) @@ -44,8 +46,8 @@ def show(self, som, distance2=1, row_normalized=False, show_data=True, std = np.std(umat.flatten()) md = np.median(umat.flatten()) mx = md + 0 * std - contour(umat, np.linspace(mn, mx, 15), linewidths=0.7, - cmap=plt.cm.get_cmap('Blues')) + pylab.contour(umat, np.linspace(mn, mx, 15), linewidths=0.7, + cmap=plt.cm.get_cmap('Blues')) if show_data: plt.scatter(coord[:, 1], coord[:, 0], s=2, alpha=1., c='Gray', @@ -76,7 +78,7 @@ def show(self, som, distance2=1, row_normalized=False, show_data=True, # 'Laplacian of Gaussian' blobs = blob_log(image, max_sigma=5, num_sigma=4, threshold=.152) blobs[:, 2] = blobs[:, 2] * sqrt(2) - imshow(umat, cmap=plt.cm.get_cmap('RdYlBu_r'), alpha=1) + pylab.imshow(umat, cmap=plt.cm.get_cmap('RdYlBu_r'), alpha=1) sel_points = list() for blob in blobs: From 69b878e6ee99be2e1f6f48173ec90cd7b58816ee Mon Sep 17 00:00:00 2001 From: Erin Wild Date: Mon, 18 Feb 2019 19:46:07 -0500 Subject: [PATCH 5/8] Fix typos --- README.md | 8 ++++---- sompy/visualization/umatrix.py | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 1d9fe56..e45df7f 100644 --- a/README.md +++ b/README.md @@ -30,9 +30,9 @@ python setup.py install Many thanks to @sebastiandev, the library is now standardized in a pythonic tradition. Below you can see some basic examples, showing how to use the library. -But I recommend you to go through the codes. There are several functionalities already implemented, but not documented. I would be very happy to add your new examples here. +But I recommend you to go through the codes. There are several functionalities already implemented, but not documented. I would be very happy to add your new examples here. -[Basice Example](https://gist.github.com/sevamoo/035c56e7428318dd3065013625f12a11) +[Basic Example](https://gist.github.com/sevamoo/035c56e7428318dd3065013625f12a11) ### Citation @@ -42,7 +42,7 @@ There is no published paper about this library. However if possible, please cite Main Contributers: Vahid Moosavi @sevamoo Sebastian Packmann @sebastiandev -Iván Vallés @ivallesp +Iván Vallés @ivallesp ``` @@ -51,5 +51,5 @@ For more information, you can contact me via sevamoo@gmail.com or svm@arch.ethz. -Thanks a lot. +Thanks a lot. Best Vahid Moosavi diff --git a/sompy/visualization/umatrix.py b/sompy/visualization/umatrix.py index 6a97631..b0b981c 100644 --- a/sompy/visualization/umatrix.py +++ b/sompy/visualization/umatrix.py @@ -30,7 +30,7 @@ def build_u_matrix(self, som, distance=1, row_normalized=False): return Umatrix.reshape(som.codebook.mapsize) def show(self, som, distance2=1, row_normalized=False, show_data=True, - contooor=True, blob=False, labels=False): + contour=True, blob=False, labels=False): umat = self.build_u_matrix(som, distance=distance2, row_normalized=row_normalized) msz = som.codebook.mapsize @@ -40,7 +40,7 @@ def show(self, som, distance2=1, row_normalized=False, show_data=True, self._fig, ax = plt.subplots(1, 1) pylab.imshow(umat, cmap=plt.cm.get_cmap('RdYlBu_r'), alpha=1) - if contooor: + if contour: mn = np.min(umat.flatten()) mx = np.max(umat.flatten()) std = np.std(umat.flatten()) From fe3ff7c15d3cf1d5a5256c0e2549b17c09b66c3d Mon Sep 17 00:00:00 2001 From: Erin Wild Date: Mon, 18 Feb 2019 22:02:19 -0500 Subject: [PATCH 6/8] Use list literal instead of constructor --- sompy/visualization/umatrix.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sompy/visualization/umatrix.py b/sompy/visualization/umatrix.py index b0b981c..a9a25b0 100644 --- a/sompy/visualization/umatrix.py +++ b/sompy/visualization/umatrix.py @@ -66,7 +66,7 @@ def show(self, som, distance2=1, row_normalized=False, show_data=True, self._fig.set_size_inches((1 - ratio) * 15, ratio * 15) plt.tight_layout() plt.subplots_adjust(hspace=.00, wspace=.000) - sel_points = list() + sel_points = [] if blob: from skimage.color import rgb2gray @@ -79,7 +79,7 @@ def show(self, som, distance2=1, row_normalized=False, show_data=True, blobs = blob_log(image, max_sigma=5, num_sigma=4, threshold=.152) blobs[:, 2] = blobs[:, 2] * sqrt(2) pylab.imshow(umat, cmap=plt.cm.get_cmap('RdYlBu_r'), alpha=1) - sel_points = list() + sel_points = [] for blob in blobs: row, col, r = blob From ca600a64be37d1d16f875fbc94adb6a47341f4e3 Mon Sep 17 00:00:00 2001 From: Erin Wild Date: Mon, 18 Feb 2019 22:41:00 -0500 Subject: [PATCH 7/8] Update gitignore --- .gitignore | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/.gitignore b/.gitignore index 0447b8b..48bbe13 100644 --- a/.gitignore +++ b/.gitignore @@ -104,6 +104,9 @@ venv.bak/ # Rope project settings .ropeproject +# VS Code project settings +.vscode/ + # mkdocs documentation /site @@ -114,3 +117,8 @@ dmypy.json # Pyre type checker .pyre/ + +# macOS +.DS_Store + +.directory From c0c6b28d0cc800a175052340f938d658837bd850 Mon Sep 17 00:00:00 2001 From: Erin Wild Date: Mon, 18 Feb 2019 22:55:23 -0500 Subject: [PATCH 8/8] Fix line length too long --- sompy/sompy.py | 45 ++++++++++++++++++------------- sompy/visualization/bmuhits.py | 6 ++--- sompy/visualization/hitmap.py | 3 ++- sompy/visualization/mapview.py | 29 +++++++++++--------- sompy/visualization/plot_tools.py | 7 ++--- 5 files changed, 53 insertions(+), 37 deletions(-) diff --git a/sompy/sompy.py b/sompy/sompy.py index 6f4bf1e..a350011 100644 --- a/sompy/sompy.py +++ b/sompy/sompy.py @@ -137,7 +137,8 @@ def __init__(self, mapsize = self.calculate_map_size(lattice) if not mapsize else mapsize self.codebook = Codebook(mapsize, lattice) self.training = training - self._component_names = self.build_component_names() if component_names is None else [component_names] + self._component_names = (self.build_component_names() + if component_names is None else [component_names]) self._distance_matrix = self.calculate_map_dist() @property @@ -212,7 +213,8 @@ def train(self, :param n_job: number of jobs to use to parallelize the traning :param shared_memory: flag to active shared memory :param verbose: verbosity, could be 'debug', 'info' or None - :param train_len_factor: Factor that multiply default training lenghts (similar to "training" parameter in the matlab version). (lbugnon) + :param train_len_factor: Factor that multiply default training lenghts + (similar to "training" parameter in the matlab version). (lbugnon) """ logging.root.setLevel( getattr(logging, verbose.upper()) if verbose else logging.ERROR) @@ -241,9 +243,11 @@ def train(self, self.codebook.pca_linear_initialization(self._data) self.rough_train(njob=n_job, shared_memory=shared_memory, trainlen=train_rough_len, - radiusin=train_rough_radiusin, radiusfin=train_rough_radiusfin, trainlen_factor=train_len_factor, maxtrainlen=maxtrainlen) + radiusin=train_rough_radiusin, radiusfin=train_rough_radiusfin, + trainlen_factor=train_len_factor, maxtrainlen=maxtrainlen) self.finetune_train(njob=n_job, shared_memory=shared_memory, trainlen=train_finetune_len, - radiusin=train_finetune_radiusin, radiusfin=train_finetune_radiusfin, trainlen_factor=train_len_factor, maxtrainlen=maxtrainlen) + radiusin=train_finetune_radiusin, radiusfin=train_finetune_radiusfin, + trainlen_factor=train_len_factor, maxtrainlen=maxtrainlen) logging.debug( " --------------------------------------------------------------") logging.info(" Final quantization error: %f" % np.mean(self._bmu[1])) @@ -260,7 +264,8 @@ def _calculate_ms_and_mpd(self): return ms, mpd - def rough_train(self, njob=1, shared_memory=False, trainlen=None, radiusin=None, radiusfin=None, trainlen_factor=1, maxtrainlen=np.Inf): + def rough_train(self, njob=1, shared_memory=False, trainlen=None, radiusin=None, + radiusfin=None, trainlen_factor=1, maxtrainlen=np.Inf): logging.info(" Rough training...") ms, mpd = self._calculate_ms_and_mpd() @@ -280,7 +285,8 @@ def rough_train(self, njob=1, shared_memory=False, trainlen=None, radiusin=None, self._batchtrain(trainlen, radiusin, radiusfin, njob, shared_memory) - def finetune_train(self, njob=1, shared_memory=False, trainlen=None, radiusin=None, radiusfin=None, trainlen_factor=1, maxtrainlen=np.Inf): + def finetune_train(self, njob=1, shared_memory=False, trainlen=None, radiusin=None, + radiusfin=None, trainlen_factor=1, maxtrainlen=np.Inf): logging.info(" Finetune training...") ms, mpd = self._calculate_ms_and_mpd() @@ -288,7 +294,7 @@ def finetune_train(self, njob=1, shared_memory=False, trainlen=None, radiusin=No #lbugnon: add maxtrainlen if self.initialization == 'random': trainlen = min(int(np.ceil(50 * mpd)), maxtrainlen) if not trainlen else trainlen - radiusin = max(1, ms / 12.) if not radiusin else radiusin # from radius fin in rough training + radiusin = max(1, ms / 12.) if not radiusin else radiusin radiusfin = max(1, radiusin / 25.) if not radiusfin else radiusfin elif self.initialization == 'pca': @@ -336,12 +342,11 @@ def _batchtrain(self, trainlen, radiusin, radiusfin, njob=1, self.codebook.matrix = self.update_codebook_voronoi(data, bmu, neighborhood) - #lbugnon: ojo! aca el bmy[1] a veces da negativo, y despues de eso se rompe...hay algo raro ahi + #lbugnon: ojo! aca el bmy[1] a veces da negativo, y despues de eso se rompe... + # hay algo raro ahi qerror = (i + 1, round(time() - t1, 3), - np.mean(np.sqrt(bmu[1] + fixed_euclidean_x2))) #lbugnon: ojo aca me tiró un warning, revisar (commit sinc: 965666d3d4d93bcf48e8cef6ea2c41a018c1cb83 ) - #lbugnon - #ipdb.set_trace() - # + np.mean(np.sqrt(bmu[1] + fixed_euclidean_x2))) + logging.info( " epoch: %d ---> elapsed time: %f, quantization error: %f\n" % qerror) @@ -618,12 +623,15 @@ def calculate_topographic_error(self): bmus2 = self.find_bmu(self.data_raw, njb=1, nth=2) topographic_error = None if self.codebook.lattice == "rect": - bmus_gap = np.abs((self.bmu_ind_to_xy(np.array(bmus1[0]))[:, 0:2] - self.bmu_ind_to_xy(np.array(bmus2[0]))[:, 0:2]).sum(axis=1)) + bmus_gap = np.abs((self.bmu_ind_to_xy(np.array(bmus1[0]))[:, 0:2] + - self.bmu_ind_to_xy(np.array(bmus2[0]))[:, 0:2]).sum(axis=1)) topographic_error = np.mean(bmus_gap != 1) elif self.codebook.lattice == "hexa": - dist_matrix_1 = self.codebook.lattice_distances[bmus1[0].astype(int)].reshape(len(bmus1[0]), -1) - topographic_error = (np.array( - [distances[bmu2] for bmu2, distances in zip(bmus2[0].astype(int), dist_matrix_1)]) > 2).mean() + dist_matrix_1 = (self.codebook.lattice_distances[bmus1[0].astype(int)] + .reshape(len(bmus1[0]), -1)) + topographic_error = (np.array([distances[bmu2] + for bmu2, distances + in zip(bmus2[0].astype(int), dist_matrix_1)]) > 2).mean() return(topographic_error) def calculate_quantization_error(self): @@ -632,8 +640,9 @@ def calculate_quantization_error(self): return quantization_error def calculate_map_size(self, lattice): - """ - Calculates the optimal map size given a dataset using eigenvalues and eigenvectors. Matlab ported + """Calculates the optimal map size given a dataset using eigenvalues and eigenvectors. + Matlab ported. + :lattice: 'rect' or 'hex' :return: map sizes """ diff --git a/sompy/visualization/bmuhits.py b/sompy/visualization/bmuhits.py index 3dd3946..cc7b870 100644 --- a/sompy/visualization/bmuhits.py +++ b/sompy/visualization/bmuhits.py @@ -26,9 +26,9 @@ def show(self, som, anotate=True, onlyzeros=False, labelsize=7, cmap="jet", loga self.height /= (self.width / org_w) if self.width > self.height else (self.height / org_h) counts = Counter(som._bmu[0]) - counts = [counts.get(x, 0) for x in range(som.codebook.mapsize[0] * som.codebook.mapsize[1])] - mp = np.array(counts).reshape(som.codebook.mapsize[0], - som.codebook.mapsize[1]) + counts = [counts.get(x, 0) + for x in range(som.codebook.mapsize[0] * som.codebook.mapsize[1])] + mp = np.array(counts).reshape(som.codebook.mapsize[0], som.codebook.mapsize[1]) if not logaritmic: norm = matplotlib.colors.Normalize( diff --git a/sompy/visualization/hitmap.py b/sompy/visualization/hitmap.py index 52f6675..9d86284 100644 --- a/sompy/visualization/hitmap.py +++ b/sompy/visualization/hitmap.py @@ -50,6 +50,7 @@ def show(self, som, data=None, anotate=True, onlyzeros=False, labelsize=7, cmap= plt.imshow(clusters.reshape(msz[0], msz[1])[::], alpha=.5) elif som.codebook.lattice == "hexa": - ax, cents = plot_hex_map(np.flip(clusters.reshape(msz[0], msz[1])[::], axis=1), fig=self._fig, colormap=cmap, colorbar=False) + ax, cents = plot_hex_map(np.flip(clusters.reshape(msz[0], msz[1])[::], axis=1), + fig=self._fig, colormap=cmap, colorbar=False) if anotate: self._set_labels(cents, ax, clusters, onlyzeros, labelsize, hex=True) diff --git a/sompy/visualization/mapview.py b/sompy/visualization/mapview.py index 4290d5b..bca09d8 100644 --- a/sompy/visualization/mapview.py +++ b/sompy/visualization/mapview.py @@ -86,16 +86,20 @@ def show(self, som, what='codebook', which_dim='all', cmap=None, ax = plt.subplot(no_row_in_plot, no_col_in_plot, axis_num) ind = int(indtoshow[axis_num - 1]) - min_color_scale = np.mean(codebook[:, ind].flatten()) - 1 * np.std(codebook[:, ind].flatten()) - max_color_scale = np.mean(codebook[:, ind].flatten()) + 1 * np.std(codebook[:, ind].flatten()) - min_color_scale = min_color_scale if min_color_scale >= min(codebook[:, ind].flatten()) else \ - min(codebook[:, ind].flatten()) - max_color_scale = max_color_scale if max_color_scale <= max(codebook[:, ind].flatten()) else \ - max(codebook[:, ind].flatten()) - norm = matplotlib.colors.Normalize(vmin=min_color_scale, vmax=max_color_scale, clip=True) - - mp = codebook[:, ind].reshape(som.codebook.mapsize[0], - som.codebook.mapsize[1]) + min_color_scale = (np.mean(codebook[:, ind].flatten()) + - 1 * np.std(codebook[:, ind].flatten())) + max_color_scale = (np.mean(codebook[:, ind].flatten()) + + 1 * np.std(codebook[:, ind].flatten())) + min_color_scale = (min_color_scale + if min_color_scale >= min(codebook[:, ind].flatten()) + else min(codebook[:, ind].flatten())) + max_color_scale = (max_color_scale + if max_color_scale <= max(codebook[:, ind].flatten()) + else max(codebook[:, ind].flatten())) + norm = matplotlib.colors.Normalize(vmin=min_color_scale, vmax=max_color_scale, + clip=True) + + mp = codebook[:, ind].reshape(som.codebook.mapsize[0], som.codebook.mapsize[1]) pl = plt.pcolor(mp[::-1], norm=norm) plt.axis([0, som.codebook.mapsize[1], 0, som.codebook.mapsize[0]]) plt.title(names[axis_num - 1]) @@ -103,8 +107,9 @@ def show(self, som, what='codebook', which_dim='all', cmap=None, ax.set_xticklabels([]) plt.colorbar(pl) elif som.codebook.lattice == "hexa": - plot_hex_map(codebook.reshape(som.codebook.mapsize + [som.codebook.matrix.shape[-1]]), titles=names, - shape=[no_row_in_plot, no_col_in_plot], colormap=cmap, fig=self._fig) + plot_hex_map(codebook.reshape(som.codebook.mapsize + [som.codebook.matrix.shape[-1]]), + titles=names, shape=[no_row_in_plot, no_col_in_plot], colormap=cmap, + fig=self._fig) class View2DPacked(MapView): diff --git a/sompy/visualization/plot_tools.py b/sompy/visualization/plot_tools.py index e54a676..8a96c38 100644 --- a/sompy/visualization/plot_tools.py +++ b/sompy/visualization/plot_tools.py @@ -6,8 +6,8 @@ from mpl_toolkits.axes_grid1 import make_axes_locatable -def plot_hex_map(d_matrix, titles=[], colormap=cm.gray, shape=[1, 1], comp_width=5, hex_shrink=1.0, fig=None, - colorbar=True): +def plot_hex_map(d_matrix, titles=[], colormap=cm.gray, shape=[1, 1], comp_width=5, + hex_shrink=1.0, fig=None, colorbar=True): """ Plot hexagon map where each neuron is represented by a hexagon. The hexagon color is given by the distance between the neurons (D-Matrix) @@ -25,7 +25,8 @@ def plot_hex_map(d_matrix, titles=[], colormap=cm.gray, shape=[1, 1], comp_width def create_grid_coordinates(x, y): coordinates = [x for row in -1 * np.array(list(range(x))) for x in - list(zip(np.arange(((row) % 2) * 0.5, y + ((row) % 2) * 0.5), [0.8660254 * (row)] * y))] + list(zip(np.arange(((row) % 2) * 0.5, y + ((row) % 2) * 0.5), + [0.8660254 * (row)] * y))] return (np.array(list(reversed(coordinates))), x, y) if d_matrix.ndim < 3: