文章目录
问题引入
对已知年龄x1,年收入x2,得到是否买车y。其中是否买车1表示是,0表示1
数据格式
年龄 | 年收入 | 是否买车 |
---|---|---|
20 | 3 | 0 |
23 | 7 | 1 |
31 | 10 | 1 |
42 | 13 | 1 |
50 | 7 | 0 |
60 | 5 | 0 |
28 | 8 | ?(要预测的) |
解决方法
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