sklearn中的感知机模型perceptron

from sklearn import  datasets
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import Perceptron
import  numpy as np

#加载iris数据
iris = datasets.load_iris()
x = iris.data[:,[2,3]]
y = iris.target
print(np.unique(y))

#train_test_split
#分离训练和测试数据,test_size 为分离比例,random_state是打乱顺序在进行分离,
#stratify 为保证测试和训练数据集中的三种类型的数据比例相同
x_train,x_test,y_train,y_test = train_test_split(x,y,test_size=0.3,random_state=1,
                                                 stratify=y)
#bincount
print("Labels counts in y: ", np.bincount(y))
print("Labels counts in y_train: ", np.bincount(y_train))
print("Labels counts in y_test: ", np.bincount(y_test))

sc = StandardScaler()
#计算平均值和标准差
sc.fit(x_train)
#利用平均值和标准差进行数据归一化
x_train_std = sc.transform(x_train)
x_test_std = sc.transform(x_test)


#train perceptron model
#构建对象。迭代,学习率,随机
ppn = Perceptron(n_iter=50,eta0=0.01,random_state=1)

#开始训练
ppn.fit(x_train_std,y_train)
#预测
y_pred = ppn.predict(x_test_std)
miss_calssified = (y_pred != y_test).sum()
print(miss_calssified)

from sklearn.metrics import accuracy_score
print('acc: %.2f'%accuracy_score(y_pred,y_test))

 

你可能感兴趣的:(ML)