机器学习之logistic回归

参考资料:

点击打开链接

不想写解释了,以后再补。

我的参数矩阵跟别人的不太一样,代码:

import numpy as np
import matplotlib.pyplot as plt


def gradient_descent(x, y, w, col, alpha=10,times=100,eps=1e-8):  # 调参有点难受
    for i in range(times):
        a = 1/(1+np.exp(-w.T*x))
        dJ_dw = 1/col*x*(a.T-y.T)
        w -= alpha*dJ_dw
        if np.sum(np.abs(dJ_dw))<eps:
            print('第{}次迭代后的结果'.format(i))
            break

def recover_w(x_mean, x_std, w):
    std = np.append(np.ones((1, 1)), x_std, axis=0)
    mean = np.append(np.zeros((1, 1)), x_mean, axis=0)
    w = np.array(w)
    w /= std
    w[0][0] -= np.sum(mean*w)
    return w

x = np.loadtxt('ex4x.dat')
y = np.loadtxt('ex4y.dat')
x_mean = np.mean(x,0)
x_std = np.std(x,0)
x = (x-x_mean)/x_std
x=x.T
row,col=x.shape
b = np.ones((1, col))
x = np.append(b, x, axis=0)
y.resize((1, 80))
w = np.mat(np.zeros((row+1, 1)))
x = np.mat(x)
y = np.mat(y)
gradient_descent(x, y, w, col)
x_mean = x_mean.T
x_std = x_std.T
x_mean.resize((row, 1))
x_std.resize((row, 1))
w = recover_w(x_mean, x_std, w)
print(w)

输出:

第23次迭代后的结果
[[-16.37874363]
 [  0.14834078]
 [  0.15890845]]

完全没想到不归一化,完全收敛不了,应该是指数函数计算机算的误差太大了,归一化之后还要恢复系数,写完之后差点忘了,导致还以为收敛之后结果不对。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值