热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

python3二元LogisticsRegression回归分析(LogisticRegression)

纲要boss说增加项目平台分析方法:T检验(独立样本T检验)、线性回归、二元Logistics回归、因子分析、可靠性分析根本不懂,一脸懵逼状态,分析部确实有人才,反正我是一脸懵

 

纲要

boss说增加项目平台分析方法:

T检验(独立样本T检验)、线性回归、二元Logistics回归、因子分析、可靠性分析

根本不懂,一脸懵逼状态,分析部确实有人才,反正我是一脸懵

 

首先解释什么是二元Logistic回归分析吧

 二元Logistics回归 可以用来做分类,回归更多的是用于预测 

 

官方简介:

链接:https://pythonfordatascience.org/logistic-regression-python/

 

 

Logistic regression models are used to analyze the relationship between a dependent variable (DV) and independent variable(s) (IV) when the DV is dichotomous. The DV is the outcome variable, a.k.a. the predicted variable, and the IV(s) are the variables that are believed to have an influence on the outcome, a.k.a. predictor variables. If the model contains 1 IV, then it is a simple logistic regression model, and if the model contains 2+ IVs, then it is a multiple logistic regression model.

Assumptions for logistic regression models:

The DV is categorical (binary)
If there are more than 2 categories in terms of types of outcome, a multinomial logistic regression should be used
Independence of observations
Cannot be a repeated measures design, i.e. collecting outcomes at two different time points.
Independent variables are linearly related to the log odds
Absence of multicollinearity
Lack of outliers
原文

 

理解了什么是二元以后,开始找库

需要用的包

 这里需要特别说一下,第一天晚上我就用的logit,但结果不对,然后用机器学习搞,发现结果还不对,用spss比对的值

奇怪,最后没办法,只能抱大腿了,因为他们纠结Logit和Logistic的区别,然后有在群里问了下,有大佬给解惑了

而且也有下面文章给解惑

 

1. 是 statsmodels 的logit模块

2. 是 sklearn.linear_model 的 LogisticRegression模块

 

 

 先说第一种方法

首先借鉴文章链接:https://blog.csdn.net/zj360202/article/details/78688070?utm_source=blogxgwz0

解释的比较清楚,但是一定要注意一点就是,截距项,我就是在这个地方出的问题,因为我觉得不重要,就没加

#!/usr/bin/env
# -*- coding:utf-8 -*-

import pandas as pd
import statsmodels.api as sm
import pylab as pl
import numpy as np
from pandas import DataFrame, Series
from sklearn.cross_validation import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn import metrics
from collections import OrderedDict

data = {
    'y': [0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1, 1],
    'x': [i for i in range(1, 21)],
}

df = DataFrame(OrderedDict(data))


df["intercept"] = 1.0  # 截距项,很重要的呦,我就错在这里了


print(df)
print("==================")
print(len(df))
print(df.columns.values)

print(df[df.columns[1:]])

logit = sm.Logit(df['y'],  df[df.columns[1:]])
#
result = logit.fit()
#
res = result.summary2()

print(res)

 

 

 

 

 

这么写我觉得更好,因为上面那么写执行第二遍的时候总是报错:

statsmodels.tools.sm_exceptions.PerfectSeparationError: Perfect separation detected, results not available

 

我改成x, y变量自己是自己的,就莫名其妙的好了

 

 

    obj = TwoDimensionalLogisticRegressionModel()
    data_x = obj.SelectVariableSql( UserID, ProjID, QuesID, xVariable, DatabaseName, TableName, CasesCondition)
    data_y = obj.SelectVariableSql( UserID, ProjID, QuesID, yVariable, DatabaseName, TableName, CasesCondition)
    if len(data_x) != len(data_y):
        raise MyCustomError(retcode=4011)
    obj.close()

    df_X = DataFrame(OrderedDict(data_x))
    df_Y = DataFrame(OrderedDict(data_y))

    df_X["intercept"] = 1.0  # 截距项,很重要的呦,我就错在这里了
    logit = sm.Logit(df_Y, df_X)
    result = logit.fit()
    res = result.summary()

    data = [j for j in [i for i in str(res).split('\n')][-3].split(' ') if j != ''][1:]

    return data

 

允许二分数值虚拟变量的使用,修改后

obj = TwoDimensionalLogisticRegressionModel()
data_x = obj.SelectVariableSql( UserID, ProjID, QuesID, xVariable, DatabaseName, TableName, CasesCondition)
data_y = obj.SelectVariableSql( UserID, ProjID, QuesID, yVariable, DatabaseName, TableName, CasesCondition)
if len(data_x) != len(data_y):
    raise MyCustomError(retcode=4011)
obj.close()

df_X = DataFrame(data_x)
df_Y = DataFrame(data_y) # 因变量,01

df_X["intercept"] = 1.0  # 截距项,很重要的呦,我就错在这里了

YColumnList = list(df_Y[yVariable].values)
setYColumnList = list(set(YColumnList))
if len(setYColumnList) > 2 or len(setYColumnList) <2:
    raise MyCustomError(retcode=4015)
else:
    if len(setYColumnList) == 2 and [0,1] != [int(i) for i in setYColumnList]:
        newYcolumnsList = []
        for i in YColumnList:
            if i == setYColumnList[0]:
                newYcolumnsList.append(0)
            else:
                newYcolumnsList.append(1)
        df_Y = DataFrame({yVariable:newYcolumnsList})
logit = sm.Logit(df_Y, df_X)
result = logit.fit()
res = result.summary()

data = [j for j in [i for i in str(res).split('\n')][-3].split(' ') if j != '']

return data[1:]

 

 

 

 

 第二种方法,机器学习

参考链接:https://zhuanlan.zhihu.com/p/34217858

#!/usr/bin/env python
# -*- coding:utf-8 -*-

from collections import OrderedDict
import pandas as pd



examDict = {
    '学习时间': [i for i in range(1, 20)],
    '通过考试': [0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1]
}

examOrderDict = OrderedDict(examDict)
examDF = pd.DataFrame(examOrderDict)
# print(examDF.head())

exam_X = examDF.loc[:, "学习时间"]
exam_Y = examDF.loc[:, "通过考试"]

print(exam_X)
# print(exam_Y)

from sklearn.cross_validation import train_test_split

X_train,X_test,y_train, y_test = train_test_split(exam_X,exam_Y, train_size=0.8)

# print(X_train.values)
print(len(X_train.values))
X_train = X_train.values.reshape(-1, 1)
print(len(X_train))
print(X_train)
X_test = X_test.values.reshape(-1, 1)


from sklearn.linear_model import LogisticRegression

module_1 = LogisticRegression()
module_1.fit(X_train, y_train)

print("coef:", module_1.coef_)

front = module_1.score(X_test,y_test)
print(front)

print("coef:", module_1.coef_)
print("intercept_:", module_1.intercept_)

# 预测
pred1 = module_1.predict_proba(3)
print("预测概率[N/Y]", pred1)

pred2 = module_1.predict(5)
print(pred2)

 

 但是,机器学习的这个有问题,就是只抽取了15个值

 

statsmodels的库链接

Statsmodels:http://www.statsmodels.org/stable/index.html

 


推荐阅读
  • CSS3选择器的使用方法详解,提高Web开发效率和精准度
    本文详细介绍了CSS3新增的选择器方法,包括属性选择器的使用。通过CSS3选择器,可以提高Web开发的效率和精准度,使得查找元素更加方便和快捷。同时,本文还对属性选择器的各种用法进行了详细解释,并给出了相应的代码示例。通过学习本文,读者可以更好地掌握CSS3选择器的使用方法,提升自己的Web开发能力。 ... [详细]
  • android listview OnItemClickListener失效原因
    最近在做listview时发现OnItemClickListener失效的问题,经过查找发现是因为button的原因。不仅listitem中存在button会影响OnItemClickListener事件的失效,还会导致单击后listview每个item的背景改变,使得item中的所有有关焦点的事件都失效。本文给出了一个范例来说明这种情况,并提供了解决方法。 ... [详细]
  • Python瓦片图下载、合并、绘图、标记的代码示例
    本文提供了Python瓦片图下载、合并、绘图、标记的代码示例,包括下载代码、多线程下载、图像处理等功能。通过参考geoserver,使用PIL、cv2、numpy、gdal、osr等库实现了瓦片图的下载、合并、绘图和标记功能。代码示例详细介绍了各个功能的实现方法,供读者参考使用。 ... [详细]
  • 本文介绍了Oracle存储过程的基本语法和写法示例,同时还介绍了已命名的系统异常的产生原因。 ... [详细]
  • 使用圣杯布局模式实现网站首页的内容布局
    本文介绍了使用圣杯布局模式实现网站首页的内容布局的方法,包括HTML部分代码和实例。同时还提供了公司新闻、最新产品、关于我们、联系我们等页面的布局示例。商品展示区包括了车里子和农家生态土鸡蛋等产品的价格信息。 ... [详细]
  • 微软头条实习生分享深度学习自学指南
    本文介绍了一位微软头条实习生自学深度学习的经验分享,包括学习资源推荐、重要基础知识的学习要点等。作者强调了学好Python和数学基础的重要性,并提供了一些建议。 ... [详细]
  • 本文介绍了数据库的存储结构及其重要性,强调了关系数据库范例中将逻辑存储与物理存储分开的必要性。通过逻辑结构和物理结构的分离,可以实现对物理存储的重新组织和数据库的迁移,而应用程序不会察觉到任何更改。文章还展示了Oracle数据库的逻辑结构和物理结构,并介绍了表空间的概念和作用。 ... [详细]
  • 本文分享了一个关于在C#中使用异步代码的问题,作者在控制台中运行时代码正常工作,但在Windows窗体中却无法正常工作。作者尝试搜索局域网上的主机,但在窗体中计数器没有减少。文章提供了相关的代码和解决思路。 ... [详细]
  • Go Cobra命令行工具入门教程
    本文介绍了Go语言实现的命令行工具Cobra的基本概念、安装方法和入门实践。Cobra被广泛应用于各种项目中,如Kubernetes、Hugo和Github CLI等。通过使用Cobra,我们可以快速创建命令行工具,适用于写测试脚本和各种服务的Admin CLI。文章还通过一个简单的demo演示了Cobra的使用方法。 ... [详细]
  • 本文介绍了机器学习手册中关于日期和时区操作的重要性以及其在实际应用中的作用。文章以一个故事为背景,描述了学童们面对老先生的教导时的反应,以及上官如在这个过程中的表现。同时,文章也提到了顾慎为对上官如的恨意以及他们之间的矛盾源于早年的结局。最后,文章强调了日期和时区操作在机器学习中的重要性,并指出了其在实际应用中的作用和意义。 ... [详细]
  • 本文讨论了如何使用IF函数从基于有限输入列表的有限输出列表中获取输出,并提出了是否有更快/更有效的执行代码的方法。作者希望了解是否有办法缩短代码,并从自我开发的角度来看是否有更好的方法。提供的代码可以按原样工作,但作者想知道是否有更好的方法来执行这样的任务。 ... [详细]
  • 怎么在PHP项目中实现一个HTTP断点续传功能发布时间:2021-01-1916:26:06来源:亿速云阅读:96作者:Le ... [详细]
  • 本文介绍了Python爬虫技术基础篇面向对象高级编程(中)中的多重继承概念。通过继承,子类可以扩展父类的功能。文章以动物类层次的设计为例,讨论了按照不同分类方式设计类层次的复杂性和多重继承的优势。最后给出了哺乳动物和鸟类的设计示例,以及能跑、能飞、宠物类和非宠物类的增加对类数量的影响。 ... [详细]
  • 本文讨论了在手机移动端如何使用HTML5和JavaScript实现视频上传并压缩视频质量,或者降低手机摄像头拍摄质量的问题。作者指出HTML5和JavaScript无法直接压缩视频,只能通过将视频传送到服务器端由后端进行压缩。对于控制相机拍摄质量,只有使用JAVA编写Android客户端才能实现压缩。此外,作者还解释了在交作业时使用zip格式压缩包导致CSS文件和图片音乐丢失的原因,并提供了解决方法。最后,作者还介绍了一个用于处理图片的类,可以实现图片剪裁处理和生成缩略图的功能。 ... [详细]
  • 欢乐的票圈重构之旅——RecyclerView的头尾布局增加
    项目重构的Git地址:https:github.comrazerdpFriendCircletreemain-dev项目同步更新的文集:http:www.jianshu.comno ... [详细]
author-avatar
zhaoyan666777
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有