import matplotlib as mpl
import matplotlib.pyplot as plt #绘图库
import numpy as np #科学计数库
from sklearn.linear_model import LogisticRegression#导入逻辑回归库
from sklearn.model_selection import train_test_split #样本分类
from sklearn import preprocessing #归一化库
X = np.array(((59, 2, 43.4, 2, 1), (36, 1, 57.2, 1, 1), (61, 2, 190.0, 2, 1), (58, 3, 128.0, 4, 3), (55, 3, 80.0, 3, 4),
(61, 1, 94.4, 2, 1), (38, 1, 76.0, 1, 1), (42, 1, 240.0, 3, 2), (50, 1, 74.0, 1, 1), (58, 3, 68.6, 2, 2),
(68, 3, 132.8, 4, 2), (25, 2, 94.6, 4, 3), (52, 1, 56.0, 1, 1), (31, 1, 47.8, 2, 1), (36, 3, 31.6, 3, 1),
(42, 1, 66.2, 2, 1)))
Y = np.array([0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0])
X = preprocessing.scale(X)
x_train,x_test,y_train,y_test=train_test_split(X,Y,train_size=0.6)#训练集与测试集分类
#构建逻辑回归模型
#penalty:str类型,正则化项的选择。正则化主要有两种:l1和l2,默认为l2正则化。
#dual:通常为False;求解对偶形式,只有在penalty='l2' 且solver='liblinear' 时有对偶形式;
#tol:停止求解误差的标准,默认1e-4
#C:正则化系数λ的倒数; 必须是大于0的浮点数。 与SVM一样,值越小正则化越强,通常默认为1
#fit_intercept:是否存在截距
#solver :‘newton-cg’,‘lbfgs’,‘liblinear’,‘sag’,'saga',default:liblinear
#liblinear:使用了坐标轴下降法来迭代优化损失函数。
#lbfgs:利用损失函数二阶导数矩阵即海森矩阵来迭代优化损失函数。
#newton-cg:也是牛顿法家族的一种,利用损失函数二阶导数矩阵即海森矩阵来迭代优化损失函数。
#sag:随机平均梯度下降,是梯度下降法的变种,和普通梯度下降法的区别是每次迭代仅仅用一部分的样本来计算梯度,适合于样本数据多的时候。
#saga:线性收敛的随机优化算法。
#max_iter:迭代器
LR_model = LogisticRegression(penalty='l2',dual=False,tol=1e-4,C=1,fit_intercept=True,solver='liblinear',max_iter=10000)
LR_model.fit(x_train,y_train)
#系数
w=LR_model.coef_
b = LR_model.intercept_
#预测类别
cla = LR_model.predict(x_test)
print(cla)
#预测分类概率
P = LR_model.predict_proba(x_test)
print(P) #输出两列代表:每一种类别所占概率
#精度
Predict = LR_model.score(x_test,y_test)
print(Predict)
[0 1 0 0 0 0 0]
[[0.91542804 0.08457196]
[0.12977647 0.87022353]
[0.83142841 0.16857159]
[0.51653282 0.48346718]
[0.54954224 0.45045776]
[0.5153987 0.4846013 ]
[0.8322549 0.1677451 ]]
0.7142857142857143