当前位置:网站首页>机器学习基础-集成学习-13
机器学习基础-集成学习-13
2022-07-28 11:51:00 【gemoumou】
集成学习Ensemble Learning






bagging
# 导入算法包以及数据集
from sklearn import neighbors
from sklearn import datasets
from sklearn.ensemble import BaggingClassifier
from sklearn import tree
from sklearn.model_selection import train_test_split
import numpy as np
import matplotlib.pyplot as plt
iris = datasets.load_iris()
x_data = iris.data[:,:2]
y_data = iris.target
x_train,x_test,y_train,y_test = train_test_split(x_data, y_data)
knn = neighbors.KNeighborsClassifier()
knn.fit(x_train, y_train)

def plot(model):
# 获取数据值所在的范围
x_min, x_max = x_data[:, 0].min() - 1, x_data[:, 0].max() + 1
y_min, y_max = x_data[:, 1].min() - 1, x_data[:, 1].max() + 1
# 生成网格矩阵
xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.02),
np.arange(y_min, y_max, 0.02))
z = model.predict(np.c_[xx.ravel(), yy.ravel()])# ravel与flatten类似,多维数据转一维。flatten不会改变原始数据,ravel会改变原始数据
z = z.reshape(xx.shape)
# 等高线图
cs = plt.contourf(xx, yy, z)
# 画图
plot(knn)
# 样本散点图
plt.scatter(x_data[:, 0], x_data[:, 1], c=y_data)
plt.show()
# 准确率
knn.score(x_test, y_test)

dtree = tree.DecisionTreeClassifier()
dtree.fit(x_train, y_train)

# 画图
plot(dtree)
# 样本散点图
plt.scatter(x_data[:, 0], x_data[:, 1], c=y_data)
plt.show()
# 准确率
dtree.score(x_test, y_test)

bagging_knn = BaggingClassifier(knn, n_estimators=100)
# 输入数据建立模型
bagging_knn.fit(x_train, y_train)
plot(bagging_knn)
# 样本散点图
plt.scatter(x_data[:, 0], x_data[:, 1], c=y_data)
plt.show()
bagging_knn.score(x_test, y_test)

bagging_tree = BaggingClassifier(dtree, n_estimators=100)
# 输入数据建立模型
bagging_tree.fit(x_train, y_train)
plot(bagging_tree)
# 样本散点图
plt.scatter(x_data[:, 0], x_data[:, 1], c=y_data)
plt.show()
bagging_tree.score(x_test, y_test)

随机森林(Random Forest)


from sklearn import tree
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
import numpy as np
import matplotlib.pyplot as plt
# 载入数据
data = np.genfromtxt("LR-testSet2.txt", delimiter=",")
x_data = data[:,:-1]
y_data = data[:,-1]
plt.scatter(x_data[:,0],x_data[:,1],c=y_data)
plt.show()

x_train,x_test,y_train,y_test = train_test_split(x_data, y_data, test_size = 0.5)
def plot(model):
# 获取数据值所在的范围
x_min, x_max = x_data[:, 0].min() - 1, x_data[:, 0].max() + 1
y_min, y_max = x_data[:, 1].min() - 1, x_data[:, 1].max() + 1
# 生成网格矩阵
xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.02),
np.arange(y_min, y_max, 0.02))
z = model.predict(np.c_[xx.ravel(), yy.ravel()])# ravel与flatten类似,多维数据转一维。flatten不会改变原始数据,ravel会改变原始数据
z = z.reshape(xx.shape)
# 等高线图
cs = plt.contourf(xx, yy, z)
# 样本散点图
plt.scatter(x_test[:, 0], x_test[:, 1], c=y_test)
plt.show()
dtree = tree.DecisionTreeClassifier()
dtree.fit(x_train, y_train)
plot(dtree)
dtree.score(x_test, y_test)

RF = RandomForestClassifier(n_estimators=50)
RF.fit(x_train, y_train)
plot(RF)
RF.score(x_test, y_test)

boosting







import numpy as np
import matplotlib.pyplot as plt
from sklearn import tree
from sklearn.ensemble import AdaBoostClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.datasets import make_gaussian_quantiles
from sklearn.metrics import classification_report
# 生成2维正态分布,生成的数据按分位数分为两类,500个样本,2个样本特征
x1, y1 = make_gaussian_quantiles(n_samples=500, n_features=2,n_classes=2)
# 生成2维正态分布,生成的数据按分位数分为两类,400个样本,2个样本特征均值都为3
x2, y2 = make_gaussian_quantiles(mean=(3, 3), n_samples=500, n_features=2, n_classes=2)
# 将两组数据合成一组数据
x_data = np.concatenate((x1, x2))
y_data = np.concatenate((y1, - y2 + 1))
plt.scatter(x_data[:, 0], x_data[:, 1], c=y_data)
plt.show()

# 决策树模型
model = tree.DecisionTreeClassifier(max_depth=3)
# 输入数据建立模型
model.fit(x_data, y_data)
# 获取数据值所在的范围
x_min, x_max = x_data[:, 0].min() - 1, x_data[:, 0].max() + 1
y_min, y_max = x_data[:, 1].min() - 1, x_data[:, 1].max() + 1
# 生成网格矩阵
xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.02),
np.arange(y_min, y_max, 0.02))
z = model.predict(np.c_[xx.ravel(), yy.ravel()])# ravel与flatten类似,多维数据转一维。flatten不会改变原始数据,ravel会改变原始数据
z = z.reshape(xx.shape)
# 等高线图
cs = plt.contourf(xx, yy, z)
# 样本散点图
plt.scatter(x_data[:, 0], x_data[:, 1], c=y_data)
plt.show()

# 模型准确率
model.score(x_data,y_data)

# AdaBoost模型
model = AdaBoostClassifier(DecisionTreeClassifier(max_depth=3),n_estimators=10)
# 训练模型
model.fit(x_data, y_data)
# 获取数据值所在的范围
x_min, x_max = x_data[:, 0].min() - 1, x_data[:, 0].max() + 1
y_min, y_max = x_data[:, 1].min() - 1, x_data[:, 1].max() + 1
# 生成网格矩阵
xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.02),
np.arange(y_min, y_max, 0.02))
# 获取预测值
z = model.predict(np.c_[xx.ravel(), yy.ravel()])
z = z.reshape(xx.shape)
# 等高线图
cs = plt.contourf(xx, yy, z)
# 样本散点图
plt.scatter(x_data[:, 0], x_data[:, 1], c=y_data)
plt.show()

Stacking


from sklearn import datasets
from sklearn import model_selection
from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import KNeighborsClassifier
from sklearn.tree import DecisionTreeClassifier
from mlxtend.classifier import StackingClassifier # pip install mlxtend
import numpy as np
# 载入数据集
iris = datasets.load_iris()
# 只要第1,2列的特征
x_data, y_data = iris.data[:, 1:3], iris.target
# 定义三个不同的分类器
clf1 = KNeighborsClassifier(n_neighbors=1)
clf2 = DecisionTreeClassifier()
clf3 = LogisticRegression()
# 定义一个次级分类器
lr = LogisticRegression()
sclf = StackingClassifier(classifiers=[clf1, clf2, clf3],
meta_classifier=lr)
for clf,label in zip([clf1, clf2, clf3, sclf],
['KNN','Decision Tree','LogisticRegression','StackingClassifier']):
scores = model_selection.cross_val_score(clf, x_data, y_data, cv=3, scoring='accuracy')
print("Accuracy: %0.2f [%s]" % (scores.mean(), label))


Voting
from sklearn import datasets
from sklearn import model_selection
from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import KNeighborsClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import VotingClassifier
import numpy as np
# 载入数据集
iris = datasets.load_iris()
# 只要第1,2列的特征
x_data, y_data = iris.data[:, 1:3], iris.target
# 定义三个不同的分类器
clf1 = KNeighborsClassifier(n_neighbors=1)
clf2 = DecisionTreeClassifier()
clf3 = LogisticRegression()
sclf = VotingClassifier([('knn',clf1),('dtree',clf2), ('lr',clf3)])
for clf, label in zip([clf1, clf2, clf3, sclf],
['KNN','Decision Tree','LogisticRegression','VotingClassifier']):
scores = model_selection.cross_val_score(clf, x_data, y_data, cv=3, scoring='accuracy')
print("Accuracy: %0.2f [%s]" % (scores.mean(), label))

泰坦尼克号船员获救预测项目

import pandas
titanic = pandas.read_csv("titanic_train.csv")
titanic

# 空余的age填充整体age的中值
titanic["Age"] = titanic["Age"].fillna(titanic["Age"].median())
print(titanic.describe())


print(titanic["Sex"].unique())
# 把male变成0,把female变成1
titanic.loc[titanic["Sex"] == "male", "Sex"] = 0
titanic.loc[titanic["Sex"] == "female", "Sex"] = 1


print(titanic["Embarked"].unique())
# 数据填充
titanic["Embarked"] = titanic["Embarked"].fillna('S')
# 把类别变成数字
titanic.loc[titanic["Embarked"] == "S", "Embarked"] = 0
titanic.loc[titanic["Embarked"] == "C", "Embarked"] = 1
titanic.loc[titanic["Embarked"] == "Q", "Embarked"] = 2


from sklearn.preprocessing import StandardScaler
# 选定特征
predictors = ["Pclass", "Sex", "Age", "SibSp", "Parch", "Fare", "Embarked"]
x_data = titanic[predictors]
y_data = titanic["Survived"]
# 数据标准化
scaler = StandardScaler()
x_data = scaler.fit_transform(x_data)
逻辑回归
from sklearn import cross_validation
from sklearn.linear_model import LogisticRegression
# 逻辑回归模型
LR = LogisticRegression()
# 计算交叉验证的误差
scores = cross_validation.cross_val_score(LR, x_data, y_data, cv=3)
# 求平均
print(scores.mean())

神经网络
from sklearn.neural_network import MLPClassifier
# 建模
mlp = MLPClassifier(hidden_layer_sizes=(20,10),max_iter=1000)
# 计算交叉验证的误差
scores = cross_validation.cross_val_score(mlp, x_data, y_data, cv=3)
# 求平均
print(scores.mean())

KNN
from sklearn import neighbors
knn = neighbors.KNeighborsClassifier(21)
# 计算交叉验证的误差
scores = cross_validation.cross_val_score(knn, x_data, y_data, cv=3)
# 求平均
print(scores.mean())

决策树
from sklearn import tree
# 决策树模型
dtree = tree.DecisionTreeClassifier(max_depth=5, min_samples_split=4)
# 计算交叉验证的误差
scores = cross_validation.cross_val_score(dtree, x_data, y_data, cv=3)
# 求平均
print(scores.mean())

随机森林
# 随机森林
from sklearn.ensemble import RandomForestClassifier
RF1 = RandomForestClassifier(random_state=1, n_estimators=10, min_samples_split=2)
# 计算交叉验证的误差
scores = cross_validation.cross_val_score(RF1, x_data, y_data, cv=3)
# 求平均
print(scores.mean())

RF2 = RandomForestClassifier(n_estimators=100, min_samples_split=4)
# 计算交叉验证的误差
scores = cross_validation.cross_val_score(RF2, x_data, y_data, cv=3)
# 求平均
print(scores.mean())



边栏推荐
- Leetcode394 string decoding
- C# 结构使用
- Linear classifier (ccf20200901)
- 十三. 实战——常用依赖的作用
- Brief introduction to JS operator
- Minimally invasive electrophysiology has passed the registration: a listed enterprise with annual revenue of 190million minimally invasive mass production
- 04 pyechars 地理图表(示例代码+效果图)
- Fundamentals of machine learning - support vector machine svm-17
- GMT installation and use
- Can molecular modeling solve the data dilemma of AI pharmacy?
猜你喜欢

The openatom openharmony sub forum was successfully held, and ecological and industrial development entered a new journey

What if the right button of win11 start menu doesn't respond

单调栈Monotonic Stack

机器学习实战-集成学习-23
![[pictures and texts] detailed tutorial of one click reinstallation of win11 system](/img/cc/749fe4095fc5afb1fc2c65df43d06c.png)
[pictures and texts] detailed tutorial of one click reinstallation of win11 system

New Oriental's single quarter revenue was 524million US dollars, a year-on-year decrease of 56.8%, and 925 learning centers were reduced

IO流再回顾,深入理解序列化和反序列化

03 pyechars rectangular coordinate system chart (example code + effect drawing)
![[cute new problem solving] climb stairs](/img/a2/fd2f21c446562ba9f0359988d97efe.png)
[cute new problem solving] climb stairs
![[half understood] zero value copy](/img/5b/18082c1ea93f2e3bbf4920d73163fd.png)
[half understood] zero value copy
随机推荐
上位机和三菱FN2x通信实例
Machine learning practice - neural network-21
05 pyechars basic chart (example code + effect diagram)
SuperMap game engine license module division
Insufficient permission to pull server code through Jenkins and other precautions
20220728-Object类常用方法
Scala transformation, filtering, grouping, sorting
Markdown concise grammar manual
GMT installation and use
输入字符串,内有数字和非字符数组,例如A123x456将其中连续的数字作为一个整数,依次存放到一个数组中,如123放到a[0],456放到a[1],并输出a这些数
利用依赖包直接实现分页、SQL语句
机器学习基础-支持向量机 SVM-17
Vs code is not in its original position after being updated
What if win11 cannot recognize Ethernet
[half understood] zero value copy
04 pyechars geographic chart (example code + effect diagram)
快速读入
leetcode 376. Wiggle Subsequence
Library automatic reservation script
机器学习基础-贝叶斯分析-14