神经网络是最著名且使用最广泛的算法之一。在监督学习中,我们标记了输出数据,我们将预测输出与实际标签进行比较,然后计算误差。在神经网络中,我们以同样的方式定义神经网络体系结构,通过比较实际标签和预测标签来计算误差,然后使用某种优化算法来优化该误差。训练神经网络最广泛使用的算法是反向传播和梯度下降。但是,我们可以使用任何优化算法来训练我们的神经网络模型。今天我们将看看如何在Python中使用Numpy用粒子群优化来训练神经网络模型。
神经网络
导入Python库
from sklearn.datasets import load_irisfrom pso_numpy import *import numpy as np
导入sklearn加载Iris flower机器学习数据集,pso_numpy使用PSO算法,numpy执行神经网络的forward pass。
加载机器学习数据集
#load iris dataset..data = load_iris()#Store input & target in X and Y..X = data.dataY = data.target
从sklearn加载Iris数据集,并将输入数据分配给X,将目标标签分配给Y。
定义架构
#define no of nodes in each layer..INPUT_NODES = 4HIDDEN_NODES = 20OUTPUT_NODES = 3
在神经网络模型中定义输入,隐藏和输出节点数。
One-hot编码
def one_hot_encode(Y): """ create one-hot encoded vectors from target labels(Y). :param Y: int(N, ) :return: int(N, C) Returns an array of shape(N, C) where C is number of classes. """ num_unique = len(np.unique(np.array(Y))) zeros = np.zeros((len(Y), num_unique)) zeros[range(len(Y)), Y] = 1 return zeros
如果我们要计算分类交叉熵损失,则使用One-hot编码。将唯一的向量分配给每个目标标签(类)。该函数将Y作为输入,并为每个类返回One-hot编码向量。
Softmax激活
def softmax(logits): """ Apply softmax function on logits and return probabilities. :param logits: double(N, C) Logits of each instance for each class. :return: double(N, C) probability for each class of each instance. """ exps = np.exp(logits) return exps / np.sum(exps, axis=1, keepdims=True)
使用Softmax函数从logits(不应用任何激活的最后一层的输出)计算每个类的概率。
损失函数
def Negative_Likelihood(probs, Y): """ Calculates Negative Log Likelihood loss. :param probs: double(N, C) Probability of each instance for each class. :param Y: int(N, ) Integer representation of each class. :return: double Returns value of loss calculated. """ num_samples = len(probs) corect_logprobs = -np.log(probs[range(num_samples), Y]) return np.sum(corect_logprobs) / num_samplesdef Cr