?九月?份了,車神哥又回歸了校園 ?冬天 ?還會遠嗎 ?推薦一首最近很?喜歡?的歌? ?No Fear In My Heart -樸樹 ?
由于最近在寫一篇相關的論文,就說說其中遇到的一些問題吧~
Minisom
之前做過一個對minisom的第三方開源庫的介紹,可以點擊看這里。
對相應的代碼添加了注釋:
導入各種庫吧
# 導入庫
from sklearn
. model_selection import train_test_split
from sklearn
. metrics import classification_report
import numpy as np
import matplotlib
. pyplot as plt
from matplotlib
. patches import Patch
import pandas as pd
from minisom import MiniSom
import math
import xlrd
from icecream import ic
from tqdm import tqdm
from openpyxl import load_workbook
import openpyxl
from time import time
第一步是導入數據的Function,這很簡單就不解釋了
# 傳入數據成DataFrame的矩陣格式
def
loaddata ( datafile
, num_name
) : df
= pd
. read_excel ( datafile
, sheet_name
= num_name
, index_col
= 0 ) # 導入數據
return df # 返回值
由于代碼不是很長,就沒有按照模塊來寫了
然后是導入源文件及其標簽。 說實話,在現實項目中,想要找到不同特征的標簽是真的真的真的太難了!!! 不要問為什么,當你實踐你就知道了~
# 導入原始數據
#
1. 導入訓練和測試數據集
datafile
= "*********.xls" # 原始數據文件名
#
2. 導入標簽數據
y
= pd
. DataFrame ( pd
. read_csv ( 'label****.csv' ) ) # 讀取你的標簽數據或者原有的標簽是最好的yy
= [ ] # 設置空矩陣# 循環將標簽導入yy矩陣中
for iy in
range ( y
. shape
[ 0 ] ) : Uy
= y
. iloc
[ iy
, 0 ] yy
. append ( int ( Uy
) ) y
= yy # 賦值給y
再讀取每個sheet中的不同特征名稱,我的數據集是這樣,如果你沒有特征名稱,最好對其進行標記,這樣會更加有效。
#
3. 讀取特征標簽
feature_names
= pd
. DataFrame ( pd
. read_excel ( datafile
, index_col
= 0 ) ) . columns # 取數據的列:特征標簽
class_names
= [ 0 , 1 ] # 標簽名稱feat
= [ ] # 設置空矩陣
# 循環將特征名稱添加到feat矩陣中
for tz in
range ( feature_names
. shape
[ 0 ] ) : tezh
= feature_names
[ tz
] feat
. append ( tezh
) # 逐步添加進featfeature_names
= feat # 賦值給feature_names
print ( '特征名稱:' , feature_names
)
由于我的源文件會有很多個sheet,所以需要對每一個sheet進行訓練及測試,再進行保存操作,如果你只要一個數據表的話,可以對此進行相應的改進。
# 按照每一個數據Sheet讀取每一層的數據
# 讀取文件數據集
workbook
= xlrd
. open_workbook ( datafile
) # 打開數據文件
sheets
= workbook
. sheet_names ( ) # 讀取原始數據的數據表sheet名
SheetNames
= [ ] # 設置空矩陣
# 循環輸出
for sheetname in
tqdm ( sheets
) : print ( "表格的名稱是:" , sheetname
) SheetNames
. append ( sheetname
) # 循環添加進空矩陣SheetNames中
print ( '原始數據表的表單名稱為:' , SheetNames
)
num_n
= pd
. DataFrame ( SheetNames
) . shape
[ 0 ] # 獲取表單的個數
print ( '表單的個數為:' , num_n
) # 設置空數據表
1
dff
= pd
. DataFrame ( columns
= [ "title" , "content" ] ) # 添加列名
dff
. to_excel ( 'SOM_Result.xlsx' ) # 保存到
'SOM_Result.xlsx' ## 設置空數據表
2
dff2
= pd
. DataFrame ( columns
= [ "title1" , "content1" ] ) # 添加列名
dff2
. to_excel ( 'SOM_label_result.xlsx' ) # 保存到
'SOM_label_result.xlsx' start_time
= time ( ) # 記錄設置開始的時間
接下來也是對我的每一個表單進行循環遍歷訓練及其測試的過程,如果只需要進行一次,那么只需要取消循環過程,更改其中的一些變量即可。 其中包含SOM的訓練及測試,權值矩陣、map、聚類結果的可視化,精確度等操作。
for i_c in
range ( num_n
) : if i_c
< num_n
: print ( '程序目前處在第%r層數.' % SheetNames
[ i_c
] ) XMat
= loaddata ( datafile
, num_name
= SheetNames
[ i_c
] ) # 返回得到浮點型矩陣# 設置空數據表
1 dff
= pd
. DataFrame ( columns
= [ "title" , "content" ] ) # 添加列名dff
. to_excel ( 'SOM_Result_' + SheetNames
[ i_c
] + '.xlsx' ) # 保存到
'SOM_Result.xlsx' ## 設置空數據表
2 dff2
= pd
. DataFrame ( columns
= [ "title1" , "content1" ] ) # 添加列名dff2
. to_excel ( 'SOM_label_result_' + SheetNames
[ i_c
] + '.xlsx' ) # 保存到
'SOM_label_result.xlsx' X
= XMat
. values # 將DataFrame格式改為np
. array矩陣# 劃分訓練集、測試集
7 : 3 X_train
, X_test
, y_train
, y_test
= train_test_split ( X
, y
, test_size
= 0.3 , random_state
= 0 ) # X為原始數據,y為標簽數據,test_size為訓練集和測試集劃分比例,random_state為選擇隨機打亂的方式,可設置為
0 或
1 方式N
= X_train
. shape
[ 0 ] #樣本數量M
= X_train
. shape
[ 1 ] #維度
/ 特征數量
'' '設置超參數
'' 'size
= math
. ceil ( np
. sqrt ( 5 * np
. sqrt ( N
) ) ) # 經驗公式:決定輸出層尺寸
print ( "訓練樣本個數:{} 測試樣本個數:{}" . format ( N
, X_test
. shape
[ 0 ] ) ) print ( "輸出網格最佳邊長為:" , size
) max_iter
= 1000 # 迭代次數
# Initialization and training(初始化及其訓練) size為神經元數,M為輸入維度/ 特征數量, learning——rate為學習率 som
= MiniSom ( size
, size
, M
, sigma
= 3 , learning_rate
= 0.5 , neighborhood_function
= 'bubble' ) # Neighborhood_function’近鄰函數‘可選的設置有
'gaussian' 、
'mexican_hat' 、
'bubble' . 調參的時候可以都試一遍,看效果
'' '初始化權值,有
2 個API
'' 'som
. pca_weights_init ( X_train
) # PCA降維初始化som
. train_batch ( X_train
, max_iter
, verbose
= False
) # train_batch 每次按順序取一個樣本,用過最后一個樣本后跳回第一個樣本,循環直到迭代次數滿足max_iterwinmap
= som
. labels_map ( X_train
, y_train
) # 求取獲勝神經元# 判斷樣本的類別def
classify ( som
, data
, winmap
) : from numpy import sum as npsum # 導入庫default_class
= npsum ( list ( winmap
. values ( ) ) ) . most_common ( ) [ 0 ] [ 0 ] # 獲取獲勝神經元的值result
= [ ] # 設置空矩陣
for d in data
: # 循環迭代win_position
= som
. winner ( d
) # 獲勝神經元的權值位置
if win_position in winmap
: # 判斷是否屬于獲勝神經元result
. append ( winmap
[ win_position
] . most_common ( ) [ 0 ] [ 0 ] ) # 將其添加進空矩陣result中
else : result
. append ( default_class
) # 若不滿足上面的條件則將default_class添加進result中
print ( '輸出result結果:' , result
) return result # 返回值# 輸出混淆矩陣y_pred
= classify ( som
, X_test
, winmap
) # 調用classify函數
print ( classification_report ( y_test
, np
. array ( y_pred
) ) ) # 輸出混淆矩陣# 繪制各種圖
# U- Matrix heatmap
= som
. distance_map ( ) #生成U
- Matrixplt
. imshow ( heatmap
, cmap
= 'bone_r' ) #miniSom案例中用的pcolor函數
, 需要調整坐標plt
. colorbar ( ) # 顏色卡plt
. figure ( figsize
= ( 9 , 9 ) ) # 設置圖像大小# 背景上畫U
- Matrixheatmap
= som
. distance_map ( ) # 熱力圖plt
. pcolor ( heatmap
, cmap
= 'bone_r' ) # plotting the distance map as background 設置樣式# 定義不同標簽的圖案標記markers
= [ 'o' , 's' ] # 設置圖案樣式colors
= [ 'C0' , 'C1' ] # 定義不同標簽圖案的顏色category_color
= { 'Normal' : 'C0' , 'fault' : 'C1' , } # 設置對應字典
for cnt
, xx in
enumerate ( X_train
) : # 迭代獲取X_train訓練數據w
= som
. winner ( xx
) # getting the winner# 在樣本Heat的地方畫上標記plt
. plot ( w
[ 0 ] + .5 , w
[ 1 ] + .5 , markers
[ y_train
[ cnt
] ] , markerfacecolor
= 'None' , markeredgecolor
= colors
[ y_train
[ cnt
] ] , markersize
= 12 , markeredgewidth
= 2 ) # plot繪制圖像,markerfacecolor:標記顏色,markersize:標記尺寸,markeredgewidth:標記寬度plt
. axis ( [ 0 , size
, 0 , size
] ) # 設置坐標系ax
= plt
. gca ( ) # 進行坐標軸的移動
, gca就是get current axesax
. invert_yaxis ( ) #顛倒y軸方向legend_elements
= [ Patch ( facecolor
= clr
, edgecolor
= 'w' , label
= l
) for l
, clr in category_color
. items ( ) ] plt
. legend ( handles
= legend_elements
, loc
= 'center left' , bbox_to_anchor
= ( 1 , .95 ) ) # 設置圖像界面細節
# plt . show ( ) # 顯示圖label_name_map_number
= { "Normal" : 0 , "Fault" : 1 } # 神經元占比餅圖from matplotlib
. gridspec import GridSpecplt
. figure ( figsize
= ( 9 , 9 ) ) # 設置圖像界面大小the_grid
= GridSpec ( size
, size
) # 神經元個數
for position in winmap
. keys ( ) : # 迭代獲取獲勝神經元位置label_fracs
= [ winmap
[ position
] [ label
] for label in
[ 0 , 1 ] ] # 獲取標簽plt
. subplot ( the_grid
[ position
[ 1 ] , position
[ 0 ] ] , aspect
= 1 ) # 表示把顯示界面分割成the_grid
[ position
[ 1 ] * position
[ 0 ] 的網格patches
, texts
= plt
. pie ( label_fracs
) # 用于繪制餅圖plt
. text ( position
[ 0 ] / 100 , position
[ 1 ] / 100 , str ( len ( list ( winmap
[ position
] . elements ( ) ) ) ) , color
= 'black' , fontdict
= { 'weight' : 'bold' , 'size' : 15 } , va
= 'center' , ha
= 'center' ) # 給圖中加標簽plt
. legend ( patches
, class_names
, loc
= 'center right' , bbox_to_anchor
= ( - 1 , 9 ) , ncol
= 3 ) # 顯示圖中的各種標簽
# plt . show ( ) # 輸出顯示圖像# 權重熱力圖plt
. figure ( figsize
= ( 10 , 10 ) ) # 設置圖像大小
for i
, f in
enumerate ( feature_names
) : # 迭代循環獲取feature_names特征plt
. subplot ( 4 , 4 , i
+ 1 ) # 表示把顯示界面分割成
4 * 4 的網格plt
. title ( f
) # 設置標題W
= som
. get_weights ( ) # 獲得權重數據plt
. imshow ( W
[ : , : , i
] , cmap
= 'coolwarm' ) # 輸出熱力圖,W
[ : , : , i
] 變量存儲圖像,可以是浮點型數組、unit8數組以及PIL圖像,參數cmap用于設置熱圖的Colormap,代表熱力塊的樣式顏色plt
. colorbar ( ) # colorbar,顏色卡尺plt
. xticks ( np
. arange ( size
+ 1 ) ) # 設置主圖的橫坐標的刻度字體大小plt
. yticks ( np
. arange ( size
+ 1 ) ) # 設置主圖的縱坐標的刻度字體大小
# plt . show ( ) # 輸出顯示圖像# 保存result——label
print ( '開始SOM標簽Result保存!' ) df_winmap
= pd
. DataFrame
. from_dict ( winmap
, orient
= 'index' ) # 讀取轉換winmap
ic ( df_winmap
) # 輸出顯示df_winmapwriter1
= pd
. ExcelWriter ( 'SOM_label_result_' + SheetNames
[ i_c
] + '.xlsx' , engine
= 'openpyxl' ) # 讀取
'SOM_label_result.xlsx' book1
= load_workbook ( writer1
. path
) # 獲取文件路徑writer1
. book
= book1 # 賦值df_winmap
. to_excel ( excel_writer
= writer1
, sheet_name
= str ( SheetNames
[ i_c
] ) ) # 建立為數據表writer1
. save ( ) # 保存數據表writer1
. close ( ) # 關閉數據表
print ( 'SOM標簽Result保存結束!' ) # 保存result_data
print ( '開始SOM最終Result坐標保存!' ) winner
= som
. win_map ( X_train
, return_indices
= True
) # 獲取SOM的獲勝神經元結果my_df
= pd
. DataFrame
. from_dict ( winner
, orient
= 'index' ) # 轉換輸出賦值給my_df
ic ( my_df
) # 顯示輸出writer
= pd
. ExcelWriter ( 'SOM_Result_' + SheetNames
[ i_c
] + '.xlsx' , engine
= 'openpyxl' ) # 建立數據表
'SOM_Result.xlsx' book
= load_workbook ( writer
. path
) # 獲取文件路徑writer
. book
= book # 賦值my_df
. to_excel ( excel_writer
= writer
, sheet_name
= str ( SheetNames
[ i_c
] ) ) # 保存數據表writer
. save ( ) # 保存操作writer
. close ( ) # 關閉操作
print ( 'SOM最終Result坐標保存結束!' )
大體的流程就是這樣了,minisom的庫訓練起來比Matlab快了不知道多少倍,?yyds?!!!
九月,加油吧!!!
?堅持讀Paper ,堅持做筆記 ,堅持學習 ?!!! ?To Be No.1
??哈 哈 哈 哈
?創作不易 ?,過路能?關注 、收藏 、點個贊 ?三連 就最好不過了
?( ′・?・` )
?
『 我是這耀眼的瞬間,是劃過天邊的剎那火焰. 』
總結
以上是生活随笔 為你收集整理的⚡自组织映射(SOM)神经网络⚡Python实现 |Python技能树征题 的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔 網站內容還不錯,歡迎將生活随笔 推薦給好友。