欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python中如何實現(xiàn)徑向基核函數(shù)

 更新時間:2023年02月20日 10:16:56   作者:柳葉吳鉤  
這篇文章主要介紹了python中如何實現(xiàn)徑向基核函數(shù)問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

1、生成數(shù)據(jù)集(雙月數(shù)據(jù)集)

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、k均值聚類

def k_means(input_cells, k_count):
    count = len(input_cells)      #點的個數(shù)
    x = input_cells[0:count, 0]
    y = input_cells[0:count, 1]
    #隨機選擇K個點
    k = rd.sample(range(count), k_count)
    
    k_point = [[x[i], [y[i]]] for i in k]   #保證有序
    k_point.sort()

    global frames
    #global step
    while True:
        km = [[] for i in range(k_count)]      #存儲每個簇的索引
        #遍歷所有點
        for i in range(count):
            cp = [x[i], y[i]]                   #當(dāng)前點
            #計算cp點到所有質(zhì)心的距離
            _sse = [distance(k_point[j], cp) for j in range(k_count)]
            #cp點到那個質(zhì)心最近
            min_index = _sse.index(min(_sse))   
            #把cp點并入第i簇
            km[min_index].append(i)
        #更換質(zhì)心
       
        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 != k_point):#一直循環(huán)直到聚類中心沒有變化
            k_point = k_new
        else:
            return k_point,km

3、高斯核函數(shù)

高斯核函數(shù),主要的作用是衡量兩個對象的相似度,當(dāng)兩個對象越接近,即a與b的距離趨近于0,則高斯核函數(shù)的值趨近于1,反之則趨近于0,換言之:

兩個對象越相似,高斯核函數(shù)值就越大

作用:

  • 用于分類時,衡量各個類別的相似度,其中sigma參數(shù)用于調(diào)整過擬合的情況,sigma參數(shù)較小時,即要求分類器,加差距很小的類別也分類出來,因此會出現(xiàn)過擬合的問題;
  • 用于模糊控制時,用于模糊集的隸屬度。
def gaussian (a,b, sigma):
    return np.exp(-norm(a-b)**2 / (2 * sigma**2))

4、求高斯核函數(shù)的方差

 Sigma_Array = []
    for j in range(k_count):
        Sigma = []
        for i in range(len(center_array[j][0])):
            temp =  Phi(np.array([center_array[j][0][i],center_array[j][1][i]]),np.array(center[j]))
            Sigma.append(temp)
        Sigma = np.array(Sigma)
        Sigma_Array.append(np.cov(Sigma))

5、顯示高斯核函數(shù)計算結(jié)果

gaussian_kernel_array = []
    fig = plt.figure()
    ax = Axes3D(fig)
    
    for j in range(k_count):
        gaussian_kernel = []
        for i in range(len(center_array[j][0])):
            temp =  Phi(np.array([center_array[j][0][i],center_array[j][1][i]]),np.array(center[j]))
            temp1 = gaussian(temp,Sigma_Array[0])
            gaussian_kernel.append(temp1)
        
        gaussian_kernel_array.append(gaussian_kernel)
 
        ax.scatter(center_array[j][0], center_array[j][1], gaussian_kernel_array[j],s=20)
    plt.show()

6、運行結(jié)果

在這里插入圖片描述

7、完整代碼

# coding:utf-8
import numpy as np
import pylab as pl
import random as rd
import imageio
import math
import random
import matplotlib.pyplot as plt
import numpy as np
import mpl_toolkits.mplot3d
from mpl_toolkits.mplot3d import Axes3D

from scipy import *
from scipy.linalg import norm, pinv
 
from matplotlib import pyplot as plt
random.seed(0)

#定義sigmoid函數(shù)和它的導(dǎo)數(shù)
def sigmoid(x):
    return 1.0/(1.0+np.exp(-x))
def sigmoid_derivate(x):
    return x*(1-x) #sigmoid函數(shù)的導(dǎo)數(shù)


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

def distance(a, b):
    return (a[0]- b[0]) ** 2 + (a[1] - b[1]) ** 2
#K均值算法
def k_means(input_cells, k_count):
    count = len(input_cells)      #點的個數(shù)
    x = input_cells[0:count, 0]
    y = input_cells[0:count, 1]
    #隨機選擇K個點
    k = rd.sample(range(count), k_count)
    
    k_point = [[x[i], [y[i]]] for i in k]   #保證有序
    k_point.sort()

    global frames
    #global step
    while True:
        km = [[] for i in range(k_count)]      #存儲每個簇的索引
        #遍歷所有點
        for i in range(count):
            cp = [x[i], y[i]]                   #當(dāng)前點
            #計算cp點到所有質(zhì)心的距離
            _sse = [distance(k_point[j], cp) for j in range(k_count)]
            #cp點到那個質(zhì)心最近
            min_index = _sse.index(min(_sse))   
            #把cp點并入第i簇
            km[min_index].append(i)
        #更換質(zhì)心
       
        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 != k_point):#一直循環(huán)直到聚類中心沒有變化
            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(k_point[j][0], k_point[j][1], dcolor[j%4])
            return k_point,km
    
def Phi(a,b):
    return norm(a-b)

def gaussian (x, sigma):
    return np.exp(-x**2 / (2 * sigma**2))
        
if __name__ == '__main__':
    
    #計算平面兩點的歐氏距離
    step=0
    color=['.r','.g','.b','.y']#顏色種類
    dcolor=['*r','*g','*b','*y']#顏色種類
    frames = []
    
    N = 200
    d = -4
    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 = [[0] for y in range(1, 201)]
    labels=labels_pre+labels_pos
    
    
    k_count = 2 
    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 = []

    for j in range(k_count):
       
           center_array.append([[x[i] for i in km[j]], [y[i] for i in km[j]]])
    Sigma_Array = []
    for j in range(k_count):
        Sigma = []
        for i in range(len(center_array[j][0])):
            temp =  Phi(np.array([center_array[j][0][i],center_array[j][1][i]]),np.array(center[j]))
            Sigma.append(temp)
      
        Sigma = np.array(Sigma)
        Sigma_Array.append(np.cov(Sigma))
    
    gaussian_kernel_array = []
    fig = plt.figure()
    ax = Axes3D(fig)
    
    for j in range(k_count):
        gaussian_kernel = []
        for i in range(len(center_array[j][0])):
            temp =  Phi(np.array([center_array[j][0][i],center_array[j][1][i]]),np.array(center[j]))
            temp1 = gaussian(temp,Sigma_Array[0])
            gaussian_kernel.append(temp1)
        
        gaussian_kernel_array.append(gaussian_kernel)
        
        ax.scatter(center_array[j][0], center_array[j][1], gaussian_kernel_array[j],s=20)
    plt.show()

總結(jié)

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • Python+Turtle制作海龜迷宮小游戲

    Python+Turtle制作海龜迷宮小游戲

    這篇文章主要是帶大家寫一個利用Turtle庫制作的一款海龜闖關(guān)的三大迷宮,文中的示例代碼講解詳細,對我們學(xué)習(xí)Python有一定幫助,感興趣的可以了解一下
    2022-04-04
  • python實現(xiàn)推箱子游戲

    python實現(xiàn)推箱子游戲

    這篇文章主要為大家詳細介紹了python實現(xiàn)推箱子游戲,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-11-11
  • Python詳細講解圖像處理的而兩種庫OpenCV和Pillow

    Python詳細講解圖像處理的而兩種庫OpenCV和Pillow

    這篇文章介紹了Python使用OpenCV與Pillow分別進行圖像處理的方法,文中通過示例代碼介紹的非常詳細。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-06-06
  • Python數(shù)據(jù)可視化中的時間序列圖表功能(實例展示其強大功能)

    Python數(shù)據(jù)可視化中的時間序列圖表功能(實例展示其強大功能)

    時間序列圖表在多個領(lǐng)域中都有廣泛的應(yīng)用,通過Python中的各種繪圖庫和數(shù)據(jù)分析工具,我們可以方便地對時間序列數(shù)據(jù)進行可視化和分析,本文提供的示例代碼和方法能夠為您的時間序列數(shù)據(jù)分析工作提供有益的參考,感興趣的朋友跟隨小編一起看看吧
    2024-07-07
  • 對python:print打印時加u的含義詳解

    對python:print打印時加u的含義詳解

    今天小編就為大家分享一篇對python:print打印時加u的含義詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-12-12
  • python數(shù)據(jù)預(yù)處理之將類別數(shù)據(jù)轉(zhuǎn)換為數(shù)值的方法

    python數(shù)據(jù)預(yù)處理之將類別數(shù)據(jù)轉(zhuǎn)換為數(shù)值的方法

    下面小編就為大家?guī)硪黄猵ython數(shù)據(jù)預(yù)處理之將類別數(shù)據(jù)轉(zhuǎn)換為數(shù)值的方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-07-07
  • Python實現(xiàn)判斷變量是否是函數(shù)方式

    Python實現(xiàn)判斷變量是否是函數(shù)方式

    這篇文章主要介紹了Python實現(xiàn)判斷變量是否是函數(shù)方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-02-02
  • python創(chuàng)建Flask Talisman應(yīng)用程序的步驟詳解

    python創(chuàng)建Flask Talisman應(yīng)用程序的步驟詳解

    Flask是一個功能強大的Web框架,主要用于使用Python語言開發(fā)有趣的Web應(yīng)用程序,Talisman基本上是一個Flask擴展,用于添加HTTP安全標(biāo)頭我們的Flask應(yīng)用程序易于實施,本文就給大家講講帶Talisman的Flask安全性,需要的朋友可以參考下
    2023-09-09
  • 聊聊python中的循環(huán)遍歷

    聊聊python中的循環(huán)遍歷

    這篇文章主要介紹了python中的循環(huán)遍歷的相關(guān)資料,幫助大家更好的理解和學(xué)習(xí)python,感興趣的朋友可以了解下
    2020-09-09
  • Python安裝Bs4及使用方法

    Python安裝Bs4及使用方法

    這篇文章主要介紹了Python安裝Bs4及使用方法,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-04-04

最新評論