卡方檢驗python程序_Python從零開始第二章(1)卡方檢驗(python)

如果我們想確定兩個獨立分類數據組的統計顯著性,會發生什么?這是卡方檢驗獨立性有用的地方。

Chi-Square檢驗

我們將在1994年查看人口普查數據。具體來說,我們對“性別和“每周工作時間”之間的關系感興趣。在我們的案例中,每個人只能有一個“性別”,且只有一個工作時間類別。為了這個例子,我們將使用pandas將數字列'每周小時'轉換為一個分類列。然后我們將'sex'和'hours_per_week_categories'分配給新的數據幀。# -*- coding: utf-8 -*-

"""

Created on Sun Feb 3 19:24:55 2019

@author: czh

"""

# In[*]

import matplotlib.pyplot as plt

import numpy as np

import math

import seaborn as sns

import pandas as pd

%matplotlib inline

import os

os.chdir('D:\\train')

# In[*]

cols = ['age', 'workclass', 'fnlwg', 'education', 'education-num',

'marital-status','occupation','relationship', 'race','sex',

'capital-gain', 'capital-loss', 'hours-per-week', 'native-country', 'income']

data = pd.read_csv('census.csv', names=cols,sep=', ')

# In[*]

#Create a column for work hour categories.

def process_hours(df):

cut_points = [0,9,19,29,39,49,1000]

label_names = ["0-9","10-19","20-29","30-39","40-49","50+"]

df["hours_per_week_categories"] = pd.cut(df["hours-per-week"],

cut_points,labels=label_names)

return df

# In[*]

data = process_hours(data)

workhour_by_sex = data[['sex', 'hours_per_week_categories']]

workhour_by_sex.head()sex hours_per_week_categories

0 Male 40-49

1 Male 10-19

2 Male 40-49

3 Male 40-49

4 Female 40-49

查看workhour_by_sex['sex'].value_counts()

Out[31]:

Male 21790

Female 10771

Name: sex, dtype: int64workhour_by_sex['hours_per_week_categories'].value_counts()

Out[33]:

40-49 18336

50+ 6462

30-39 3667

20-29 2392

10-19 1246

0-9 458

Name: hours_per_week_categories, dtype: int64原假設

回想一下,我們有興趣知道'sex'和'hours_per_week_categories'之間是否存在關系。 為此,我們必須使用卡方檢驗。 但首先,讓我們陳述我們的零假設和另類假設。H0:性別與每周工作小時數沒有統計學上的顯著關系.H0:性別與每周工作小時數之間沒有統計學上的顯著關系。

H1:性別和每周工作小時數之間存在統計學上的顯著關系.

下一步是將數據格式化為頻率計數表。 這稱為列聯表,我們可以通過在pandas中使用pd.crosstab()函數來實現。contingency_table = pd.crosstab(

workhour_by_sex['sex'],

workhour_by_sex['hours_per_week_categories'],

margins = True

)

contingency_table

Out[34]:

hours_per_week_categories 0-9 10-19 20-29 30-39 40-49 50+ All

sex

Female 235 671 1287 1914 5636 1028 10771

Male 223 575 1105 1753 12700 5434 21790

All 6462 1246 18336 3667 458 2392 32561

該表中的每個單元表示頻率計數。 例如,表格中“男性”行和“10 -19”列的交集將表示從我們的樣本數據集中每周工作10-19小時的男性人數。 “全部”行和“50 +”列的交叉點表示每周工作50小時以上的人員總數。# In[*]

#Assigns the frequency values

malecount = contingency_table.iloc[0][0:6].values

femalecount = contingency_table.iloc[1][0:6].values

#Plots the bar chart

fig = plt.figure(figsize=(10, 5))

sns.set(font_scale=1.8)

categories = ["0-9","10-19","20-29","30-39","40-49","50+"]

p1 = plt.bar(categories, malecount, 0.55, color='#d62728')

p2 = plt.bar(categories, femalecount, 0.55, bottom=malecount)

plt.legend((p2[0], p1[0]), ('Male', 'Female'))

plt.xlabel('Hours per Week Worked')

plt.ylabel('Count')

plt.show()

image.png

上圖顯示了人口普查中的樣本數據。如果性別與每周工作小時數之間確實沒有關系。然后,數據將顯示每個時間類別的“男性”和“女性”之間的均勻比率。例如,如果5%的女性工作50+小時,我們預計工作50小時以上的男性的百分比相同。

使用Scipy進行卡方檢驗

現在我們已經完成了所有計算,現在是時候尋找捷徑了。f_obs = np.array([contingency_table.iloc[0][0:6].values,

contingency_table.iloc[1][0:6].values])

f_obs

from scipy import stats

stats.chi2_contingency(f_obs)[0:3]

Out[38]: (2287.190943926107, 0.0, 5)

p值= ~0,自由度= 5。

結論

如果p值<0.05,我們可以拒絕零假設。 “性別”和“每周工作時間”之間肯定存在某種關系。 我們不知道這種關系是什么,但我們知道這兩個變量并不是彼此獨立的。

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/394701.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/394701.shtml
英文地址,請注明出處:http://en.pswp.cn/news/394701.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

當使用makemigrations時報錯No changes detected

在修改了models.py后&#xff0c;有些用戶會喜歡用python manage.py makemigrations生成對應的py代碼。 但有時執行python manage.py makemigrations命令&#xff08;也可能人比較皮&#xff0c;把migrations文件夾給刪了&#xff09;&#xff0c;會提示"No changes detec…

以下是ECMAScript 2016、2017和2018中所有新增功能的示例

by rajaraodv通過rajaraodv 以下是ECMAScript 2016、2017和2018中所有新增功能的示例 (Here are examples of everything new in ECMAScript 2016, 2017, and 2018) It’s hard to keep track of what’s new in JavaScript (ECMAScript). And it’s even harder to find usef…

win10下markdownpad2顯示問題

win10下解決html渲染問題 下載如下文件安裝后&#xff0c;親測可用 http://markdownpad.com/download/awesomium_v1.6.6_sdk_win.exe轉載于:https://www.cnblogs.com/liuqidongprogram/p/6049295.html

php原生函數應用

php常見基本的函數 一、字符串函數implode — 將一個一維數組的值轉化為字符串 lcfirst — 使一個字符串的第一個字符小寫 ltrim — 刪除字符串開頭的空白字符&#xff08;或其他字符&#xff09; rtrim — 刪除字符串末端的空白字符&#xff08;或者其他字符&#xff09; str_…

android 申請usb權限,USB 權限申請流程

USB android授權方式權限的控制分三塊&#xff1a;1:USB host端有個線程循環檢測系統是否USB設備插拔&#xff0c;如果有就找到申請權限的APP并調用起來2:APP運行后主動申請權限&#xff0c;也就是requestPermission()接口3:APP運行后直接打開USB設備&#xff0c;這時候USB hos…

ai人工智能程序_簡單解釋:一個AI程序如何掌握Go的古老游戲

ai人工智能程序by Aman Agarwal通過阿曼阿加瓦爾(Aman Agarwal) 簡單解釋&#xff1a;一個AI程序如何掌握Go的古老游戲 (Explained Simply: How an AI program mastered the ancient game of Go) This is about AlphaGo, Google DeepMind’s Go playing AI that shook the tec…

python提取hbase數據_詳解python操作hbase數據的方法介紹

配置 thrift python使用的包 thrift 個人使用的python 編譯器是pycharm community edition. 在工程中設置中&#xff0c;找到project interpreter&#xff0c; 在相應的工程下&#xff0c;找到package&#xff0c;然后選擇 “” 添加&#xff0c; 搜索 hbase-thrift (Python cl…

工作隨記

td自動換行:設置table 的 style"table-layout:fixed;" 然后設置td的 style"word-wrap:break-word;" white-space: nowrap 文本不換行 Intelidea創建好項目之后&#xff0c;右鍵新建Java class的時候發現沒有改選項,在Project Structure設置源碼目錄 DOM4j中…

qt for android 圖片可拉伸,qt實現九宮格布局,圖片拉伸

在實現qt播放時&#xff0c;調用的mplayer,由于采用的是自定義繪圖&#xff0c;用的是setAttribute(Qt::WA_TranslucentBackground);結果不能正常在上面顯示播放畫面&#xff0c;在默認皮膚下是沒有問題的&#xff0c;決定用九宮格圖片拉伸方式(效果如圖)附件圖片&#xff1a;文…

第一次作業-李純銳201731084433

作業屬于課程 https://edu.cnblogs.com/campus/xnsy/SoftwareEngineeringClass2 作業要求位置 https://edu.cnblogs.com/campus/xnsy/SoftwareEngineeringClass2/homework/2706 我在這個課程的目標是&#xff1a; 認真學習好軟件工程原理以及科學的軟件項目開發與管理方法&…

定點化_mif文件生成

clc; %全屏清零 clear all; %變量清零 N2^8; %設置ROM深度&#xff08;字變量&#xff09;的變量參數&#xff0c; s_p0:255; …

zeppelin連接數據源_使用開放源代碼合同(open-zeppelin)創建以太坊令牌

zeppelin連接數據源by Danny通過丹尼 使用開放源代碼合同(open-zeppelin)創建以太坊令牌 (Create an Ethereum token using open source contracts (open-zeppelin)) I want to show you that creating a best practice token is a simple process. To be honest, we are goin…

python不是內部文件_已安裝python,但是出現‘python’不是內部或外部命令,也不是可運行的程序或批處理文件。...

解決方法&#xff1a; 1.打開python shell查看你的python安裝路徑&#xff08;黃色標注&#xff09; >>> import sys >>> sys.path [, C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python37\\Lib\\idlelib, C:\\Users\\Administrator\\App…

使用canvas繪制時鐘

使用canvas繪制時鐘 什么使canvas呢&#xff1f;HTML5 <canvas> 元素用于圖形的繪制&#xff0c;通過腳本 (通常是JavaScript)來完成。<canvas> 標簽只是圖形容器&#xff0c;所以我們必須使用腳本來繪制圖形。通過它可以繪制路徑,盒、圓、字符以及添加圖像等等。 …

Visual Studio 2017創建XAML文件

Visual Studio 2017創建XAML文件在Visual Stuido 2015中&#xff0c;在已經創建好的項目中添加XAML文件&#xff0c;只要右擊項目&#xff0c;單擊“添加”|“新建項”命令&#xff0c;然后從“添加新項”對話框中&#xff0c;選擇“Cross-Platform”|“Forms Xaml Page”選項即…

android 安裝assets中的apk,如何安裝assets下apk,附源碼(原創)

publicstaticvoidInstall(Context ctx, String strLocalFile) {Intent intentInstallnewIntent();String apkPath"/data/data/"ctx.getPackageName()"/files";String apkName"yuan.apk";File filenewFile(apkPath, apkName);try{//assets下對于超…

FtpWebRequest.UsePassive屬性:設置FTP工作模式

默認值&#xff1a;true&#xff0c;被動模式 PASV&#xff08;被動&#xff09;方式的連接過程是&#xff1a;客戶端向服務器的FTP端口&#xff08;默認是21&#xff09;發送連接請求&#xff0c;服務器接受連接&#xff0c;建立一條命令鏈路。 當需要傳送數據時&#xff0c; …

angular面試題及答案_關于最流行的Angular問題的StackOverflow上的48個答案

angular面試題及答案by Shlomi Levi通過Shlomi Levi 關于最流行的Angular問題的StackOverflow上的48個答案 (48 answers on StackOverflow to the most popular Angular questions) I gathered the most common questions and answers from Stackoverflow. These questions we…

c++分治法求最大最小值實現_最優化計算與matlab實現(12)——非線性最小二乘優化問題——G-N法...

參考資料《精通MATLAB最優化計算&#xff08;第二版&#xff09;》編程工具Matlab 2019a目錄石中居士&#xff1a;最優化計算與Matlab實現——目錄?zhuanlan.zhihu.com非線性最小二乘優化問題非線性最小二乘優化也叫無約束極小平方和函數問題&#xff0c;它是如下無約束極小問…

win7 IIS7環境下部署PHP 7.0

最近在本機電腦win7 II7環境下部署PHP 7.0遇到一些問題&#xff0c;將之記錄下來 簡要步驟如下&#xff1a; 1、到php官網下載php&#xff0c;由于是IIS環境要下載非線程安全的版本&#xff0c;我下載的是7.0.13 2、解壓到本地文件目錄下 3、通過控制臺進入到php文件目錄&#…