PSO优化MLP神经网络分类预测
# -*- coding: utf-8 -*-
import torch
import numpy as np
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
import matplotlib.pyplot as plt
import pandas as pd
#加载数据
def load_and_process_data():
data = pd.read_csv('data/data.csv').values
X = data[:, :3]
y = data[:, -1]
# 数据标准化
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)
return X_train_tensor, y_train_tensor, X_test_tensor, y_test_tensor
# 定义模型
class Classifier(torch.nn.Module):
def __init__(self, input_dim, output_dim, num_hidden_units):
super(Classifier, self).__init__()
self.linear1 = torch.nn.Linear(input_dim, num_hidden_units)
self.linear2 = torch.nn.Linear(num_hidden_units, output_