资源简介
粒子群优化算法对BPNN进行超参数优化的python代码实现,亲测可用
代码片段和文件信息
# -*- coding: utf-8 -*-
“““
Created on Fri Apr 13 20:40:15 2018
@author: wanglei
“““
from datasets import LoadData
from datasets import Fitness
from keras.models import Sequential
from keras.layers import DenseDropoutActivation
from keras.optimizers import AdamSGD
from keras.utils.visualize_plots import figures
import matplotlib.pyplot as plt
import numpy as np
#数据导入
data = LoadData.load_data()
train_input = data[‘train_input‘]
train_output = data[‘train_output‘]
test_input = data[‘test_input‘]
test_output = data[‘test_output‘]
#神经网络参数设置
inputnum = train_input.shape[1]
hiddennum = 12
outputnum = train_output.shape[1]
#PSO 参数设置
pso_c1 = 1.499455
pso_c2 = 1.49445
pso_maxgen = 200
pso_sizepop = 30 #pso 种群中粒子数
pso_longpop = inputnum*hiddennum+hiddennum*outputnum+hiddennum+outputnum
pso_Vmax = 1
pso_Vmin = -1
pso_popmax = 5
pso_popmin = -5
# 粒子位置/速度初始化
pso_pop = 10 * np.random.rand(pso_sizepoppso_longpop) -5
pso_V = 2 * np.random.rand(pso_sizepoppso_longpop) -1
# 评价粒子适应度
pso_fitness = np.random.rand(pso_sizepop1) +5
i = 0 #pso种群粒子长度迭代index
while i < pso_sizepop:
print ( ‘fitness: ‘ + str(i))
pso_fitness[i]=Fitness.fit(train_inputtrain_outputtest_inputtest_outputpso_pop[i])
i = i +1
pso_fitBest = pso_fitness.min()
pso_fitBest_index = np.argmin(pso_fitness)
pso_zbest = pso_pop[pso_fitBest_index] #全局最佳
pso_gbest = pso_pop #个体最佳 初始为pop初始值
pso_zbest_fit = pso_fitBest #全局最佳值的适应度
pso_gbest_fit = pso_fitness
fit_history = []
fit_history.append(pso_zbest_fit)
#PSO 迭代
j = 0 # pso种群迭代代数index
k = 0 # pso种群粒子长度迭代index
while j < pso_maxgen:
print ( ‘gen:‘ + str(j))
while k < pso_sizepop:
print( ‘gen:‘ + str(j) + ‘pop update:‘ + str(k))
#速度更新
pso_V[k] = pso_V[k] + pso_c1 * np.random.random_sample() * (pso_gbest[k] - pso_pop[k]) + pso_c2 * np.random.random_sample() * (pso_zbest - pso_pop[k])
#超过界限的置为界限
pso_V[k][np.argwhere(pso_V[k] > pso_Vmax)] = pso_Vmax
pso_V[k][np.argwhere(pso_V[k] < pso_Vmin)] = pso_Vmin
#位置更新
pso_pop[k] = pso_pop[k] + 0.2 * pso_V[k]
pso_pop[k][np.argwhere(pso_pop[k] > pso_popmax)] = pso_popmax
pso_pop[k][np.argwhere(pso_pop[k] < pso_popmin)] = pso_popmin
#自适应变异
if np.random.random_sample() > 0.95:
pso_pop[k][np.random.randint(0pso_longpop)] = 10 * np.random.random() -5
pso_fitness[k]=Fitness.fit(train_inputtrain_outputtest_inputtest_outputpso_pop[k])
k = k + 1
#更新个体/群体最优值
k = 0
while k < pso_sizepop:
print (‘gen:‘ + str(j) + ‘ best update‘ + str(k))
if pso_fitness[k] < pso_gbest_fit[k]:
pso_gbest[k] = pso_pop[k]
pso_gbest_fit[k] = pso_fitness[k]
if pso_fitness[k] < pso_zbest_fit:
pso_zbest = pso_pop[k]
pso_zbes
属性 大小 日期 时间 名称
----------- --------- ---------- ----- ----
文件 3345 2018-04-13 20:43 PSO.py
文件 2773 2018-07-17 20:42 PSO_BP.py
----------- --------- ---------- ----- ----
6118 2
评论
共有 条评论