P r e s e n t e d b y R . G . Presented\ by\ R.G. Presented by R.G.
写在前面:
最近在上《机器学习与内容安全》的课程,老师布置了第一次实验内容,看了一下,大致应该是吴恩达的东西。由于疫情在家(这事得从一直🦇说起。,。kidding),网络不是很好,所以没法安装matlab,而老师给的参考代码是matlab的(感觉应该是吴恩达课程里面的,不过我没去搜),再加上我一直觉得matlab有点笨重然后启动有点慢>_<,因此呢,我打算用伟大的蟒蛇语言(手动滑稽)重写一下参考代码,并加上了一些注释和数学推导。有需要的童鞋可以看看这篇文章,写得可能不算太好,但是希望点个赞给点鼓励,哈哈哈。盗用啊吗粽的金桔(金句),点赞再看,养成习惯~
题目要求:
python重现
import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
import math
bar = '-'*50
set_X = pd.read_table('./q1x.dat', header=None, delim_whitespace = True)
set_X.head()
0 | 1 | |
---|---|---|
0 | 1.343250 | -1.331148 |
1 | 1.820553 | -0.634668 |
2 | 0.986321 | -1.888576 |
3 | 1.944373 | -1.635452 |
4 | 0.976734 | -1.353315 |
plt.plot(set_X[0], set_X[1], 'b+') # 大致画一下特征分布
plt.title('Data distribution of q1x')
plt.xlabel('feature 0')
plt.ylabel('feature 1')
vec_y = pd.read_csv('./q1y.dat',header=None)
vec_y.head()
0 | |
---|---|
0 | 0.0 |
1 | 0.0 |
2 | 0.0 |
3 | 0.0 |
4 | 0.0 |
vec_y[0].value_counts() # 统计一下 0 1 标签个数
0.0 50
1.0 49
Name: 0, dtype: int64
# 加入 标签 区分数据类别
plt.plot(set_X[0][vec_y[0] == 0], set_X[1][vec_y[0] == 0], 'r+', label="y=0")
plt.plot(set_X[0][vec_y[0] == 1], set_X[1][vec_y[0]==1],'b*', label="y=1")
plt.legend(loc="best")
plt.title('Data distribution of q1x')
plt.xlabel('feature 0')
plt.ylabel('feature 1')
plt.show()
def sigmod(x):
return 1/(1+np.exp(-x))
def logistic_grad_ascent(feature_setX, label_sety, alpha=0.0001, max_iters=10):
''' 逻辑回归-梯度上升法
利用梯度上升算法,解使最大似然函数ll 取最大值的参数向量theta_list
feature_setX: 特征数据集
label_sety: 标签数据集
alpha: learning rate, 学习率/步长
max_iters: 迭代次数
'''
theta_list = np.zeros(feature_setX.ndim+1)
theta_list = np.mat(theta_list).T
feature_setX.insert(0,'x0',np.ones(feature_setX.shape[0])) # 解释见下述cell
ll = []
for i in range(max_iters):
hx =sigmod(feature_setX.dot(theta_list)) # 计算hx = g()
theta_list += alpha * feature_setX.T.dot(label_sety - hx) # 解释见下述cell
ll.append(np.sum( label_sety * np.log(hx) + (1 - label_sety) * np.log(1 - hx) ))
return theta_list,ll # 返回最终求出的参数值list,以及每一次迭代的最大似然函数值list