我可以为ELM分类器实施迭代训练循环吗?

如何解决我可以为ELM分类器实施迭代训练循环吗?

我正在使用Extreme Learning Machine分类器进行手势识别,但是我仍然有20%的准确性。有人可以帮我实施一个迭代训练循环来提高准确性吗?我是初学者,这里使用的代码:我将标准化后准备的数据集分为训练部分和测试部分,然后使用训练函数通过计算Moore Penrose逆来训练它,然后使用预测函数预测每个手势的类。

# -*- coding: utf-8 -*-
"""
Created on Sat Jul  4 17:52:25 2020

@author: lenovo
"""

# -*- coding: utf-8 -*-
__author__ = 'Sarra'

import numpy as np

class ELM(object):  

def __init__(self,inputSize,outputSize,hiddenSize):
    """
    Initialize weight and bias between input layer and hidden layer
    Parameters:
    inputSize: int
        The number of input layer dimensions or features in the training data
    outputSize: int
        The number of output layer dimensions
    hiddenSize: int
        The number of hidden layer dimensions        
    """    

    self.inputSize = inputSize
    self.outputSize = outputSize
    self.hiddenSize = hiddenSize       
    
    # Initialize random weight with range [-0.5,0.5]
    self.weight = np.matrix(np.random.uniform(-0.5,0.5,(self.hiddenSize,self.inputSize)))

    # Initialize random bias with range [0,1]
    self.bias = np.matrix(np.random.uniform(0,1,(1,self.hiddenSize)))
    
    self.H = 0
    self.beta = 0

def sigmoid(self,x):
    """
    Sigmoid activation function
    
    Parameters:
    x: array-like or matrix
        The value that the activation output will look for
    Returns:      
        The results of activation using sigmoid function
    """
    return 1 / (1 + np.exp(-1 * x))

def predict(self,X):
    """
    Predict the results of the training process using test data
    Parameters:
    X: array-like or matrix
        Test data that will be used to determine output using ELM
    Returns:
        Predicted results or outputs from test data
    """
    X = np.matrix(X)
    y = self.sigmoid((X * self.weight.T) + self.bias) * self.beta

    return y

def train(self,X,y):
    """
    Extreme Learning Machine training process
    Parameters:
    X: array-like or matrix
        Training data that contains the value of each feature
    y: array-like or matrix
        Training data that contains the value of the target (class)
    Returns:
        The results of the training process   
    """

    X = np.matrix(X)
    y = np.matrix(y)        
    
    # Calculate hidden layer output matrix (Hinit)
    self.H = (X * self.weight.T) + self.bias

    # Sigmoid activation function
    self.H = self.sigmoid(self.H)

    # Calculate the Moore-Penrose pseudoinverse matriks        
    H_moore_penrose = np.linalg.pinv(self.H.T * self.H) * self.H.T

    # Calculate the output weight matrix beta
    self.beta = H_moore_penrose * y

    return self.H * self.beta


import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from sklearn import preprocessing
from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
# read the dataset
database = pd.read_csv(r"C:\\Users\\lenovo\\tensorflow\\tensorflow1\\Numpy-ELM\\hand_gestures_database.csv")                  
#separate data from labels 
data = database.iloc[:,1:].values.astype('float64')

#normalize data
#n_data = preprocessing.minmax_scale(data,feature_range=(0,1),axis=0,copy=True)
scaler = MinMaxScaler()
scaler.fit(data)
n_data = scaler.transform(data)
#identify the labels 
label = database.iloc[:,0]
#encoding labels to transform each label to a value between 0 to number of labels-1
def prepare_targets(n):
    le =preprocessing.LabelEncoder()
    le.fit(n)
    label_enc = le.transform(n)
    return label_enc
label_enc = prepare_targets(label)
CLASSES = 10
#transform the value of each label to a  binary vector 
target = np.zeros([label_enc.shape[0],CLASSES])
for i in range(label_enc.shape[0]):
     target[i][label_enc[i]] = 1
target.view(type=np.matrix)
print("target",target)



# Create instance of ELM object with 10 hidden neuron
maxx=0
for u in range(10):
    elm = ELM(45,10,10)

    # Train test split 80:20
    X_train,X_test,y_train,y_test = train_test_split(n_data,target,test_size=0.34,random_state=1)

    elm.train(X_train,y_train)

    y_pred = elm.predict(X_test)

    # Train data
    correct = 0

    total = y_pred.shape[0]
    for i in range(total):
        predicted = np.argmax(y_pred[i])
        test = np.argmax(y_test[i])
        correct = correct + (1 if predicted == test else 0)    
    print('Accuracy: {:f}'.format(correct/total))
    if(correct/total>maxx):
        maxx=correct/total
print(maxx)
###confusion matrix    
import seaborn as sns
y_pred=np.argmax(y_pred,axis=1)
y_true=(np.argmax(y_test,axis=1))

target_names=["G1","G2","G3","G4","G5","G6","G7","G8","G9","G10"]

cm=confusion_matrix(y_true,y_pred)
#cmn = cm.astype('float')/cm.sum(axis=1)[:,np.newaxis]*100

fig,ax = plt.subplots(figsize=(15,8))
sns.heatmap(cm/np.sum(cm),annot=True,fmt='.2f',xticklabels=target_names,yticklabels=target_names,cmap='Blues')

#sns.heatmap(cmn,fmt='.2%',yticklabels=target_names)
plt.ylabel('Actual')
plt.xlabel('Predicted')
plt.ylim(-0.5,len(target_names) + 0.5)
plt.show(block=False)
def perf_measure(y_actual,y_pred):
    TP = 0
    FP = 0
    TN = 0
    FN = 0

for i in range(len(y_pred)): 
    if y_actual[i]==y_pred[i]==1:
       TP += 1
    if y_pred[i]==1 and y_actual[i]!=y_pred[i]:
       FP += 1
    if y_actual[i]==y_pred[i]==0:
       TN += 1
    if y_pred[i]==0 and y_actual[i]!=y_pred[i]:
       FN += 1

return(TP,FP,TN,FN)

TP,FN=perf_measure(y_true,y_pred)
print("precision",TP/(TP+FP))
print("sensivity",TP/(TP+FN))
print("specifity",TN/(TN+FP)) 
print("accuracy",(TP+TN)/(TN+FP+FN+TP))       

解决方法

关于您是否可以为ELM实施迭代训练循环的问题:

不,您不能。 ELM由一个随机层和一个输出层组成。因为第一层是固定的,所以它本质上是线性模型,正如您所指出的,我们可以使用伪逆来找到最佳输出权重。

但是,由于您已经一步找到了该模型的理想解决方案,因此没有直接的方法来迭代地改善此结果。

但是,我不建议您使用极限学习机。 除了controversy的起源以外,他们在学习功能方面也非常有限。

还有其他一些行之有效的手势分类方法,可能会更有用。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 <select id="xxx"> SELECT di.id, di.name, di.work_type, di.updated... <where> <if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 <property name="dynamic.classpath" value="tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -> systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping("/hires") public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate<String
使用vite构建项目报错 C:\Users\ychen\work>npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-