回归问题中我们常用均方误差MSE作为损失函数 但是在分类问题中 使用sigmoid/softmx得到概率 配合MSE损失函数时 采用梯度下降法进行学习时 会出现模型一开始训练时 学习速率非常慢的情况 所以常采用交叉熵作为分类问题的损失函数。
关于交叉熵可以参考知乎上飞鱼大佬的文章:损失函数 交叉熵损失函数
LDA的基本思想 给定训练样例集 设法将样例投影到一条直线上 使得同类样例的投影点尽可能接近、异类样例的投影点中心尽可能远离。更简单的概括为一句话 就是“投影后类内方差最小 类间方差最大”。
逻辑回归一般不用于多分类问题 在多分类问题上效果不佳 但是LDA适合与多分类问题
#通用函数 import numpy as np from collections import Counter def sigmoid_fun(z): return 1/(1 np.exp(-z)) def cross_entropy(N,P,y): J np.sum(y*np.log(P) (1-y)*np.log(1-P))/N return J #逻辑回归类 class LR: w None def fit(self,X,y,alpha 0.01,accuracy 0.00001): self.w np.full((X.shape[1] 1,1),0.5) self.N X.shape[0] b np.ones(X.shape[0]) X np.column_stack((X,b)) y y.reshape(self.N,1) obj self.cost_func(w,X,y) new_obj float( inf ) while np.abs(new_obj-obj) accuracy: obj new_obj df y-sigmoid_fun(X.dot(w)) df df.T.dot(X).T self.w self.w-alpha*df new_obj self.cost_func(self.w,X,y) def cost_func(self,w,X,y): P sigmoid_fun(X.dot(w)) r cross_entropy(self.N,P,y) return r def predict(self,X): b np.ones(X.shape[0]) X np.column_stack((X,b)) predict X.dot(self.w) result [] for i in predict: if i 0.5: result.append(1) else: result.append(0) return result def score(self,X_test,y_test): y_predict self.predict(X_test) re (y_test y_predict) re1 Counter(re) a re1[True] / (re1[True] re1[False]) return a
#构建二分类数据集并调用 from sklearn.model_selection import train_test_split iris datasets.load_iris() X iris[ data ] y iris[ target ] X X[y! 2] y y[y! 2] X_train,X_test, y_train, y_test train_test_split(X,y) myLogstic LR() myLogstic.fit(X_train,y_train) myLogstic.score(X_test,y_test)



