最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python如何檢驗樣本是否服從正態(tài)分布

 更新時間:2024年02月26日 09:36:18   作者:煙雨風渡  
這篇文章主要介紹了Python如何檢驗樣本是否服從正態(tài)分布問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教

在進行t檢驗、F檢驗之前,我們往往要求樣本大致服從正態(tài)分布,下面介紹兩種檢驗樣本是否服從正態(tài)分布的方法。

可視化

我們可以通過將樣本可視化,看一下樣本的概率密度是否是正態(tài)分布來初步判斷樣本是否服從正態(tài)分布。

代碼如下:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
 
# 使用pandas和numpy生成一組仿真數(shù)據(jù)
s = pd.DataFrame(np.random.randn(500),columns=['value'])
print(s.shape)      # (500, 1)
 
# 創(chuàng)建自定義圖像
fig = plt.figure(figsize=(10, 6))
# 創(chuàng)建子圖1
ax1 = fig.add_subplot(2,1,1)
# 繪制散點圖
ax1.scatter(s.index, s.values)
plt.grid()      # 添加網(wǎng)格
 
# 創(chuàng)建子圖2
ax2 = fig.add_subplot(2, 1, 2)
# 繪制直方圖
s.hist(bins=30,alpha=0.5,ax=ax2)
# 繪制密度圖
s.plot(kind='kde', secondary_y=True,ax=ax2)     # 使用雙坐標軸
plt.grid()      # 添加網(wǎng)格
 
# 顯示自定義圖像
plt.show()

可視化圖像如下:

從圖中可以初步看出生成的數(shù)據(jù)近似服從正態(tài)分布。

為了得到更具說服力的結果,我們可以使用統(tǒng)計檢驗的方法,這里使用的是.scipy.stats中的函數(shù)。

統(tǒng)計檢驗

1)kstest

scipy.stats.kstest函數(shù)可用于檢驗樣本是否服從正態(tài)、指數(shù)、伽馬等分布,函數(shù)的源代碼為:

def kstest(rvs, cdf, args=(), N=20, alternative='two-sided', mode='approx'):
    """
    Perform the Kolmogorov-Smirnov test for goodness of fit.
    This performs a test of the distribution F(x) of an observed
    random variable against a given distribution G(x). Under the null
    hypothesis the two distributions are identical, F(x)=G(x). The
    alternative hypothesis can be either 'two-sided' (default), 'less'
    or 'greater'. The KS test is only valid for continuous distributions.
    Parameters
    ----------
    rvs : str, array or callable
        If a string, it should be the name of a distribution in `scipy.stats`.
        If an array, it should be a 1-D array of observations of random
        variables.
        If a callable, it should be a function to generate random variables;
        it is required to have a keyword argument `size`.
    cdf : str or callable
        If a string, it should be the name of a distribution in `scipy.stats`.
        If `rvs` is a string then `cdf` can be False or the same as `rvs`.
        If a callable, that callable is used to calculate the cdf.
    args : tuple, sequence, optional
        Distribution parameters, used if `rvs` or `cdf` are strings.
    N : int, optional
        Sample size if `rvs` is string or callable.  Default is 20.
    alternative : {'two-sided', 'less','greater'}, optional
        Defines the alternative hypothesis (see explanation above).
        Default is 'two-sided'.
    mode : 'approx' (default) or 'asymp', optional
        Defines the distribution used for calculating the p-value.
          - 'approx' : use approximation to exact distribution of test statistic
          - 'asymp' : use asymptotic distribution of test statistic
    Returns
    -------
    statistic : float
        KS test statistic, either D, D+ or D-.
    pvalue :  float
        One-tailed or two-tailed p-value.

2)normaltest

scipy.stats.normaltest函數(shù)專門用于檢驗樣本是否服從正態(tài)分布,函數(shù)的源代碼為:

def normaltest(a, axis=0, nan_policy='propagate'):
    """
    Test whether a sample differs from a normal distribution.
    This function tests the null hypothesis that a sample comes
    from a normal distribution.  It is based on D'Agostino and
    Pearson's [1]_, [2]_ test that combines skew and kurtosis to
    produce an omnibus test of normality.
    Parameters
    ----------
    a : array_like
        The array containing the sample to be tested.
    axis : int or None, optional
        Axis along which to compute test. Default is 0. If None,
        compute over the whole array `a`.
    nan_policy : {'propagate', 'raise', 'omit'}, optional
        Defines how to handle when input contains nan. 'propagate' returns nan,
        'raise' throws an error, 'omit' performs the calculations ignoring nan
        values. Default is 'propagate'.
    Returns
    -------
    statistic : float or array
        ``s^2 + k^2``, where ``s`` is the z-score returned by `skewtest` and
        ``k`` is the z-score returned by `kurtosistest`.
    pvalue : float or array
       A 2-sided chi squared probability for the hypothesis test.

3)shapiro

scipy.stats.shapiro函數(shù)也是用于專門做正態(tài)檢驗的,函數(shù)的源代碼為:

def shapiro(x):
    """
    Perform the Shapiro-Wilk test for normality.
    The Shapiro-Wilk test tests the null hypothesis that the
    data was drawn from a normal distribution.
    Parameters
    ----------
    x : array_like
        Array of sample data.
    Returns
    -------
    W : float
        The test statistic.
    p-value : float
        The p-value for the hypothesis test.

下面我們使用第一部分生成的仿真數(shù)據(jù),用這三種統(tǒng)計檢驗函數(shù)檢驗生成的樣本是否服從正態(tài)分布(p > 0.05),代碼如下:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
 
# 使用pandas和numpy生成一組仿真數(shù)據(jù)
s = pd.DataFrame(np.random.randn(500),columns=['value'])
print(s.shape)      # (500, 1)
 
# 計算均值
u = s['value'].mean()
# 計算標準差
std = s['value'].std()  # 計算標準差
print('scipy.stats.kstest統(tǒng)計檢驗結果:----------------------------------------------------')
print(stats.kstest(s['value'], 'norm', (u, std)))
print('scipy.stats.normaltest統(tǒng)計檢驗結果:----------------------------------------------------')
print(stats.normaltest(s['value']))
print('scipy.stats.shapiro統(tǒng)計檢驗結果:----------------------------------------------------')
print(stats.shapiro(s['value']))

統(tǒng)計檢驗結果如下:

scipy.stats.kstest統(tǒng)計檢驗結果:----------------------------------------------------
KstestResult(statistic=0.01596290473494305, pvalue=0.9995623150120069)
scipy.stats.normaltest統(tǒng)計檢驗結果:----------------------------------------------------
NormaltestResult(statistic=0.5561685865675511, pvalue=0.7572329891688141)
scipy.stats.shapiro統(tǒng)計檢驗結果:----------------------------------------------------
(0.9985257983207703, 0.9540967345237732)

可以看到使用三種方法檢驗樣本是否服從正態(tài)分布的結果中p-value都大于0.05,說明服從原假設,即生成的仿真數(shù)據(jù)服從正態(tài)分布。

總結

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關文章

  • Python Flask 和 Django 的區(qū)別與適用場景示例分析

    Python Flask 和 Django 的區(qū)別與適用場景示例分析

    Flask和Django是兩個流行的Python Web框架,但設計哲學、功能和用法有很大區(qū)別,Flask是一個輕量級框架,簡單靈活,適合小型項目和快速原型開發(fā),本文給大家介紹Python Flask 和 Django 的區(qū)別與適用場景示例分析,感興趣的朋友跟隨小編一起看看吧
    2024-10-10
  • Python+DeOldify實現(xiàn)老照片上色功能

    Python+DeOldify實現(xiàn)老照片上色功能

    DeOldify是一種技術,以彩色和恢復舊的黑白圖像,甚至電影片段。它是由一個叫Jason?Antic的人開發(fā)和更新的。本文將利用DeOldify實現(xiàn)老照片上色功能,感興趣的可以了解一下
    2022-06-06
  • Python使用uv整合Pip、Pyenv和Venv的實戰(zhàn)指南

    Python使用uv整合Pip、Pyenv和Venv的實戰(zhàn)指南

    Python 的包管理一直是個讓開發(fā)者又愛又恨的話題,從 pip 到 virtualenv,再到 poetry、conda、pdm,工具層出不窮,但似乎總覺得差點意思,最近,Python 圈子殺出了一匹黑馬uv,本文給大家介紹了Python使用uv整合Pip、Pyenv和Venv的實戰(zhàn)指南,需要的朋友可以參考下
    2026-05-05
  • python-docx的簡單使用示例教程

    python-docx的簡單使用示例教程

    這篇文章主要介紹了python-docx的簡單使用,本文通過示例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2023-05-05
  • Keras在mnist上的CNN實踐,并且自定義loss函數(shù)曲線圖操作

    Keras在mnist上的CNN實踐,并且自定義loss函數(shù)曲線圖操作

    這篇文章主要介紹了Keras在mnist上的CNN實踐,并且自定義loss函數(shù)曲線圖操作,具有很好的參考價值,希望對大家有所幫助。
    2021-05-05
  • Python完全識別驗證碼自動登錄實例詳解

    Python完全識別驗證碼自動登錄實例詳解

    今天小編就為大家分享一篇Python完全識別驗證碼自動登錄實例詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-11-11
  • python使用NumPy文件的讀寫操作

    python使用NumPy文件的讀寫操作

    這篇文章主要介紹了python使用NumPy讀寫文本文件。想了解第三方庫文件操作的同學,來看一下吧
    2021-04-04
  • Python中的Django基本命令實例詳解

    Python中的Django基本命令實例詳解

    這篇文章主要介紹了Python之Django基本命令 ,需要的朋友可以參考下
    2018-07-07
  • 6個實用的Python自動化腳本詳解

    6個實用的Python自動化腳本詳解

    每天你都可能會執(zhí)行許多重復的任務,例如閱讀 pdf、播放音樂、查看天氣、打開書簽、清理文件夾等等,使用自動化腳本,就無需手動一次又一次地完成這些任務,非常方便??旄S小編一起試一試吧
    2022-01-01
  • python爬取熱搜制作詞云

    python爬取熱搜制作詞云

    這篇文章主要介紹了python爬取百度熱搜制作詞云,首先爬取百度熱搜,至少間隔1小時,存入文件,避免重復請求,如果本1小時有了不再請求,存入數(shù)據(jù)庫,供詞云包使用,爬取熱搜,具體流程請需要的小伙伴參考下面文章內容
    2021-12-12

最新評論

临湘市| 绥芬河市| 柳州市| 晋城| 江安县| 翼城县| 吴川市| 习水县| 北辰区| 云阳县| 治多县| 拜城县| 贡嘎县| 墨江| 兴仁县| 丹江口市| 习水县| 台南市| 镇康县| 太保市| 永靖县| 丹寨县| 手机| 巴里| 弋阳县| 习水县| 白朗县| 宁城县| 淄博市| 义马市| 三门县| 金阳县| 昂仁县| 都兰县| 临洮县| 保定市| 徐州市| 太湖县| 阿城市| 临西县| 特克斯县|