Python基於K-均值、RLS演算法實現RBF神經網路(神經網路與機器學習 第五章 計算機實驗)
1、生成資料集
class moon_data_class(object):
def __init__(self,N,d,r,w):
self.N=N
self.w=w
self.d=d
self.r=r
def sgn(self,x):
if(x>0):
return 1;
else:
return -1;
def sig(self,x):
return 1.0 /(1+np.exp(x))
def dbmoon(self):
N1 = 10*self.N
N = self.N
r = self.r
w2 = self.w/2
d = self.d
done = True
data = np.empty(0)
while done:
#generate Rectangular data
tmp_x = 2*(r+w2)*(np.random.random( [N1, 1])-0.5)
tmp_y = (r+w2)*np.random.random([N1, 1])
tmp = np.concatenate((tmp_x, tmp_y), axis=1)
tmp_ds = np.sqrt(tmp_x*tmp_x + tmp_y*tmp_y)
#generate double moon data ---upper
idx = np.logical_and(tmp_ds > (r-w2), tmp_ds < (r+w2))
idx = (idx.nonzero())[0]
if data.shape[0] == 0:
data = tmp.take(idx, axis=0)
else:
data = np.concatenate((data, tmp.take(idx, axis=0)), axis=0)
if data.shape[0] >= N:
done = False
#print (data)
db_moon = data[0:N, :]
#print (db_moon)
#generate double moon data ----down
data_t = np.empty([N, 2])
data_t[:, 0] = data[0:N, 0] + r
data_t[:, 1] = -data[0:N, 1] - d
db_moon = np.concatenate((db_moon, data_t), axis=0)
return db_moon
2、定義RBF神經網路
2.1 RLS演算法
class RBF_NET:
def __init__(self,K,input_n,output_n):
self.K = K
self.input_n = input_n
self.output_n = output_n
self.x =[]
self.y =[]
self.k_point = []
self.weight = [0] * K
self.Alpha = np.array([0] * K)
self.weight = [0] * K
self.weight = np.mat(self.weight).T
self.center =[0] * K
self.Sigma = []
def k_means(self,input_cells):
k_count = self.K
count = len(input_cells) #點的個數
x = input_cells[0:count, 0]
y = input_cells[0:count, 1]
#隨機選擇K個點
k = rd.sample(range(count), k_count)
self.k_point = [[x[i], [y[i]]] for i in k] #保證有序
self.k_point.sort()
while True:
km = [[] for i in range(k_count)] #儲存每個簇的索引
#遍歷所有點
for i in range(count):
cp = [x[i], y[i]] #當前點
#計算cp點到所有質心的距離
_sse = [distance(self.k_point[j], cp) for j in range(k_count)]
#cp點到那個質心最近
min_index = _sse.index(min(_sse))
#把cp點併入第i簇
km[min_index].append(i)
#更換質心
k_new = []
for i in range(k_count):
_x = sum([x[j] for j in km[i]]) / len(km[i])
_y = sum([y[j] for j in km[i]]) / len(km[i])
k_new.append([_x, _y])
k_new.sort() #排序
if (k_new != self.k_point):#一直迴圈直到聚類中心沒有變化
self.k_point = k_new
else:
pl.figure()
pl.title("N=%d,k=%d iteration"%(count,k_count))
for j in range(k_count):
pl.plot([x[i] for i in km[j]], [y[i] for i in km[j]], color[j%4])
pl.plot(self.k_point[j][0], self.k_point[j][1], dcolor[j%4])
pl.show()
self.x =x
self.y =y
self.center = self.k_point
return self.k_point,km
def get_max_distance():
pass
def get_sigma_cov(self):
k_count = self.K
center_array = []
for j in range(k_count):
center_array.append([[self.x[i] for i in km[j]], [self.y[i] for i in km[j]]])
Sigma_Cov = []
distans_Max = []
Sigma_Array = []
Sigma = [0]*k_count
for j in range(k_count):
distans = []
for i in range(len(center_array[j][0])):
temp = self.Phi(np.array([center_array[j][0][i],center_array[j][1][i]]),np.array(self.center[j]))
distans.append(temp)
distans = np.array(distans)
temp = np.mean(distans)/np.sqrt(2*self.K)
Sigma[j]=temp
test = np.array(distans)
Sigma_Array.append(np.cov(test))
# Sigma_Cov.append(np.cov(Sigma))
self.Sigma =np.array(Sigma)
return Sigma
def train(self,input_cells,labels,batch_size):
Sigma_Array = self.get_sigma_cov()
P = np.eye(self.K)*0.01
# G = np.array([1] * k_count)
# self.Alpha = np.array([0] * self.K)
for batch in range(batch_size):
i=0
for input_data in input_cells:
Phi_Arr = []
for j in range(k_count):
temp = self.Phi(np.array([input_data[0],input_data[1]]),np.array(center[j]))
temp1 = self.gaussian(temp,self.Sigma[j])
Phi_Arr.append(temp1)
Phi_Arr = np.mat(Phi_Arr).T
temp_1 = np.dot(P,np.mat(Phi_Arr))
temp_2 = np.dot(temp_1,np.mat(Phi_Arr).T)
temp_3 = np.dot(temp_2,np.mat(P))
temp_4 = np.dot(Phi_Arr.T, P)
temp_5 = np.dot(temp_4,Phi_Arr)
P = P - temp_3/(1+temp_5)
G = np.dot(P,np.mat(Phi_Arr))
alpha = np.mat(labels[i]) - np.dot(self.weight.T,Phi_Arr)
self.weight = self.weight + G*alpha
i += 1
def predict(self,input_data):
Phi_Arr = []
#print("input_data:",input_data)
for j in range(k_count):
temp = self.Phi(input_data,np.array(self.k_point[j]))
temp1 = self.gaussian(temp,self.Sigma[j])
Phi_Arr.append(temp1)
Phi_Arr = np.mat(Phi_Arr).T
out_put = np.dot(self.weight.T,Phi_Arr)
t = np.tanh(4*out_put[0][0])
return t
def Phi(self, a, b):
return norm(a-b)
def gaussian (self, x, sigma):
return np.exp(-x**2 / (2 * sigma**2))
3、訓練網路,列印結果
if __name__ == '__main__':
#計算平面兩點的歐氏距離
step=0
color=['.r','.g','.b','.y']#顏色種類
dcolor=['*r','*g','*b','*y']#顏色種類
frames = []
N = 200
d = -6
r = 10
width = 6
data_source = moon_data_class(N, d, r, width)
data = data_source.dbmoon()
# x0 = [1 for x in range(1,401)]
input_cells = np.array([np.reshape(data[0:2*N, 0], len(data)), np.reshape(data[0:2*N, 1], len(data))]).transpose()
labels_pre = [[-1] for y in range(1, 201)]
labels_pos = [[1] for y in range(1, 201)]
labels=labels_pre+labels_pos
k_count = 20
#center,km = k_means(input_cells, k_count)
"""test = Phi(input_cells[1],np.array(center[0]))
print(test)
test = distance(input_cells[1],np.array(center[0]))
print(np.sqrt(test))"""
count = len(input_cells)
x = input_cells[0:count, 0]
y = input_cells[0:count, 1]
center_array = []
RBF_NET = RBF_NET(k_count,1,1)
center,km = RBF_NET.k_means(input_cells)
RBF_NET.get_sigma_cov()
RBF_NET.train(input_cells,labels,50)
test_x = []
test_y = []
test_p = []
y_p_old = 0
#for x in input_cells:
# t =RBF_NET.predict(x)
# print(t)
for x in np.arange(-12.,15.,0.1):
for y in np.arange(-10.,15.,0.1):
y_p =RBF_NET.predict(np.array([x, y]))
if(y_p_old > 0 and y_p[0] < 0):
test_x.append(x)
test_y.append(y)
test_p.append([y_p_old,y_p[0]])
y_p_old = y_p[0]
#畫決策邊界
plt.plot( test_x, test_y, 'g--')
plt.plot(data[0:N, 0], data[0:N, 1], 'r*', data[N:2*N, 0], data[N:2*N, 1], 'b*')
plt.show()
4、執行結果
完成程式碼
# coding:utf-8
import numpy as np
import pylab as pl
import random as rd
import math
import random
import matplotlib.pyplot as plt
import numpy as np
import mpl_toolkits.mplot3d
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from scipy import *
from scipy.linalg import norm, pinv
from matplotlib import pyplot as plt
random.seed(0)
class moon_data_class(object):
def __init__(self,N,d,r,w):
self.N=N
self.w=w
self.d=d
self.r=r
def sgn(self,x):
if(x>0):
return 1;
else:
return -1;
def sig(self,x):
return 1.0/(1+np.exp(x))
def dbmoon(self):
N1 = 10*self.N
N = self.N
r = self.r
w2 = self.w/2
d = self.d
done = True
data = np.empty(0)
while done:
#generate Rectangular data
tmp_x = 2*(r+w2)*(np.random.random([N1, 1])-0.5)
tmp_y = (r+w2)*np.random.random([N1, 1])
tmp = np.concatenate((tmp_x, tmp_y), axis=1)
tmp_ds = np.sqrt(tmp_x*tmp_x + tmp_y*tmp_y)
#generate double moon data ---upper
idx = np.logical_and(tmp_ds > (r
相關推薦
Python基於K-均值、RLS演算法實現RBF神經網路(神經網路與機器學習 第五章 計算機實驗)
1、生成資料集
class moon_data_class(object):
def __init__(self,N,d,r,w):
self.N=N
self.w=w
self.d=d
self.r=r
Python學習-第五章 條件、迴圈及其他語句
條件、迴圈及其他語句
序列解包(可迭代物件解包):將一個序列(或任何可迭代物件)解包,並將得到的值儲存到一系列變數中。
>>> values=1,2,3
>>> values
(1, 2, 3)
>>> x,y,z=values
Coursera NG 機器學習 第五週 正則化 bias Vs variance Python實現
ex5.py
import scipy.optimize as op
import numpy as np
from scipy.io import loadmat
from ex5modules import *
#Part 1: Loading and visuali
小白學習機器學習---第三章(2):對數機率迴歸python實現
上程式碼~~~~~~~~###梯度下降法實現多元線性迴歸
def loadDataSet():
###資料匯入函式###
dataMatrix=[] #資料矩陣,第一列是w=1.0,第2,3列是特徵
labelMatrix=[] #標籤矩陣
JavaScript中變量、作用域和內存問題(JavaScript高級程序設計第4章)
外部 對象的引用 pan object 揮手 fun 可用內存 限制 argument 一、變量
(1)ECMAScript變量肯能包含兩種不同的數據類型的值:基本類型值和引用類型值。基本類型值指的是簡單的數據段,引用類型值指那些可能由多個值構成的對象。
(2)基本數據類型
python學習第五章
如果 實例化 == 常見 繼承 print 一個 調用 多繼承 1.繼承
即是一個派生的類(derived class)繼承基類(base class)的字段和方法,繼承也允許把一個 派生類的對象作為 一個基類
對象對待。通俗來講就是方便,繼承前人的代碼,減少工作量,當然這
python爬蟲學習第五章正則
多行匹配 href out 地址 常見 apt 分別是 all arch
html,body,div,span,applet,object,iframe,h1,h2,h3,h4,h5,h6,p,blockquote,pre,a,abbr,acronym,address,b
演算法設計與分析基礎 第五章謎題
習題5.1
11.Tromino謎題 Tromino是一個由棋盤上的三個1×1方塊組成的L型骨牌。我們的問題是,如何用Tromino覆蓋一個缺少了一個方塊的2n×2n棋盤。除了這個缺失的方塊,Tromino應該覆蓋棋盤上的所有方塊,Tromino可以任意轉向但不能有重疊。
為此問題
【吳恩達】機器學習第14章k-Means以及ex7-k-means程式設計練習
1.K-means方法是什麼?
1.首先K-meas方法是一種無監督的聚類問題。
2.方法內容:首先需要確定聚類中心u和聚類數量K:我們可以隨機選擇中心u;當K<m(m是樣本數),我們可以隨機選擇K個樣本作為聚類中心,這個方法一般效果會好一些。聚類數量K我們可以通過
演算法第五章上機實驗報告
工作分配問題:
問題描述:已知n的值與每個工作分配給其中一人的費用,n件工作分配給n個人,一二維陣列記錄工作i分配給第j個人所需的費用為c[i][j] 。 設計一個演算法,對於給定的工作費用,為每一個人都分配1 件不同的工作,並使總費用達到最小(需要注意的是每個人只能被分配到一項工作)
演算法描述:
解
演算法設計與分析:第五章 回溯法 5.8流水作業車間排程
/*
流水作業車間排程:
n個作業要在兩臺機器M1和M2組成的流水線上完成加工。每個作業加工的順序都是現在M1上加工,然後在
M2上加工。M1和M2加工作業i所需的時間分別為ai和bi。流水作業排程問題要求確定這n個作業的最優
加工順序,使得從第一個作業在機器M1上開始加工
演算法實現:插入排序(C/C++、Python)
虛擬碼:
INSERTION-SORT
for j <- 2 to length[A]
key <- A[j]
Insert A[j]into the sorted sequence A[l...j-1].
i <- j - 1
wh
基於LVD、貝葉斯模型演算法實現的電商行業商品評論與情感分析案例
一、 專案需求
現在大家進行網購,在購物之前呢,肯定會看下相關商品的評論,看下好評和差評,然後再綜合衡量,最後才會決定是否購買相關的商品。對一個指定商品,生產商,賣家,買家認同該商品的哪些優點/不認同
演算法實現:選擇排序(C/C++、Python)
虛擬碼:
SELECTION-SORT{A)
n <- length[A]
for i<-1 to n-1 do
j <-FIND-MIN(A,i,n)
A[j]&l
演算法實現:合併排序(C/C++、Python)
合併排序的關鍵步驟在於合併步驟中的合併兩個已排序子序列。為做合併,引入一個輔助過程MERGE(A, p, q, r), 其中A是一個數組,p、q和r是下標,滿足p小於等於q小於r。該過程假設子陣列A[p...q] 和A[q+1...r]都已排好序,並將它們合併成一個已排好序的
k-means(k均值聚類)演算法介紹及實現(c++)
基本介紹:
k-means 演算法接受輸入量 k ;然後將n個數據物件劃分為 k個聚類以便使得所獲得的聚類滿足:同一聚類中的物件相似度較高;而不同聚類中的物件相似度較小。聚類相似度是利用各聚類中物件的均值所獲得一個“中心物件”(引力中心)來進行計算的。
工作過程:
k
資料結構-基於鄰接矩陣實現圖的遍歷視覺化及使用Floyd、Dijkstra演算法求解最短路徑(JavaScript實現)
使用 JavaScript 基於鄰接矩陣實現了圖的深度、廣度遍歷,以及 Floyd、Dijkstra 演算法求解最短路徑。另外使用 SVG 實現圖的遍歷視覺化。一、輸入首先,輸入資料主要有兩個,一個是存放節點名的陣列,另一個是存放邊物件的陣列。例如://存放圖結點的陣列
va
資料結構-基於鄰接表實現圖的遍歷視覺化及使用Floyd、Dijkstra演算法求解最短路徑(JavaScript實現)
使用 JavaScript 基於鄰接表實現了圖的深度、廣度遍歷,以及 Floyd、Dijkstra 演算法求解最短路徑。另外使用 SVG 實現圖的遍歷視覺化。<!DOCTYPE html>
<html lang="en">
<head>
K均值聚類演算法的MATLAB實現
單來說,K-均值聚類就是在給定了一組樣本(x1, x2, ...xn) (xi, i = 1, 2, ... n均是向量) 之後,假設要將其聚為 m(<n) 類,可以按照如下的步驟實現:
Step 1: 從 (x1, x2, ...xn) 中隨機選擇
斯坦福大學機器學習筆記——聚類(k-均值聚類演算法、損失函式、初始化、聚類數目的選擇)
上面的部落格的演算法都是有監督學習的演算法,即對於每個資料我們都有該資料對應的標籤,資料集的形式如下:
而今天我們學習的演算法是一種無監督學習的演算法——聚類,該演算法中的每個資料沒有標籤,資料集的形式如下:
K-均值聚類
k-均值聚類是一種最常見