python实现线性回归和逻辑回归

线性回归模型

每个训练集x为行向量

import matplotlib.pyplot as plt
import numpy as np

x = np.array([[1, 1],
              [1, 2],
              [1, 3],
              [1, 4],
              [1, 5]], dtype=float)
y = np.array([1., 2.1, 3., 4.1, 5.], dtype=float)
a = 0.03  # 学习率
f_num = len(x[0]) - 1  # 特征数
t_num = len(x)  # 训练集大小
w = np.array([0 for i in range(f_num + 1)], dtype=float)

while True:
    # 将旧的参数赋值给temp_arr
    temp_arr = w.copy()
    w = w - a * (x.T @ (x @ w - y)) / t_num
    res = abs(temp_arr - w) < 0.00001
    if res.all():
        break
print('weight:'+str(w))
#绘制
plt.plot(x[:,1],y,'b-o')
x1 = np.linspace(0,6,100)
plt.plot(x1,w[0]+w[1]*x1)
# 测试
test = np.array([1, 6], dtype=float)
res_test = w @ test
print('测试结果:'+str(res_test))
plt.plot(test[1],res_test,'r-o')
plt.show()

逻辑回归模型
每个训练集x为列向量,注意与上方不同

import numpy as np

x = np.array([[1, 1, 1],
              [1.1, 1.2, 2.5]], dtype=float).T
y = np.array([1, 1, 0], dtype=int)
a = 0.3  # 学习率
f_num = len(x[0]) - 1  # 特征数
t_num = len(x)  # 训练集大小
w = np.array(np.random.randint(0, 1, 2), dtype=float)

while True:
    # 将旧的参数赋值给temp_arr
    temp_arr = w.copy()
    w = w - a * (x.T @ (1 / (1 + np.exp(-(x @ w))) - y)) / t_num
    res = abs(temp_arr - w) < 0.00001
    if res.all():
        break
print('权值:'+w)
print('预测结果:'+1 / (1 + np.exp(-(w[0] + w[1] * 1.1))))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值