python 生成正態(tài)分布數(shù)據(jù),并繪圖和解析
1、生成正態(tài)分布數(shù)據(jù)并繪制概率分布圖
import pandas as pd import numpy as np import matplotlib.pyplot as plt # 根據(jù)均值、標(biāo)準(zhǔn)差,求指定范圍的正態(tài)分布概率值 def normfun(x, mu, sigma): pdf = np.exp(-((x - mu)**2)/(2*sigma**2)) / (sigma * np.sqrt(2*np.pi)) return pdf # result = np.random.randint(-65, 80, size=100) # 最小值,最大值,數(shù)量 result = np.random.normal(15, 44, 100) # 均值為0.5,方差為1 print(result) x = np.arange(min(result), max(result), 0.1) # 設(shè)定 y 軸,載入剛才的正態(tài)分布函數(shù) print(result.mean(), result.std()) y = normfun(x, result.mean(), result.std()) plt.plot(x, y) # 這里畫出理論的正態(tài)分布概率曲線 # 這里畫出實(shí)際的參數(shù)概率與取值關(guān)系 plt.hist(result, bins=10, rwidth=0.8, density=True) # bins個(gè)柱狀圖,寬度是rwidth(0~1),=1沒有縫隙 plt.title('distribution') plt.xlabel('temperature') plt.ylabel('probability') # 輸出 plt.show() # 最后圖片的概率和不為1是因?yàn)檎龖B(tài)分布是從負(fù)無窮到正無窮,這里指截取了數(shù)據(jù)最小值到最大值的分布
根據(jù)范圍生成正態(tài)分布:
result = np.random.randint(-65, 80, size=100) # 最小值,最大值,數(shù)量
根據(jù)均值、方差生成正態(tài)分布:
result = np.random.normal(15, 44, 100) # 均值為0.5,方差為1
2、判斷一個(gè)序列是否符合正態(tài)分布
import numpy as np from scipy import stats pts = 1000 np.random.seed(28041990) a = np.random.normal(0, 1, size=pts) # 生成1個(gè)正態(tài)分布,均值為0,標(biāo)準(zhǔn)差為1,100個(gè)點(diǎn) b = np.random.normal(2, 1, size=pts) # 生成1個(gè)正態(tài)分布,均值為2,標(biāo)準(zhǔn)差為1, 100個(gè)點(diǎn) x = np.concatenate((a, b)) # 把兩個(gè)正態(tài)分布連接起來,所以理論上變成了非正態(tài)分布序列 k2, p = stats.normaltest(x) alpha = 1e-3 print("p = {:g}".format(p)) # 原假設(shè):x是一個(gè)正態(tài)分布 if p < alpha: # null hypothesis: x comes from a normal distribution print("The null hypothesis can be rejected") # 原假設(shè)可被拒絕,即不是正態(tài)分布 else: print("The null hypothesis cannot be rejected") # 原假設(shè)不可被拒絕,即使正態(tài)分布
3、求置信區(qū)間、異常值
import numpy as np import matplotlib.pyplot as plt from scipy import stats import pandas as pd # 求列表數(shù)據(jù)的異常點(diǎn) def get_outer_data(data_list): df = pd.DataFrame(data_list, columns=['value']) df = df.iloc[:, 0] # 計(jì)算下四分位數(shù)和上四分位 Q1 = df.quantile(q=0.25) Q3 = df.quantile(q=0.75) # 基于1.5倍的四分位差計(jì)算上下須對(duì)應(yīng)的值 low_whisker = Q1 - 1.5 * (Q3 - Q1) up_whisker = Q3 + 1.5 * (Q3 - Q1) # 尋找異常點(diǎn) kk = df[(df > up_whisker) | (df < low_whisker)] data1 = pd.DataFrame({'id': kk.index, '異常值': kk}) return data1 N = 100 result = np.random.normal(0, 1, N) # result = np.random.randint(-65, 80, size=N) # 最小值,最大值,數(shù)量 mean, std = result.mean(), result.std(ddof=1) # 求均值和標(biāo)準(zhǔn)差 # 計(jì)算置信區(qū)間,這里的0.9是置信水平 conf_intveral = stats.norm.interval(0.9, loc=mean, scale=std) # 90%概率 print('置信區(qū)間:', conf_intveral) x = np.arange(0, len(result), 1) # 求異常值 outer = get_outer_data(result) print(outer, type(outer)) x1 = outer.iloc[:, 0] y1 = outer.iloc[:, 1] plt.scatter(x1, y1, marker='x', color='r') # 所有離散點(diǎn) plt.scatter(x, result, marker='.', color='g') # 異常點(diǎn) plt.plot([0, len(result)], [conf_intveral[0], conf_intveral[0]]) plt.plot([0, len(result)], [conf_intveral[1], conf_intveral[1]]) plt.show()
4、采樣點(diǎn)離散圖和概率圖
import numpy as np import matplotlib.pyplot as plt from scipy import stats import pandas as pd import time print(time.strftime('%Y-%m-%D %H:%M:%S')) # 根據(jù)均值、標(biāo)準(zhǔn)差,求指定范圍的正態(tài)分布概率值 def _normfun(x, mu, sigma): pdf = np.exp(-((x - mu)**2)/(2*sigma**2)) / (sigma * np.sqrt(2*np.pi)) return pdf # 求列表數(shù)據(jù)的異常點(diǎn) def get_outer_data(data_list): df = pd.DataFrame(data_list, columns=['value']) df = df.iloc[:, 0] # 計(jì)算下四分位數(shù)和上四分位 Q1 = df.quantile(q=0.25) Q3 = df.quantile(q=0.75) # 基于1.5倍的四分位差計(jì)算上下須對(duì)應(yīng)的值 low_whisker = Q1 - 1.5 * (Q3 - Q1) up_whisker = Q3 + 1.5 * (Q3 - Q1) # 尋找異常點(diǎn) kk = df[(df > up_whisker) | (df < low_whisker)] data1 = pd.DataFrame({'id': kk.index, '異常值': kk}) return data1 N = 100 result = np.random.normal(0, 1, N) # result = np.random.randint(-65, 80, size=N) # 最小值,最大值,數(shù)量 # result = [100]*100 # 取值全相同 # result = np.array(result) mean, std = result.mean(), result.std(ddof=1) # 求均值和標(biāo)準(zhǔn)差 # 計(jì)算置信區(qū)間,這里的0.9是置信水平 if std == 0: # 如果所有值都相同即標(biāo)準(zhǔn)差為0則無法計(jì)算置信區(qū)間 conf_intveral = [min(result)-1, max(result)+1] else: conf_intveral = stats.norm.interval(0.9, loc=mean, scale=std) # 90%概率 # print('置信區(qū)間:', conf_intveral) # 求異常值 outer = get_outer_data(result) # 繪制離散圖 fig = plt.figure() fig.add_subplot(2, 1, 1) plt.subplots_adjust(hspace=0.3) x = np.arange(0, len(result), 1) plt.scatter(x, result, marker='.', color='g') # 畫所有離散點(diǎn) plt.scatter(outer.iloc[:, 0], outer.iloc[:, 1], marker='x', color='r') # 畫異常離散點(diǎn) plt.plot([0, len(result)], [conf_intveral[0], conf_intveral[0]]) # 置信區(qū)間線條 plt.plot([0, len(result)], [conf_intveral[1], conf_intveral[1]]) # 置信區(qū)間線條 plt.text(0, conf_intveral[0], '{:.2f}'.format(conf_intveral[0])) # 置信區(qū)間數(shù)字顯示 plt.text(0, conf_intveral[1], '{:.2f}'.format(conf_intveral[1])) # 置信區(qū)間數(shù)字顯示 info = 'outer count:{}'.format(len(outer.iloc[:, 0])) plt.text(min(x), max(result)-((max(result)-min(result)) / 2), info) # 異常點(diǎn)數(shù)顯示 plt.xlabel('sample count') plt.ylabel('value') # 繪制概率圖 if std != 0: # 如果所有取值都相同 fig.add_subplot(2, 1, 2) x = np.arange(min(result), max(result), 0.1) y = _normfun(x, result.mean(), result.std()) plt.plot(x, y) # 這里畫出理論的正態(tài)分布概率曲線 plt.hist(result, bins=10, rwidth=0.8, density=True) # bins個(gè)柱狀圖,寬度是rwidth(0~1),=1沒有縫隙 info = 'mean:{:.2f}\nstd:{:.2f}\nmode num:{:.2f}'.format(mean, std, np.median(result)) plt.text(min(x), max(y) / 2, info) plt.xlabel('value') plt.ylabel('Probability') else: fig.add_subplot(2, 1, 2) info = 'non-normal distribution!!\nmean:{:.2f}\nstd:{:.2f}\nmode num:{:.2f}'.format(mean, std, np.median(result)) plt.text(0.5, 0.5, info) plt.xlabel('value') plt.ylabel('Probability') plt.savefig('./distribution.jpg') plt.show() print(time.strftime('%Y-%m-%D %H:%M:%S'))
以上就是python 生成正態(tài)分布數(shù)據(jù),并繪圖和解析的詳細(xì)內(nèi)容,更多關(guān)于python 正態(tài)分布的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Opencv中的cv2.calcHist()函數(shù)的作用及返回值說明
這篇文章主要介紹了Opencv中的cv2.calcHist()函數(shù)的作用及返回值說明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-11-11python實(shí)現(xiàn)百度文庫自動(dòng)化爬取
項(xiàng)目是合法項(xiàng)目,只是進(jìn)行數(shù)據(jù)解析而已,不能下載看不到的內(nèi)容.部分文檔在電腦端不能預(yù)覽,但是在手機(jī)端可以預(yù)覽,所有本項(xiàng)目把瀏覽器瀏覽格式改成手機(jī)端,支持Windows和Ubuntu. 本項(xiàng)目使用的是chromedriver來控制chrome來模擬人來操作來進(jìn)行文檔爬取2021-04-04Python爬蟲JSON及JSONPath運(yùn)行原理詳解
這篇文章主要介紹了Python爬蟲JSON及JSONPath運(yùn)行原理詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-06-06基于Python采集爬取微信公眾號(hào)歷史數(shù)據(jù)
這篇文章主要介紹了基于Python采集爬取微信公眾號(hào)歷史數(shù)據(jù),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-11-11自動(dòng)在Windows中運(yùn)行Python腳本并定時(shí)觸發(fā)功能實(shí)現(xiàn)
講一下在Python中寫好了一個(gè)腳本之后,怎么自動(dòng)雙擊一個(gè)程序自動(dòng)就跑起來。以及,怎么在Windows 10中設(shè)計(jì)定期定時(shí)觸發(fā)并跑腳本,有需要的朋友可以參考下2021-09-09python裝飾器相當(dāng)于函數(shù)的調(diào)用方式
今天小編就為大家分享一篇python裝飾器相當(dāng)于函數(shù)的調(diào)用方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-12-12python組合無重復(fù)三位數(shù)的實(shí)例
今天小編就為大家分享一篇python組合無重復(fù)三位數(shù)的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-11-11