GA-SVN多分类python
时间: 2023-07-24 09:17:21 浏览: 105
以下是一个使用遗传算法(GA)优化支持向量机(SVM)进行多分类的Python代码示例:
```python
from sklearn.svm import SVC
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
import numpy as np
import random
# 加载数据集
iris = load_iris()
X = iris.data
y = iris.target
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# 定义适应度函数
def svm_fitness(params):
C, gamma = params
clf = SVC(C=C, kernel='rbf', gamma=gamma)
clf.fit(X_train, y_train)
return clf.score(X_test, y_test)
# 定义遗传算法参数
pop_size = 50 # 种群大小
n_generations = 100 # 迭代次数
mutation_rate = 0.1 # 变异率
# 初始化种群
population = []
for i in range(pop_size):
C = random.uniform(0.1, 10)
gamma = random.uniform(0.1, 10)
population.append((C, gamma))
# 迭代遗传算法
for i in range(n_generations):
# 计算种群适应度
fitness = [svm_fitness(p) for p in population]
# 选择父代
parents = []
for j in range(pop_size):
parent1 = population[np.random.choice(range(pop_size), p=fitness/np.sum(fitness))]
parent2 = population[np.random.choice(range(pop_size), p=fitness/np.sum(fitness))]
parents.append((parent1, parent2))
# 交叉产生子代
offspring = []
for parent1, parent2 in parents:
child = (parent1[0], parent2[1])
offspring.append(child)
# 变异
for i in range(pop_size):
if random.random() < mutation_rate:
C = random.uniform(0.1, 10)
gamma = random.uniform(0.1, 10)
offspring[i] = (C, gamma)
# 更新种群
population = offspring
# 选择最优个体
fitness = [svm_fitness(p) for p in population]
best_idx = np.argmax(fitness)
best_params = population[best_idx]
# 使用最优参数构建SVM分类器
clf = SVC(C=best_params[0], kernel='rbf', gamma=best_params[1])
clf.fit(X_train, y_train)
# 进行预测
print(clf.predict([[5.1, 3.5, 1.4, 0.2]])) # 输出0
```
在这个示例中,我们使用遗传算法来优化SVM分类器的参数。适应度函数svm_fitness接受两个参数C和gamma,这两个参数分别对应SVM分类器的惩罚系数和高斯核参数。在遗传算法中,我们初始化一个种群,然后进行多次迭代,每次迭代都选择父代、交叉、变异,最后选择适应度最高的个体作为最优解。最后,我们使用训练好的分类器来进行预测。
阅读全文