概念及应用:
logistic回归主要用于分类问题中,遇到k分类问题时则转化为k个二分类问题即可。
logistic回归是将logit曲线套用在解释变量线性组合上,利用极大似然法进行参数估计,将似然函数(二项分布交叉熵)作为目标函数,利用最优化方法(牛顿法、梯度下降法)进行求解。
python实现
数据载入及切分
from sklearn import datasets
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]
xtrain,xtest,ytrain,ytest=train_test_split(
X, y, test_size=0.3, random_state=42)
中间函数准备
tip:由于exp(x)呈现指数级增长,易导致float溢出,可以对x范围进行控制防止溢出。
def sigmoid(z):
# #防止溢出在RuntimeWarning: overflow encountered in exp
return 1 / (1.0 + np.exp(-np.clip(z,-100,10000)))
def f(x,w):#x为n*k w为k*1
return sigmoid(x@w )
def predict(x,w):
return np.round(f(x, w))
利用随机梯度下降法进行求解
#损失函数为两个伯努利分布的交叉熵由极大似然估计进行推导
def cross_entropy_loss(y_pred, y_label):
cross_loss=-np.dot(y_label,np.log(y_pred))-np.dot(np.log(1-y_label),1-y_pred)
return cross_loss
def gradient(x, y, w):
y_pred=predict(x,w)
w_grad=np.matmul(x.T,y_pred-y_label)
return w_grad
#随机梯度下降进行迭代
def training(x,y_label,alpha):
# x=x.reset_index(drop=True)
# y_label=y_label.reset_index(drop=True)
dim=x.shape[1]
w = np.random.rand(dim, 1)
for i in range(1000):
index=np.random.randint(0,len(y_label)-1)
# y_pred=f(np.array(x.iloc[index,:],ndmin=2),w)
# gradient=np.array(x.iloc[index,:],ndmin=2).T@(y_pred-y_label.iloc[index])
y_pred=f(np.array(x[index,:],ndmin=2),w)
gradient=np.array(x[index,:],ndmin=2).T@(y_pred-y_label[index])
w-=alpha*gradient
return w
预测
w=training(xtrain,ytrain,0.001)
y_train_pred=predict(xtrain,w)
y_test_pred=predict(xtest,w)
效果评估
from sklearn.metrics import classification_report,confusion_matrix
print(classification_report(ytrain, y_train_pred))
print(classification_report(ytest, y_test_pred))
print(confusion_matrix(ytrain, y_train_pred))
print(confusion_matrix(ytest, y_test_pred))
输出结果:
precision recall f1-score support
0 1.00 1.00 1.00 33
1 1.00 1.00 1.00 37
accuracy 1.00 70
macro avg 1.00 1.00 1.00 70
weighted avg 1.00 1.00 1.00 70
precision recall f1-score support
0 1.00 1.00 1.00 17
1 1.00 1.00 1.00 13
accuracy 1.00 30
macro avg 1.00 1.00 1.00 30
weighted avg 1.00 1.00 1.00 30
[[33 0]
[ 0 37]]
[[17 0]
[ 0 13]]