八、AdaBoost算法

105 阅读1分钟

##载入相关模块

import numpy as np

import pandas as pd

from sklearn.datasets import load_iris

from sklearn.model_selection import train_test_split

from collections import Counter

##载入数据

iris = load_iris()

df = pd.DataFrame(iris.data, columns=iris.feature_names)

df['label'] = iris.target

df.columns = ['sepal length', 'sepal width', 'petal length', 'petal width', 'label']

##提取特征和样品

#取前面100个数,第一列、第二列和最后一列

data = np.array(df.iloc[:100, [0, 1, -1]])

#最后一个特征作为标签,其他的作为特征

X, y = data[:,:-1], data[:,-1]

#取80%作为训练,20%作为测试

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)

载入sklearn中的支持向量分类器模块

from sklearn.ensemble import AdaBoostClassifier

##模型训练

clf = AdaBoostClassifier(n_estimators=100, learning_rate=0.5)

clf.fit(X_train, y_train)

验证算法精度

clf.score(X_test, y_test)