[2019计算机视觉]——贪心学院 学习笔记 【实验】2.1 使用逻辑函数 完成对购车的预测

问题引入

对已知年龄x1,年收入x2,得到是否买车y。其中是否买车1表示是,0表示1

数据格式

年龄年收入是否买车
2030
2371
31101
42131
5070
6050
288?(要预测的)

解决方法

1. 使用sklearn中的线性模型

sklearn是机器学习算法库
将上面的数据格式化输入

from sklearn import linear_model
X = [[20, 3],
    [23, 7],
    [31, 10],
    [42, 13],
    [50, 7],
    [60, 5]]
y = [0, 1, 1, 1, 0, 0]

2. 创建逻辑回归对象

lr = linear_model.LogisticRegression()

3. 训练回归模型

lr.fit(X, y)

运行结果:

LogisticRegression(C=1.0, class_weight=None, dual=False,
fit_intercept=True,
intercept_scaling=1, max_iter=100, multi_class=‘ovr’, n_jobs=1,
penalty=‘l2’, random_state=None, solver=‘liblinear’, tol=0.0001,
verbose=0, warm_start=False)

4. 使用训练好的模型进行预测

testX = [[28, 8]]
label = lr.predict(testX)
print("Logit预测类别:", label)

prob = lr.predict_proba(testX)
print("概率:", prob)

运行结果:

Logit预测类别: [1]
概率: [[0.14694811 0.85305189]]

5. 取出 θ \theta θ

theta_0 = lr.intercept_[0]
theta_1 = lr.coef_[0][0]
theta_2 = lr.coef_[0][1]

print('theta_0 = ', theta_0)
print('theta_1 = ', theta_1)
print('theta_2 = ', theta_2)

运行结果:

theta_0 = -0.041318375969934665
theta_1 = -0.19730001368291536
theta_2 = 0.9155574523479832

6. 验证 θ j 的 结 论 \theta_{j}的结论 θj

import math

testX = [[28, 8]]
prob = lr.predict_proba(testX)
ratio = prob[0][1]/prob[0][0]

testX = [[28, 9]]
prob_new = lr.predict_proba(testX)
ratio_new = prob_new[0][1]/prob_new[0][0]

ratio_of_ratio = ratio_new / ratio
print("ratio_of_ratio =", ratio_of_ratio)

theta_2_e =  math.exp(theta_2)
print("theta 2 e =", theta_2_e)

运行结果:

ratio_of_ratio = 2.498167473143896
  theta 2 e = 2.498167473143895

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值