将数据集按类别分为两两一组,用对数几率回归训练每一组的分类模型,将测试集依次按照三个模型进行分类,分得的类别票数加1,最终分类类别为得票数最多的类。
'''
用对数几率回归在iris数据集上一对一分类,用投票法确定最终类别
'''
import numpy as np
from sklearn import datasets
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
iris = datasets.load_iris()
#读取数据
sc = StandardScaler()
sc.fit(iris.data)
sdata = sc.transform(iris.data)
# 数据标准化,将特征值减去平均值再除以极差
def sigmoid(z):
return 1.0 / (1 + np.exp(-z))
b=np.ones((len(sdata),1))
sdata = np.c_[b,sdata]
data=np.zeros((3,100,5))
data[0]=sdata[:100]
data[1]=sdata[50:]
data[2][:50]=sdata[:50]
data[2][50:]=sdata[100:150]
labels=np.ones((100,1))
labels[:50]=0
labels=np.tile(labels,(3,1,1)) #数据集按类别标号分成两两一组
w=np.ones((3,5,1))
e=0.01
for n in range(3):
for i in range(10000):
y = sigmoid(data[n].dot(w[n]))
m = y-labels[n]
w[n] = w[n]-data[n].transpose().dot(m)*e #分别训练3个一对一分类模型
#print(np.argwhere(abs(m)>0.5))
vote=np.zeros((150,3))
m=np.array([[[0,1,0],[1,-1,0]],[[0,0,1],[0,1,-1]],[[0,0,1],[1,0,-1]]])
for i in range(3):
y = sigmoid(sdata.dot(w[i]))
l=np.argwhere(y<0.5)
vote=vote+m[i][0]
vote[l]+=m[i][1] #对所有数据用三个模型进行分类,每次分到的类别票数加一
lab=np.argmax(vote,axis=1) #选择得票数最多的类别
l=list(lab-iris.target).count(0)
print('数据集类别:')
print(iris.target)
print('预测类别:')
print(lab)
print('训练集精度:%.2f%%'%(l/1.5))
数据集类别:
[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2
2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
2 2]
预测类别:
[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2
2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2
2 2]
训练集精度:98.67%
本文介绍了一种使用对数几率回归在Iris数据集上进行一对一分类的方法,通过训练三组分类模型并采用投票法确定最终分类类别,实现了高精度的数据分类。
1万+

被折叠的 条评论
为什么被折叠?



