本文整理汇总了Python中minisom.MiniSom.random_weights_init方法的典型用法代码示例。如果您正苦于以下问题:Python MiniSom.random_weights_init方法的具体用法?Python MiniSom.random_weights_init怎么用?Python MiniSom.random_weights_init使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类minisom.MiniSom
的用法示例。
在下文中一共展示了MiniSom.random_weights_init方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: SOM
# 需要导入模块: from minisom import MiniSom [as 别名]
# 或者: from minisom.MiniSom import random_weights_init [as 别名]
def SOM(data,leninput,lentarget):
som = MiniSom(5,5,leninput,sigma=1.0,learning_rate=0.5)
som.random_weights_init(data)
print("Training...")
som.train_batch(data,10000) # training with 10000 iterations
print("\n...ready!")
numpy.save('weight_som.txt',som.weights)
bone()
pcolor(som.distance_map().T) # distance map as background
colorbar()
t = zeros(lentarget,dtype=int)
# use different colors and markers for each label
markers = ['o','s','D']
colors = ['r','g','b']
outfile = open('cluster-result.csv','w')
for cnt,xx in enumerate(data):
w = som.winner(xx) # getting the winner
#print cnt
#print xx
#print w
for z in xx:
outfile.write("%s " % str(z))
outfile.write("%s-%s \n" % (str(w[0]),str(w[1])))
#outfile.write("%s %s\n" % str(xx),str(w))
# palce a marker on the winning position for the sample xx
#plot(w[0]+.5,w[1]+.5,markers[t[cnt]],markerfacecolor='None',
# markeredgecolor=colors[t[cnt]],markersize=12,markeredgewidth=2)
outfile.close()
示例2: SOM
# 需要导入模块: from minisom import MiniSom [as 别名]
# 或者: from minisom.MiniSom import random_weights_init [as 别名]
def SOM(data,leninput,lentarget,alpha_som,omega_som):
som = MiniSom(16,16,leninput,sigma=omega_som,learning_rate=alpha_som)
som.random_weights_init(data)
print("Training...")
som.train_batch(data,20000) # training with 10000 iterations
print("\n...ready!")
numpy.save('weight_som',som.weights)
bone()
pcolor(som.distance_map().T) # distance map as background
colorbar()
t = zeros(lentarget,dtype=int)
# use different colors and markers for each label
markers = ['o','s','D']
colors = ['r','g','b']
outfile = open('cluster-result.csv','w')
for cnt,xx in enumerate(data):
w = som.winner(xx) # getting the winner
for z in xx:
outfile.write("%s " % str(z))
outfile.write("%s-%s \n" % (str(w[0]),str(w[1])))
outfile.close()
示例3: testSOMs
# 需要导入模块: from minisom import MiniSom [as 别名]
# 或者: from minisom.MiniSom import random_weights_init [as 别名]
def testSOMs():
from sklearn import datasets
from minisom import MiniSom
d = datasets.load_iris()
data = np.apply_along_axis(lambda x: x/np.linalg.norm(x), 1, d['data']) # data normalization
som = MiniSom(7, 7, 4, sigma=1.0, learning_rate=0.5)
som.random_weights_init(data)
print("Training...")
som.train_random(data, 1000) # random training
print("\n...ready!")
### Plotting the response for each pattern in the iris dataset ###
from pylab import plot,axis,show,pcolor,colorbar,bone
bone()
pcolor(som.distance_map().T) # plotting the distance map as background
colorbar()
t = d['target']
# use different colors and markers for each label
markers = ['o','s','D']
colors = ['r','g','b']
for cnt,xx in enumerate(data):
w = som.winner(xx) # getting the winner
# palce a marker on the winning position for the sample xx
plot(w[0]+.5,w[1]+.5,markers[t[cnt]],markerfacecolor='None',
markeredgecolor=colors[t[cnt]],markersize=12,markeredgewidth=2)
axis([0,som.weights.shape[0],0,som.weights.shape[1]])
show() # show the figure
示例4: SOM
# 需要导入模块: from minisom import MiniSom [as 别名]
# 或者: from minisom.MiniSom import random_weights_init [as 别名]
def SOM(data,leninput,lentarget):
som = MiniSom(16,16,leninput,sigma=1.0,learning_rate=0.5)
som.random_weights_init(data)
print("Training...")
som.train_random(data,10000) # training with 10000 iterations
print("\n...ready!")
numpy.save('weight_som',som.weights)
示例5: _minisomrandom
# 需要导入模块: from minisom import MiniSom [as 别名]
# 或者: from minisom.MiniSom import random_weights_init [as 别名]
def _minisomrandom(self):
"""Clusters sentence vectors using minisomrandom algorithm
Returns
-------
numpy ndarray
codebook (weights) of the trained SOM
"""
H = int(self.opts['size'])
W = int(self.opts['size'])
N = self.X.shape[1]
som = MiniSom(H, W, N, sigma=1.0, random_seed=1)
if self.opts['initialization']:
som.random_weights_init(self.X)
som.train_random(self.X, self.opts['niterations'])
return som.get_weights()
示例6: len
# 需要导入模块: from minisom import MiniSom [as 别名]
# 或者: from minisom.MiniSom import random_weights_init [as 别名]
ATTENTION: pylab is required for the visualization.
"""
# reading the iris dataset in the csv format
# (downloaded from http://aima.cs.berkeley.edu/data/iris.csv)
#rn = len(open('iris4.csv').readlines())
data = genfromtxt('data5.csv', delimiter=',',dtype = float)
data = numpy.nan_to_num(data)
print (data)
data = apply_along_axis(lambda x: x/linalg.norm(x),1,data) # data normalization
### Initialization and training ###
som = MiniSom(40,40,136,sigma=1.0,learning_rate=0.5)
som.random_weights_init(data)
print("Training...")
som.train_random(data,10000) # random training
print("\n...ready!")
### Plotting the response for each pattern in the iris dataset ###
from pylab import plot,axis,show,pcolor,colorbar,bone
bone()
pcolor(som.distance_map().T) # plotting the distance map as background
colorbar()
target = genfromtxt('class5.csv',delimiter=',',usecols=(0),dtype=int) # loadingthe labels
t = zeros(len(target),dtype=int)
print (target)
示例7: imread
# 需要导入模块: from minisom import MiniSom [as 别名]
# 或者: from minisom.MiniSom import random_weights_init [as 别名]
from pylab 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.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')
imshow(flipud(img))
subplot(222)
示例8: MinMaxScaler
# 需要导入模块: from minisom import MiniSom [as 别名]
# 或者: from minisom.MiniSom import random_weights_init [as 别名]
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('Credit_Card_Applications.csv')
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 = 15, sigma = 1.0, learning_rate = 0.5)
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]],
markeredgecolor = colors[y[i]],
示例9: _parse_file_argument
# 需要导入模块: from minisom import MiniSom [as 别名]
# 或者: from minisom.MiniSom import random_weights_init [as 别名]
plt.pcolor(som.distance_map().T)
return fig, ax
RS = 20160101
if __name__ == '__main__':
args = _parse_file_argument()
data = pd.read_csv(args.csv)
data.fillna(0, inplace=True)
label_column = args.label_prefix
label_prefix = data[label_column].values
data.drop(label_column, axis=1, inplace=True)
label_column = args.label_sufix
label_sufix = data[label_column].values
data.drop(label_column, axis=1, inplace=True)
id_column = 'id'
data.drop(id_column, axis=1, inplace=True)
som = MiniSom(8,8,len(data.columns),sigma=1.0,learning_rate=0.5,random_seed=RS)
som.random_weights_init(data.as_matrix())
som.train_random(data.as_matrix(),100)
_plot_distribution(som)
plt.savefig('som.png', dpi=120)
示例10: If_running
# 需要导入模块: from minisom import MiniSom [as 别名]
# 或者: from minisom.MiniSom import random_weights_init [as 别名]
#.........这里部分代码省略.........
background = self.axes.pcolor(self.som.distance_map().T) # plotting the distance map as background
#f.colorbar(a)
t = np.zeros(len(self.target),dtype=int)
t[self.target == 'A'] = 0
t[self.target == 'B'] = 1
t[self.target == 'C'] = 2
t[self.target == 'D'] = 3
# use different colors and markers for each label
markers = ['o','s','D', '+']
colors = ['r','g','b', 'y']
for cnt,xx in enumerate(data):
w = self.som.winner(xx) # getting the winner
# place a marker on the winning position for the sample xx
tmp = self.axes.plot(w[0]+.5,w[1]+.5,markers[t[cnt]],markerfacecolor='None',
markeredgecolor=colors[t[cnt]],markersize=12,markeredgewidth=2)
self.axes.axis([0,self.som.weights.shape[0],0,self.som.weights.shape[1]])
#show() # show the figure
#print "drawing"
#self.figure.canvas.draw()
def init_som(self, widget=None, data=None):
##print self.data
### Initialization and training ###
cols = self.columns[self.combobox.get_active()]
data = self.data[:, 0:len(cols)]
#print len(cols)
self.som = MiniSom(self.width_spin_button.get_value_as_int(), self.height_spin_button.get_value_as_int(), len(cols),sigma=1.2,learning_rate=0.5)
# self.som.weights_init_gliozzi(data)
self.som.random_weights_init(data)
def train_som(self):
cols = self.columns[self.combobox.get_active()]
data = self.data[:, 0:len(cols)]
print("Training...")
#self.som.train_gliozzi(data) # Gliozzi et al training
self.som.train_random(data,20)
print("\n...ready!")
def make_treeview(self, data, liststore):
#i = 0
cols = self.columns[self.combobox.get_active()]
#print type(cols)
#print len(cols)
for d in data:
#i += 1
tmp = d.tolist()
#print 'tmp', tmp
#while len(tmp) < cols:
#tmp.append(False)
#print 'tmp', tmp
#cols = cols - 1
Qe = MiniSom.quantization_error_subset(self.som,d,len(cols))
#print tmp
tmp.append(Qe)
tmp.append(4 * Qe ** 0.5)
liststore.append(tmp)
示例11: self_organizing_map
# 需要导入模块: from minisom import MiniSom [as 别名]
# 或者: from minisom.MiniSom import random_weights_init [as 别名]
def self_organizing_map(image=None, images=None, weights=None, weights_max_value=1, n_colors=64,
dim=None, num_training=1000, std_multiple=0, threshold=False, show_plot=False, show_color_space_assignment=False):
"""
Given an image or stack of images (list of np arrays), cluster with an SOM and return a list of the color centers
num_training is the number of pixels used to train
weights is a list of rgb values to initialize the algorithm with
weights_max_value is a number representing the maximum possible value so that weights can be normalized to a 0-1 scale
n_colors is the number of clusters
dim is the dimensions of the nodes in the SOM. Total number of nodes should be the same as the number specified
threshold is a boolean whether to consider the black pixels or not
std_multiple is the standard deviation multiple used in thresholding
show_plot is a boolean whether to show the quantized image or not
show_color_space_assignment is a boolean whether to show the way the color space is clustered or not
"""
neuron_pixels, non_neuron_pixels, pixels, image = sample_data(image, images, std_multiple)
if dim is None and weights is not None:
# normalize weights
weights = (np.array(weights) / weights_max_value).tolist()
# figure out a way to spread out the nodes of the som and find the int factor closest to the square root
factor = get_factor_closest_to_sqrt(len(weights))
# it's prime if the factor is 1
if factor == 1:
# add a random weight to make the number of nodes even
weights = np.vstack((weights, np.random.random(3)))
# should be fine now
factor = get_factor_closest_to_sqrt(len(weights))
dim = (factor, len(weights) / factor)
weights = np.reshape(weights, (dim[0], dim[1], 3))
else:
# there are no weights to initialize
if n_colors == 2 or n_colors == 3:
dim = (1, n_colors)
else:
factor = get_factor_closest_to_sqrt(n_colors)
# it's prime if the factor is 1
if factor == 1:
# increase the number of colors by one
n_colors += 1
# should be fine now
factor = get_factor_closest_to_sqrt(n_colors)
dim = (factor, n_colors / factor)
# determine the dimensions
som = MiniSom(dim[0], dim[1], 3, weights=weights, sigma=0.1, learning_rate=0.2)
if weights is None:
if threshold:
som.random_weights_init(neuron_pixels)
else:
som.random_weights_init(pixels)
if threshold:
# get mostly bright pixels with a bit of background
som.train_random(neuron_pixels, num_training)
else:
som.train_random(pixels, num_training)
if show_plot:
qnt = som.quantization(pixels) # quantize each pixels of the image
clustered = np.zeros(image.shape)
for i, q in enumerate(qnt):
clustered[np.unravel_index(i, dims=(image.shape[0], image.shape[1]))] = q
fig = plt.figure()
ax = fig.add_subplot(1, 2, 1)
plt.imshow(image)
ax.set_title('Original')
ax = fig.add_subplot(1, 2, 2)
plt.imshow(clustered)
ax.set_title('After SOM Clustering')
plt.show()
if show_color_space_assignment:
for intensity in [.1, .2, .4, .6, .8]:
visualize_color_space(som=som, intensity=intensity)
return np.reshape(som.weights, (som.weights.shape[0] * som.weights.shape[1], 3))
示例12: load_mPD
# 需要导入模块: from minisom import MiniSom [as 别名]
# 或者: from minisom.MiniSom import random_weights_init [as 别名]
try:
mPD
PD
ProtNames
except:
mPD = load_mPD()
PD,ProtNames = load_PD()
R = Cluster.somcluster(mPD,transpose=1,nxgrid=40,nygrid=40,niter=1)
from minisom import MiniSom
### Initialization and training ###
som = MiniSom(40,40,15,sigma=1.0,learning_rate=0.5)
#som.random_weights_init(mPD)
som.weights
som.random_weights_init(transpose(mPD))
print("Training...")
som.train_random(transpose(mPD),100) # training with 100 iterations
print("\n...ready!")
timg = np.zeros(shape=(40,40))
for c in R[0]:
timg[c[0],c[1]]=timg[c[0],c[1]]+1
plt.figure()
plt.subplot(2,2,1)
plt.imshow(R[1][:,:,1])
plt.subplot(2,2,2)
plt.imshow(mean(R[1],axis=2))
示例13: test_random_weights_init
# 需要导入模块: from minisom import MiniSom [as 别名]
# 或者: from minisom.MiniSom import random_weights_init [as 别名]
def test_random_weights_init(self):
som = MiniSom(2, 2, 2, sigma=0.1, random_seed=1)
som.random_weights_init(np.array([[1.0, .0]]))
for w in som.weights:
assert_array_equal(w[0], np.array([1.0, .0]))
示例14: SomPage
# 需要导入模块: from minisom import MiniSom [as 别名]
# 或者: from minisom.MiniSom import random_weights_init [as 别名]
class SomPage(tk.Frame):
## UI 생성
def __init__(self, parent, controller):
## tk.Frame 초기화
tk.Frame.__init__(self, parent)
style.use("ggplot")
self.figure = pl.figure(1)
self.a = self.figure.add_subplot(111)
self.canvas = FigureCanvasTkAgg(self.figure, self)
self.canvas.get_tk_widget().grid(sticky="news")
self.canvas._tkcanvas.grid(sticky="news")
## Initialization
self.som = MiniSom(10,10,136,sigma=1.0,learning_rate=0.5)
####---------------------------------------------
## THREAD 생성
def callback_threaded(self, status):
self.queue = Queue() # 크기가 1인 버퍼
self.thread = Thread(target=self.training, args=(status,))
self.thread.daemon = True
self.thread.start()
self.queue.put(object()) ## 첫번째
print("Start")
self.queue.join() ## 네번째
self.thread.join()
self.plotting(status)
## size, learning_rate, training_count, target_count)
def training(self, status):
self.figure.clear()
self.queue.get() ## 두번째
## reading the dataset in the csv format
self.data = genfromtxt('iris6.csv', delimiter=',',dtype = float)
self.data = numpy.nan_to_num(self.data)
## data normalization
self.data = apply_along_axis(lambda x: x/linalg.norm(x),1,self.data)
self.som.random_weights_init(self.data)
print("Training...")
self.som.train_random(self.data,100) # random training
bone()
## plotting the distance map as background
pcolor(self.som.distance_map().T)
colorbar()
## loadingthe labels
target = genfromtxt('iris4_2.csv', delimiter=',', usecols=(0), dtype=int)
self.t = zeros(len(target),dtype=int)
print("...ready to plot...")
for i in range(len(target)):
self.t[target == i] = i
self.som.win_map(self.data)
self.queue.task_done() ## 세번째
def plotting(self, status):
self.figure = pl.figure(1)
self.a = self.figure.add_subplot(111)
print("Plotting...")
## use differet colors and markers for each label
## markers = []
colors = ['r','g','b','y','w','orange','black','pink','brown','purple']
## making bm file
with open('bm.txt', 'w') as f:
f.write(str(len(self.data))+'\n')
for cnt,xx in enumerate(self.data):
win = self.som.winner(xx) # getting the winner
# palce a marker on the winning position for the sample xx
self.a.plot(win[0]+.5,win[1]+.5,'.', markerfacecolor='None', markeredgecolor=colors[self.t[cnt]], markersize=1, markeredgewidth=1)
f.write(str(win[0])+'\t'+str(win[1])+'\t'+str(self.t[cnt])+'\n')
## making umx file
with open('umx.txt', 'w') as f:
for cnt,xx in enumerate(self.data):
win = self.som.winner(xx) # getting the winner
# palce a marker on the winning position for the sample xx
self.a.plot(win[0]+.5,win[1]+.5,'.',markerfacecolor='None',
markeredgecolor=colors[self.t[cnt]], markersize=1, markeredgewidth=1)
#.........这里部分代码省略.........