Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_random_weights_init(self):
som = MiniSom(2, 2, 2, random_seed=1)
som.random_weights_init(array([[1.0, .0]]))
for w in som._weights:
assert_array_equal(w[0], array([1.0, .0]))
from minisom import MiniSom
from numpy import genfromtxt,array,linalg,zeros,mean,std,apply_along_axis
"""
This script shows how to use MiniSom on the Iris dataset.
In partucular it shows how to train MiniSom and how to visualize the result.
ATTENTION: matplotlib is required for the visualization.
"""
# reading the iris dataset in the csv format
# (downloaded from http://aima.cs.berkeley.edu/data/iris.csv)
data = genfromtxt('iris.csv', delimiter=',',usecols=(0,1,2,3))
data = apply_along_axis(lambda x: x/linalg.norm(x),1,data) # data normalization
### Initialization and training ###
som = MiniSom(7,7,4,sigma=1.0,learning_rate=0.5)
som.random_weights_init(data)
print("Training...")
som.train_random(data,100) # random training
print("\n...ready!")
# Plotting the response for each pattern in the iris dataset
from matplotlib.pyplot import plot,axis,show,pcolor,colorbar,bone
bone()
pcolor(som.distance_map().T) # plotting the distance map as background
colorbar()
target = genfromtxt('iris.csv',delimiter=',',usecols=(4),dtype=str) # loading the labels
t = zeros(len(target),dtype=int)
t[target == 'setosa'] = 0
t[target == 'versicolor'] = 1
t[target == 'virginica'] = 2
script_dir = os.path.dirname(__file__)
training_set_path = os.path.join(script_dir, 'Credit_Card_Applications.csv')
dataset = pd.read_csv(training_set_path)
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, -1].values
# Feature Scaling
from sklearn.preprocessing import MinMaxScaler
sc = MinMaxScaler(feature_range=(0, 1))
X = sc.fit_transform(X)
# Training the SOM
from minisom import MiniSom
som = MiniSom(x=10, y=10, input_len=len(X.T))
som.random_weights_init(X)
som.train_random(data=X, num_iteration=100)
# Visualizing the results
from pylab import bone, pcolor, colorbar, plot, show
bone()
pcolor(som.distance_map().T)
colorbar()
markers = ['o', 's']
colors = ['r', 'g']
for i, x in enumerate(X):
w = som.winner(x)
plot(w[0] + 0.5,
w[1] + 0.5,
markers[y[i]],
from matplotlib.pyplot import imread,imshow,figure,show,subplot,title
from numpy import reshape,flipud,unravel_index,zeros
from minisom import MiniSom
# read the image
img = imread('tree.jpg')
# reshaping the pixels matrix
pixels = reshape(img,(img.shape[0]*img.shape[1],3))
# SOM initialization and training
print('training...')
som = MiniSom(3,3,3,sigma=0.1,learning_rate=0.2) # 3x3 = 9 final colors
som.random_weights_init(pixels)
starting_weights = som.get_weights().copy() # saving the starting weights
som.train_random(pixels,100)
print('quantization...')
qnt = som.quantization(pixels) # quantize each pixels of the image
print('building new image...')
clustered = zeros(img.shape)
for i,q in enumerate(qnt): # place the quantized values into a new image
clustered[unravel_index(i,dims=(img.shape[0],img.shape[1]))] = q
print('done.')
# show the result
figure(1)
subplot(221)
title('original')
def test_unavailable_neigh_function(self):
with self.assertRaises(ValueError):
MiniSom(5, 5, 1, neighborhood_function='boooom')
def test_train_batch(self):
som = MiniSom(5, 5, 2, sigma=1.0, learning_rate=0.5, random_seed=1)
data = array([[4, 2], [3, 1]])
q1 = som.quantization_error(data)
som.train(data, 10)
assert q1 > som.quantization_error(data)
data = array([[1, 5], [6, 7]])
q1 = som.quantization_error(data)
som.train_batch(data, 10, verbose=True)
assert q1 > som.quantization_error(data)
def test_random_seed(self):
som1 = MiniSom(5, 5, 2, sigma=1.0, learning_rate=0.5, random_seed=1)
som2 = MiniSom(5, 5, 2, sigma=1.0, learning_rate=0.5, random_seed=1)
# same initialization
assert_array_almost_equal(som1._weights, som2._weights)
data = random.rand(100, 2)
som1 = MiniSom(5, 5, 2, sigma=1.0, learning_rate=0.5, random_seed=1)
som1.train_random(data, 10)
som2 = MiniSom(5, 5, 2, sigma=1.0, learning_rate=0.5, random_seed=1)
som2.train_random(data, 10)
# same state after training
assert_array_almost_equal(som1._weights, som2._weights)
def test_train_random(self):
som = MiniSom(5, 5, 2, sigma=1.0, learning_rate=0.5, random_seed=1)
data = array([[4, 2], [3, 1]])
q1 = som.quantization_error(data)
som.train(data, 10, random_order=True)
assert q1 > som.quantization_error(data)
data = array([[1, 5], [6, 7]])
q1 = som.quantization_error(data)
som.train_random(data, 10, verbose=True)
assert q1 > som.quantization_error(data)
import random
import numpy as np
from util import visualize_rgb
from minisom import MiniSom
rgb = np.load("../data/generated_rgb.np")
w, h = 6, 6
som = MiniSom(w, h, 3, sigma=0.3, learning_rate=0.5)
visualize_rgb(w, h, som.weights, filename="minisom_init")
print "Training..."
som.train_random(rgb, 100)
print "...ready!"
visualize_rgb(w, h, som.weights, filename="minisom_result")
def setUp(self):
self.som = MiniSom(5, 5, 1)
for i in range(5):
for j in range(5):
# checking weights normalization
assert_almost_equal(1.0, linalg.norm(self.som._weights[i, j]))
self.som._weights = zeros((5, 5, 1)) # fake weights
self.som._weights[2, 3] = 5.0
self.som._weights[1, 1] = 2.0