# -*- coding: UTF-8 -*-
import warnings
import sklearn
warnings.filterwarnings('ignore')
from sko.PSO import PSO
import datetime
import numpy as np
import math
import pandas as pd
from sklearn import model_selection
import sys
import tensorflow as tf
from tensorflow import keras
# import tensorflow.keras as keras
import matplotlib as mpl
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
from neupy import algorithms
from Optimizers.optimizers import SSA,HHO,PSO
def load_data(filename):
'''导入数据
input: file_path(string):训练数据
output: feature(mat):特征
label(mat):标签
'''
p1_base_attribute = ['梳棉出条线速度', '梳棉AFIS的棉结1', '梳棉AFIS的棉结2', '梳棉AFIS的短绒率1', '梳棉AFIS的短绒率2', '梳棉落棉率', '预并出条线速度',
'精梳AFIS的棉结1', '精梳AFIS的棉结2', '精梳AFIS的短绒率1', '精梳AFIS的短绒率2', '精梳落棉率', '精梳钳次', '粗纱捻缩率',
'细纱捻缩率', '平均锭子速度', '牵伸倍数', '原棉短绒率', '原棉棉结', '原棉马克隆值', '强度', '右半部平均长度', '长度整齐度', '含杂率',
'细纱号数']
al_value = ['强力', '棉结', '条干CV', '毛羽H值', '单强CV']
al_value = ['毛羽H值']
data = pd.read_excel(r'' + filename,
index_col=None, header=0)
scaler = MinMaxScaler(feature_range=(0, 1))
scaler1 = MinMaxScaler(feature_range=(0, 1))
data_x, data_y = [], []
for i in range(len(p1_base_attribute)):
data_x.append(data[p1_base_attribute[i]])
for i in range(len(al_value)):
data_y.append(data[al_value[i]])
data = data_x + data_y
data = np.array(data).reshape((len(p1_base_attribute) + len(al_value), -1))
data_yyy = np.array(data_y).reshape(len(al_value), -1)
data = scaler.fit_transform(np.transpose(data))
data_yyy = scaler1.fit_transform(np.transpose(data_yyy))
data = data.reshape(-1, len(p1_base_attribute) + len(al_value))
train_data, train_target = data[:, :-len(al_value)], data[:, -len(al_value):]
return train_data, train_target, scaler1
train_data, train_target, scaler = load_data('F:/study/402实验室/成纱质量预测/成纱质量预测论文/基于不同优化算法的GRNN纱线不均匀度预测/data.xlsx')
## 2.数据集和测试集
print('--------------------2.Train Set and Test Set--------------------')
data_x, test_x, data_y, test_y = model_selection.train_test_split(
train_data, train_target, test_size=0.1, random_state=1)
starttime = datetime.datetime.now()
def demo_func(test_other):
nw = algorithms.GRNN(std=test_other, verbose=False)
nw.train(data_x, data_y)
y_predicted = scaler.inverse_transform(nw.predict(test_x))
mse = np.sum((y_predicted - scaler.inverse_transform(test_y))**2)/ len(test_y)
return mse*10000000
maxgen = 50
jiange = 10
res = []
legends = []
for i in range(10):
popsize = jiange*(i+1)
legends.append('popsize='+str(popsize))
hho = HHO.HHO(demo_func, 0.00000000001,1, 1, popsize, maxgen,
)
res.append(hho.convergence[1:])
print('run_time is ', hho.executionTime)
print('best_y',hho.convergence[-1])
print('best_x',hho.bestFoodPositions[-1])
print(hho.bestFoodPositions.tolist().index(hho.bestFoodPositions[-1]))
nw = algorithms.GRNN(std=hho.bestFoodPositions[-1], verbose=False)
nw.train(data_x, data_y)
y_predicted = scaler.inverse_transform(nw.predict(test_x))
print(y_predicted)
plt.figure(1)
for i in range(10):
plt.plot(range(49),res[i])
plt.xlabel('Number of iterations')
plt.ylabel('MSE value')
plt.rcParams['savefig.dpi'] = 600 # 图片像素
plt.rcParams['figure.dpi'] = 600 # 分辨率
plt.ylim(30999,31002)
plt.xlim(0,50)
plt.legend(legends)
plt.savefig('HHO_'+str(jiange)+'.jpg')
plt.show()
nw = algorithms.GRNN(std=hho.bestFoodPositions[-1], verbose=False)
endtime = datetime.datetime.now()
print(endtime-starttime)
nw.train(data_x, data_y)
y_predicted = scaler.inverse_transform(nw.predict(test_x))
mse_test = np.sum((y_predicted - scaler.inverse_transform(test_y)) ** 2)/ len(test_y)
rmse_test = mse_test ** 0.5
mae_test = np.sum(np.absolute(y_predicted - scaler.inverse_transform(test_y))) / len(test_y)
r2 = sklearn.metrics.r2_score(scaler.inverse_transform(test_y), y_predicted)
print(test_x,scaler.inverse_transform(test_y),y_predicted)
print(mse_test,rmse_test,mae_test,r2)
plt.figure(1)
plt.plot(range(7),scaler.inverse_transform(test_y))
doc = plt.scatter(range(7), scaler.inverse_transform(test_y), color='green') #绘点图
plt.plot(range(7),y_predicted)
doc1 = plt.scatter(range(7), y_predicted, color='red') #绘点图
plt.xlabel('Sample number')
plt.ylabel('Hairiness(H)')
plt.rcParams['savefig.dpi'] = 3000 # 图片像素
plt.rcParams['figure.dpi'] = 3000 # 分辨率
plt.ylim(1.9,2.3)
plt.xlim(0,6)
plt.legend(['target','output'])
plt.savefig('result.jpg')
plt.show()