本文整理汇总了Python中minisom.MiniSom.winner方法的典型用法代码示例。如果您正苦于以下问题:Python MiniSom.winner方法的具体用法?Python MiniSom.winner怎么用?Python MiniSom.winner使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类minisom.MiniSom
的用法示例。
在下文中一共展示了MiniSom.winner方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: SOM
# 需要导入模块: from minisom import MiniSom [as 别名]
# 或者: from minisom.MiniSom import winner [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()
示例2: SOM
# 需要导入模块: from minisom import MiniSom [as 别名]
# 或者: from minisom.MiniSom import winner [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()
示例3: testSOMs
# 需要导入模块: from minisom import MiniSom [as 别名]
# 或者: from minisom.MiniSom import winner [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: init
# 需要导入模块: from minisom import MiniSom [as 别名]
# 或者: from minisom.MiniSom import winner [as 别名]
class Som:
def init(self):
self.core = MiniSom(50,50,6,sigma=.8,learning_rate=.5) # needs to match generating minisom command (specifically the load_map)
self.core.load_map()
self.callme = rospy.Service("mapping", Compute, self.callback)
print "SOM setup complete"
def callback(self, data):
vector = np.array([data.fx, data.fy, data.fz, data.tx, data.ty, data.tz]) # format as needed
print vector
w = self.core.winner(vector)
return w[0],w[1]
示例5: test_recommendation
# 需要导入模块: from minisom import MiniSom [as 别名]
# 或者: from minisom.MiniSom import winner [as 别名]
def test_recommendation():
uji_profil = db.uji_profil
current_seq = []
for t in uji_profil.find({}):
current_seq.append("Topik " + str(t['topic']))
'''
APPLY SOM
'''
allTopic = articles.distinct("topic")
lentopic = len(allTopic)
uniqueTopic = []
for t in allTopic:
uniqueTopic.append("Topik " + str(t).strip())
lebarSOM = lentopic*lentopic + lentopic*2 + 1
somInput = []
somInput.append(getPresedenceMatrix(convertSession(current_seq,uniqueTopic),uniqueTopic,1))
som = MiniSom(16,16,lentopic,sigma=1.0,learning_rate=0.5)
som.weights = numpy.load('weight_som.npy')
cluster_winner = ""
for cnt,xx in enumerate(somInput):
w = som.winner(xx) # getting the winner
cluster_winner = (str(w[0])+"-"+str(w[1]))
'''
SEARCH FOR THE PATTERN IN PARTICULAR CLUSTER
'''
print cluster_winner
print current_seq
prefix_result = db.prefix_result
prefix_cluster = prefix_result.find({"cluster":cluster_winner,"data_uji":no_uji}).sort("min_sup",pymongo.DESCENDING)
topik_rekomendasi = getTopikRekomendasi(current_seq,prefix_cluster)
if topik_rekomendasi == "":
prefix_cluster = prefix_result.find({"data_uji":no_uji}).sort("min_sup",pymongo.DESCENDING)
topik_rekomendasi = getTopikRekomendasi(current_seq,prefix_cluster)
html = "--tidak ada topik rekomendasi--"
if(topik_rekomendasi!=""):
the_topik = topik_rekomendasi.replace("Topik","").strip()
html = getTestArticle(the_topik,"Rekomendasi 1","accordion_recommendation",'col_rek1',"")
html += getTestArticle(the_topik,"Rekomendasi 2","accordion_recommendation",'col_rek2',"")
html += getTestArticle(the_topik,"Rekomendasi 3","accordion_recommendation",'col_rek3',"")
return html
示例6: test_som
# 需要导入模块: from minisom import MiniSom [as 别名]
# 或者: from minisom.MiniSom import winner [as 别名]
def test_som():
print "Clustering.."
session_log_db = db.session_log
allTopic = articles.distinct("topic")
lentopic = len(allTopic)
uniqueTopic = []
for t in allTopic:
uniqueTopic.append("Topik " + str(t).strip())
lebarSOM = lentopic*lentopic + lentopic*2 + 1
panjangSOM = session_log_db.find({"data_uji":no_uji}).count()
#somInput = zeros((panjangSOM,lebarSOM),dtype=int16)
somInput = []
oriSess = []
for s in session_log_db.find({"data_uji":no_uji}):
somInput.append(getPresedenceMatrix(convertSession(s["session"],uniqueTopic),uniqueTopic,1))
oriSess.append(s["session"])
som = MiniSom(16,16,lentopic,sigma=1.0,learning_rate=0.5)
som.weights = numpy.load('weight_som.npy')
#print som.weights
outfile = open('cluster-result.csv','w')
seq_number = 0
cluster_mongo = db.cluster_result
cluster_mongo.remove({"data_uji":no_uji})
for cnt,xx in enumerate(somInput):
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 " % str(("|".join(oriSess[seq_number]))))
outfile.write("%s-%s \n" % (str(w[0]),str(w[1])))
cluster_mongo.insert({"topik":"|".join(oriSess[seq_number]),"cluster":(str(w[0])+"-"+str(w[1])),"data_uji":no_uji})
seq_number = seq_number + 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()
#TopikCluster()
html = '<div role="alert" class="alert alert-success alert-dismissible fade in">'
html = html + ' <button aria-label="Close" data-dismiss="alert" class="close" type="button"><span aria-hidden="true">Close</span></button>'
html = html + 'Berhasil Melakukan Clustering</div>'
return html
示例7: test_som
# 需要导入模块: from minisom import MiniSom [as 别名]
# 或者: from minisom.MiniSom import winner [as 别名]
def test_som(alpha_som,omega_som):
print "Clustering pada Data Uji " + str(no_uji)
session_log_db = db.session_log
allTopic = articles.distinct("topic")
lentopic = len(allTopic)
uniqueTopic = []
for t in allTopic:
uniqueTopic.append("Topik " + str(t).strip())
lebarSOM = lentopic*lentopic + lentopic*2 + 1
panjangSOM = session_log_db.find({"data_uji":no_uji}).count()
#somInput = zeros((panjangSOM,lebarSOM),dtype=int16)
somInput = []
oriSess = []
for s in session_log_db.find({"data_uji":no_uji}):
somInput.append(getPresedenceMatrix(convertSession(s["session"],uniqueTopic),uniqueTopic,1))
oriSess.append(s["session"])
som = MiniSom(16,16,lentopic,sigma=omega_som,learning_rate=alpha_som)
som.weights = numpy.load('weight_som.npy')
#print som.weights
outfile = open('cluster-result.csv','w')
seq_number = 0
cluster_mongo = db.cluster_result
cluster_mongo.remove({"data_uji":no_uji})
for cnt,xx in enumerate(somInput):
w = som.winner(xx) # getting the winner
outfile.write("%s " % str(("|".join(oriSess[seq_number]))))
outfile.write("%s-%s \n" % (str(w[0]),str(w[1])))
cluster_mongo.insert({"topik":"|".join(oriSess[seq_number]),"cluster":(str(w[0])+"-"+str(w[1])),"data_uji":no_uji})
seq_number = seq_number + 1
outfile.close()
#TopikCluster()
return "Berhasil Melakukan Clustering"
示例8: SOMDiscretizer
# 需要导入模块: from minisom import MiniSom [as 别名]
# 或者: from minisom.MiniSom import winner [as 别名]
class SOMDiscretizer(Discretizer):
def __init__(self, width=4, height=4, sigma=0.3, learning_rate=0.5):
self.width = width
self.height = height
self.sigma = sigma
self.learning_rate = learning_rate
def train(self, data):
self.som = MiniSom(self.width, self.height, len(data[0]), sigma=self.sigma, learning_rate=self.learning_rate)
self.som.train_random(data, 1000000)
def discretize(self, data_point):
x, y = self.som.winner(data_point)
return self.som.weights[x,y]
def visualize(self, filename, subset=None):
box_side = 150
border = 30
text_height = 10
text_offset_x = 60
text_offset_y = 30
w = (self.width * box_side) + ((self.width-1) * border)
h = (self.height * box_side) + ((self.height-1) * border)
img = Image.new('RGB', (w, h))
draw = ImageDraw.Draw(img)
for i in range(self.width):
for j in range(self.height):
offset = np.array([
i*(box_side + border), j*(box_side + border),
(i+1)*(box_side + border), (j+1)*(box_side + border)
])
def coords(arr, offset):
a = arr + offset
return [ (a[0], a[1]), (a[2], a[3]) ]
def dimension_subset(vector, subset):
if subset is not None:
return vector[subset[0]:subset[1]+1]
return vector
# Draw the prototype vector box
box_position = coords(np.array([
0, 0,
box_side, box_side
]), offset)
prototype_vector = dimension_subset(self.som.weights[i, j], subset)
fill = int(self.norm_data_vector(prototype_vector) * 200) + 55
draw.rectangle(box_position, fill=(0, fill, 0))
# Write the prototype vector as text
text_position = box_position[0]
line_no = 0
for value in prototype_vector:
rounded_value = round(value * 100) / 100
base_x, base_y = box_position[0]
text_position = (base_x + text_offset_x, base_y + text_offset_y + text_height*line_no)
draw.text(text_position, str(rounded_value))
line_no += 1
right_fill, bottom_fill, diagonal_fill = 0, 0, 0
# Draw right border of U-matrix
if i != self.width - 1:
right_border_position = coords(np.array([
box_side+1, 0,
box_side+1+border, box_side
]), offset)
prototype_vector_a = dimension_subset(self.som.weights[i, j], subset)
prototype_vector_b = dimension_subset(self.som.weights[i+1, j], subset)
right_fill = 255 - int(self.data_vector_difference(prototype_vector_a, prototype_vector_b) * 255)
draw.rectangle(right_border_position, fill=(right_fill, right_fill, right_fill))
# Draw bottom border of U-matrix
if j != self.height - 1:
bottom_border_position = coords(np.array([
0, box_side+1,
box_side, box_side+1+border
]), offset)
prototype_vector_a = dimension_subset(self.som.weights[i, j], subset)
prototype_vector_b = dimension_subset(self.som.weights[i, j+1], subset)
bottom_fill = 255 - int(self.data_vector_difference(prototype_vector_a, prototype_vector_b) * 255)
draw.rectangle(bottom_border_position, fill=(bottom_fill, bottom_fill, bottom_fill))
# Draw diagonal border of U-matrix
if i != self.width - 1 and j != self.height - 1:
diagonal_border_position = coords(np.array([
box_side+1, box_side+1,
box_side+1+border, box_side+1+border
]), offset)
#.........这里部分代码省略.........
示例9: open
# 需要导入模块: from minisom import MiniSom [as 别名]
# 或者: from minisom.MiniSom import winner [as 别名]
t[target == 3] = 3
t[target == 4] = 4
t[target == 5] = 5
t[target == 6] = 6
t[target == 7] = 7
t[target == 8] = 8
t[target == 9] = 9
# use differet colors and markers for each label
#markers = []
colors = ['r','g','b','y','w','orange','black','pink','brown','purple']
som.win_map(data)
with open('bm.txt', 'w') as f: #making bm file
f.write(str(len(data))+'\n')
for cnt,xx in enumerate(data):
win = som.winner(xx) # getting the winner
# palce a marker on the winning position for the sample xx
plot(win[0]+.5,win[1]+.5,'.',markerfacecolor='None',markeredgecolor=colors[t[cnt]],markersize=1,markeredgewidth=1)
f.write(str(win[0])+'\t'+str(win[1])+'\t'+str(t[cnt])+'\n')
with open('umx.txt', 'w') as f: #making umx file
for cnt,xx in enumerate(data):
win = som.winner(xx) # getting the winner
# palce a marker on the winning position for the sample xx
plot(win[0]+.5,win[1]+.5,'.',markerfacecolor='None',
markeredgecolor=colors[t[cnt]],markersize=1,markeredgewidth=1)
um=som.distance_map()
for i in range(40):
for j in range(40):
f.write(str(um[i,j])+'\t')
示例10: MiniSom
# 需要导入模块: from minisom import MiniSom [as 别名]
# 或者: from minisom.MiniSom import winner [as 别名]
num = digits.target # num[i] is the digit represented by data[i]
# training the som
from minisom import MiniSom
som = MiniSom(20,20,64,sigma=.8,learning_rate=0.5)
print("Training...")
som.train_random(data,1500) # random training
print("\n...ready!")
# plotting the results
from pylab import text,show,cm,axis,figure,subplot,imshow,zeros
wmap = {}
figure(1)
im = 0
for x,t in zip(data,num): # scatterplot
w = som.winner(x)
wmap[w] = im
text(w[0]+.5, w[1]+.5, str(t), color=cm.Dark2(t / 4.), fontdict={'weight': 'bold', 'size': 11})
im = im + 1
axis([0,som.weights.shape[0],0,som.weights.shape[1]])
figure(2,facecolor='white')
cnt = 0
for j in reversed(range(20)): # images mosaic
for i in range(20):
subplot(20,20,cnt+1,frameon=False, xticks=[], yticks=[])
if (i,j) in wmap:
imshow(digits.images[wmap[(i,j)]], cmap='Greys', interpolation='nearest')
else:
imshow(zeros((8,8)), cmap='Greys')
cnt = cnt + 1
示例11: MiniSom
# 需要导入模块: from minisom import MiniSom [as 别名]
# 或者: from minisom.MiniSom import winner [as 别名]
drmap = MiniSom(50,50,6,sigma=.8,learning_rate=.5) # Replace 64 with the dimensions of desired target (6)
if fresh_data == 1:
print "Training..."
drmap.train_random(data,1500) # random training
print "\n...ready!"
elif fresh_data == 0:
print "Loading Data"
drmap.load_map()
# plotting the results
from pylab import text,show,cm,axis,figure,subplot,imshow,zeros
figure(1)
im = 0
result = np.array([])
for x,t in zip(data,num): # scatterplot
w = drmap.winner(x)
result.resize((im+1,3))
result[im][0]=w[0]
result[im][1]=w[1]
result[im][2]=num[im]
text(w[0]+.5, w[1]+.5, str(t), color=cm.Dark2(t / 8.), fontdict={'weight': 'bold', 'size': 11})
im = im + 1
axis([0,drmap.weights.shape[0],0,drmap.weights.shape[1]])
# Save SOM file
drmap.save_map()
else:
if mode == 2:
print "Using LLE"
construct = manifold.LocallyLinearEmbedding(n_neighbors, n_components=2, method='standard')
示例12: SomPage
# 需要导入模块: from minisom import MiniSom [as 别名]
# 或者: from minisom.MiniSom import winner [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)
#.........这里部分代码省略.........
示例13: HandProcessor
# 需要导入模块: from minisom import MiniSom [as 别名]
# 或者: from minisom.MiniSom import winner [as 别名]
#.........这里部分代码省略.........
pyplot.plot(t, sums)
print "Discrete Wavelet transform"
a, b = self.discrete_wavelet_transform(sums)
self.vectors.append([a, b, filename])
self.next_plot()
pyplot.plot(range(len(a)), a)
pyplot.plot(range(len(b)), b)
# now do wavelet transform on the resulting 1d function
# cwtmatr = self.wavelet_transform(sums)
# print "Wavelet result matrix shape: %s" % str(cwtmatr.shape)
self.show()
def train_som(self):
training_data = [v[0] for v in self.vectors]
from minisom import MiniSom
size = len(training_data[0])
self.som = MiniSom(10, 10, size, sigma=0.3, learning_rate=0.5)
print "Training SOM..."
self.som.train_random(training_data, 100)
print "...ready!"
def use_som(self):
pyplot.figure()
training_data = [v[0] for v in self.vectors]
points = []
for v in training_data:
point = self.som.winner(v)
points.append(point)
print point
xs = [x for x,y in points]
ys = [y for x,y in points]
pyplot.subplot(1,1,1)
pyplot.plot(xs, ys, '*')
pyplot.savefig("output/0-som.png")
def find_contours(self, binary):
copy = numpy.copy(binary)
contours, _ = cv2.findContours(copy, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
return contours
def wavelet_transform(self, data):
# TODO: perform discrete wavelet transform instead
sig = numpy.copy(data)
widths = numpy.arange(1, len(data))
cwtmatr = signal.cwt(sig, signal.ricker, widths)
self.next_plot()
pyplot.imshow(cwtmatr, extent=[-1, 1, 1, 31], cmap='PRGn', aspect='auto',
vmax=abs(cwtmatr).max(), vmin=-abs(cwtmatr).max())
return cwtmatr
def normalize_vectors(self):