遗传算法优化支持向量机python代码
时间: 2023-08-11 19:19:53 浏览: 119
以下是一个简单的遗传算法优化支持向量机的python代码示例:
```python
import random
import numpy as np
from sklearn import svm
from sklearn.datasets import make_classification
# 生成数据集
X, y = make_classification(n_samples=1000, n_features=10, n_informative=5, n_redundant=0, random_state=1)
# 定义适应度函数,即SVM的准确率
def fitness(individual, X, y):
clf = svm.SVC(C=individual[0], kernel=individual[1], gamma=individual[2])
clf.fit(X, y)
accuracy = clf.score(X, y)
return accuracy
# 定义遗传算法
def genetic_algorithm(population_size, generations, mutation_rate, X, y):
# 初始化种群
population = []
for i in range(population_size):
individual = [random.uniform(0.1, 10), random.choice(['linear', 'rbf']), random.uniform(0.1, 1)]
population.append(individual)
# 进化
for generation in range(generations):
# 计算适应度
fitness_scores = []
for individual in population:
fitness_scores.append(fitness(individual, X, y))
# 选择
parents = []
for i in range(population_size):
parent1 = population[fitness_scores.index(max(fitness_scores))]
fitness_scores[fitness_scores.index(max(fitness_scores))] = -1
parent2 = population[fitness_scores.index(max(fitness_scores))]
fitness_scores[fitness_scores.index(max(fitness_scores))] = -1
parents.append([parent1, parent2])
# 交叉
offspring = []
for i in range(population_size):
child = []
for j in range(len(parents[i][0])):
if random.random() < 0.5:
child.append(parents[i][0][j])
else:
child.append(parents[i][1][j])
offspring.append(child)
# 变异
for i in range(population_size):
for j in range(len(offspring[i])):
if random.random() < mutation_rate:
if j == 0:
offspring[i][j] = random.uniform(0.1, 10)
elif j == 1:
offspring[i][j] = random.choice(['linear', 'rbf'])
else:
offspring[i][j] = random.uniform(0.1, 1)
# 更新种群
population = offspring
# 返回最优解
max_fitness = 0
for individual in population:
fitness_score = fitness(individual, X, y)
if fitness_score > max_fitness:
max_fitness = fitness_score
best_individual = individual
return best_individual
# 运行遗传算法
best_individual = genetic_algorithm(population_size=50, generations=100, mutation_rate=0.1, X=X, y=y)
# 输出最优解
print('Best individual:', best_individual)
```
此代码使用遗传算法来搜索SVM的最佳参数(C、kernel和gamma),以最大化SVM的准确率。它首先生成一个包含1000个样本和10个特征的分类数据集,然后定义适应度函数来计算SVM的准确率。接下来,它使用遗传算法来搜索最佳参数,其中种群大小为50,进化代数为100,变异率为0.1。最后,它输出找到的最佳参数。
阅读全文