前言
逻辑回归是机器学习的一种分类模型,用于解决二分类问题。
一、逻辑回归介绍
机器学习的一种分类模型,用于解决分类问题。主要使用场景:广告点击率、是否为垃圾邮件、是否虚假账号等,主要解决二分类问题。逻辑回归的输入就是线性回归的输出。
二、逻辑回归的原理
1.激活函数
线性回归结果输入到sigmoid函数中,将结果值映射到[0-1]之间,默认阈值0.5,小于0.5属于一类,大于0.5属于另外一类。
sigmoid函数
g
(
θ
T
x
)
=
1
1
+
e
−
θ
T
x
.
g(θ^Tx) = \frac{1}{{1+e^{-θ^{T}x}}}\,.
g(θTx)=1+e−θTx1.
2.逻辑回归模型
1)对数似然损失函数
c o s t ( h θ ( x ) , y ) = { − l o g ( h θ ( x ) ) if y =1 − l o g ( 1 − h θ ( x ) ) if y =0 cost(h_θ(x),y) = \begin{cases} -log(h_θ(x)) & \text{if $y$ =1} \\[2ex] -log(1-h_θ(x)) & \text{if $y$ =0} \\ \end{cases} cost(hθ(x),y)=⎩ ⎨ ⎧−log(hθ(x))−log(1−hθ(x))if y =1if y =0
2)损失函数变形
c o s t ( h θ ( x ) , y ) = ∑ i = 1 m − y i l o g ( h θ ( x ) ) − ( 1 − y i ) l o g ( 1 − h θ ( x ) ) cost(h_θ(x),y)=\sum_{i=1}^m-y_ilog(h_θ(x))-(1-y_i)log(1-h_θ(x)) cost(hθ(x),y)=i=1∑m−yilog(hθ(x))−(1−yi)log(1−hθ(x))
3)函数曲线
4)损失计算
3.优化
使用梯度下降的算法,提升原本属于1类别的概率,降低原本属于0类别的概率
三、案例
代码如下:
#获取数据
names = ['Sample code number', 'Clump Thickness', 'Uniformity of Cell Size',
'Uniformity of Cell Shape', 'Marginal Adhesion', 'Single Epithelial Cell Size',
'Bare Nuclei', 'Bland Chromatin', 'Normal Nucleoli', 'Mitoses', 'Class']
data = pd.read_csv('E:/breast+cancer+wisconsin/breast-cancer-wisconsin.data',names=names)
print(data.head())
# 基本数据处理
# 缺失值处理
data = data.replace(to_replace='?', value=np.NaN)
data = data.dropna()
#取出特征值和目标值
data_x = data.iloc[:, 1:-1]
# print(data_x)
data_y = data['Class']
# print(data_y)
# 分割数据
x_train,x_test,y_train,y_test = train_test_split(data_x,data_y,random_state=2,test_size=0.2)
# 标准化
tranfer = StandardScaler()
x_train = tranfer.fit_transform(x_train)
x_test = tranfer.fit_transform(x_test)
# 逻辑回归
estimator = LogisticRegression()
estimator.fit(x_train,y_train)
# 预测
y_pre = estimator.predict(x_test)
print(y_pre)
score = estimator.score(x_test,y_test)
print(score)
总结
本文主要介绍了深度学习中逻辑回归的介绍与原理,并通过sklearn进行逻辑回归案例代码实现。