# -*- 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 Dense,Dropout,Activation
from keras.optimizers import Adam,SGD
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_sizepop,pso_longpop) -5
pso_V = 2 * np.random.rand(pso_sizepop,pso_longpop) -1
# 评价粒子适应度
pso_fitness = np.random.rand(pso_sizepop,1) +5
i = 0 #pso种群粒子长度迭代index
while i < pso_sizepop:
print ( 'fitness: ' + str(i))
pso_fitness[i]=Fitness.fit(train_input,train_output,test_input,test_output,pso_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(0,pso_longpop)] = 10 * np.random.random() -5
pso_fitness[k]=Fitness.fit(train_input,train_output,test_input,test_output,pso_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_zbest_fit = pso_fitness[k]
k = k + 1
k = 0
fit_history.append(pso_zbest_fit)
j = j +1
评论1