基于Python语言的PSO-LSTM实现分类,源数据如图所示:
在这里插入代码片
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense, Input
from pyswarm import pso
import matplotlib.pyplot as plt
# 读取数据
data = pd.read_excel('1.xlsx', header=None)
# 假设数据的第1到第6列是特征,第7列是标签
X = data.iloc[:, 1:6].values
y = data.iloc[:, 6].values
# 数据归一化
scaler = StandardScaler()
X = scaler.fit_transform(X)
# 分割训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 将输入数据形状调整为 (samples, time_steps, features)
X_train = np.expand_dims(X_train, axis=2)
X_test = np.expand_dims(X_test, axis=2)
# 定义LSTM模型
def create_lstm_model(input_shape, units, dropout):
model = Sequential()
model.add(Input(shape=input_shape))
model.add(LSTM(units=units, dropout=dropout))
model.add(Dense(5, activation='softmax')) # 假设有4个类别
model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
return model
# 适应度函数
def fitness_function(params):
units, dropout = params
units = int(units)
dropout = float(dropout)
model = create_lstm_model((X_train.shape[1], X_train.shape[2]), units, dropout)
model.fit(X_train, y_train, epochs=50, batch_size=5, verbose=0)
loss, accuracy = model.evaluate(X_test, y_test, verbose=0)
return 1 - accuracy
# PSO参数
lb = [10, 0.0] # 最低单元数和最小dropout
ub = [100, 0.5] # 最高单元数和最大dropout
# 执行PSO
best_params, best_fitness = pso(fitness_function, lb, ub, swarmsize=10, maxiter=10)
# 最优参数
best_units = int(best_params[0])
best_dropout = best_params[1]
# 使用最优参数训练最终模型
final_model = create_lstm_model((X_train.shape[1], X_train.shape[2]), best_units, best_dropout)
final_model.fit(X_train, y_train, epochs=50, batch_size=5, verbose=1)
# 评估最终模型
loss, accuracy = final_model.evaluate(X_test, y_test)
print(f'Final Model Accuracy: {accuracy * 100:.2f}%')
# 生成预测值
y_pred = final_model.predict(X_test)
y_pred_classes = np.argmax(y_pred, axis=1)
# 绘制实际值和预测值对比图
plt.figure(figsize=(14, 7))
plt.plot(y_test, label='Actual Values')
plt.plot(y_pred_classes, label='Predicted Values', linestyle='dashed')
plt.title('Actual vs Predicted Values')
plt.xlabel('Sample Index')
plt.ylabel('Class')
plt.legend()
plt.show()
计算结果如下图所示,没有对图片进行美化。