以下是遗传算法优化SVM参数的Python代码示例:
首先,需要导入所需的库和模块:
```python
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score
from deap import algorithms, base, creator, tools
```
然后,准备数据集和模型:
```python
# 加载数据集
data = np.loadtxt("data.txt", delimiter=",")
X = data[:, :-1]
y = data[:, -1]
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# 定义SVM模型
clf = SVC()
```
接着,定义适应度函数和个体编码方式:
```python
# 定义适应度函数
def evaluate(individual):
clf.C, clf.gamma = individual
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
return accuracy_score(y_test, y_pred),
# 定义个体编码方式
creator.create("FitnessMax", base.Fitness, weights=(1.0,))
creator.create("Individual", list, fitness=creator.FitnessMax)
toolbox = base.Toolbox()
toolbox.register("attr_float", np.random.uniform, 0, 10)
toolbox.register("individual", tools.initRepeat, creator.Individual, toolbox.attr_float, n=2)
toolbox.register("population", tools.initRepeat, list, toolbox.individual)
toolbox.register("evaluate", evaluate)
toolbox.register("mate", tools.cxBlend, alpha=0.5)
toolbox.register("mutate", tools.mutGaussian, mu=0, sigma=1, indpb=0.1)
toolbox.register("select", tools.selTournament, tournsize=3)
```
最后,使用遗传算法进行参数优化:
```python
# 设置参数
pop_size = 10
num_generations = 10
cx_prob = 0.5
mut_prob = 0.2
# 创建初始种群
pop = toolbox.population(n=pop_size)
# 运行遗传算法
for gen in range(num_generations):
offspring = algorithms.varAnd(pop, toolbox, cxpb=cx_prob, mutpb=mut_prob)
fits = toolbox.map(toolbox.evaluate, offspring)
for ind, fit in zip(offspring, fits):
ind.fitness.values = fit
pop = toolbox.select(offspring, k=len(pop))
# 输出最优解
best_ind = tools.selBest(pop, k=1)[0]
best_c, best_gamma = best_ind
print("Best parameters: C = {:.2f}, gamma = {:.2f}".format(best_c, best_gamma))
```
这个示例代码使用遗传算法对SVM的C和gamma参数进行优化,以最大化测试集上的准确率。在运行遗传算法之后,输出最优的参数值。