sigmoid函数:处理二分类问题时,我们最后需要输出分类结果[0,1],而回归得到的是一个 (−∞,+∞) ( − ∞ , + ∞ ) 的数,因此我们需要使用sigmoid函数。函数定义: 其图像为: 通过输入的x而转变成(0,1)的数,此处x应该为预测的值,即 c0x0+c1x1+...+cnxn c 0 x 0 + c 1 x 1 + . . . + c n x n ,因此上式可转变为
f(x)=11+e−(c0x0+c1x1+...+cnxn) f ( x ) = 1 1 + e − ( c 0 x 0 + c 1 x 1 + . . . + c n x n ) 求解方法:我们的目的是求出参数c,这和线性回归的方法一样。可用梯度下降、牛顿法来进行计算。使用的是sklearn.naive_bayes,数据为约会数据(是连续的),数据和代码可前往:https://github.com/AugusXJ/scikit_learn/tree/master/LogisticRegression
from sklearn import metrics from sklearn.linear_model import LogisticRegression from sklearn.model_selection import train_test_split from sklearn.preprocessing import MinMaxScaler # 读取数据 X = [] Y = [] fr = open("datingTestSet.txt") index = 0 for line in fr.readlines(): line = line.strip() line = line.split('\t') X.append(line[:3]) Y.append(line[-1]) #归一化 scaler = MinMaxScaler() X = scaler.fit_transform(X) # 交叉分类 train_X,test_X, train_y, test_y = train_test_split(X, Y, test_size=0.2) # test_size:测试集比例20% # KNN模型,选择3个邻居 model = LogisticRegression() model.fit(train_X, train_y) print(model) expected = test_y predicted = model.predict(test_X) print(metrics.classification_report(expected, predicted)) # 输出分类信息 label = list(set(Y)) # 去重复,得到标签类别 print(metrics.confusion_matrix(expected, predicted, labels=label)) # 输出混淆矩阵信息