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

python 生成正態(tài)分布數據,并繪圖和解析

 更新時間:2020年12月21日 15:57:09   作者:朱小勇  
這篇文章主要介紹了python 生成正態(tài)分布數據,并繪圖和解析,幫助大家更好的利用python進行數據分析,感興趣的朋友可以了解下

1、生成正態(tài)分布數據并繪制概率分布圖

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt


# 根據均值、標準差,求指定范圍的正態(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) # 最小值,最大值,數量
result = np.random.normal(15, 44, 100) # 均值為0.5,方差為1
print(result)

x = np.arange(min(result), max(result), 0.1)
# 設定 y 軸,載入剛才的正態(tài)分布函數
print(result.mean(), result.std())
y = normfun(x, result.mean(), result.std())
plt.plot(x, y) # 這里畫出理論的正態(tài)分布概率曲線

# 這里畫出實際的參數概率與取值關系
plt.hist(result, bins=10, rwidth=0.8, density=True) # bins個柱狀圖,寬度是rwidth(0~1),=1沒有縫隙
plt.title('distribution')
plt.xlabel('temperature')
plt.ylabel('probability')
# 輸出
plt.show() # 最后圖片的概率和不為1是因為正態(tài)分布是從負無窮到正無窮,這里指截取了數據最小值到最大值的分布

根據范圍生成正態(tài)分布:

result = np.random.randint(-65, 80, size=100) # 最小值,最大值,數量

根據均值、方差生成正態(tài)分布:

result = np.random.normal(15, 44, 100) # 均值為0.5,方差為1

2、判斷一個序列是否符合正態(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個正態(tài)分布,均值為0,標準差為1,100個點
b = np.random.normal(2, 1, size=pts) # 生成1個正態(tài)分布,均值為2,標準差為1, 100個點
x = np.concatenate((a, b)) # 把兩個正態(tài)分布連接起來,所以理論上變成了非正態(tài)分布序列
k2, p = stats.normaltest(x)
alpha = 1e-3
print("p = {:g}".format(p))


# 原假設:x是一個正態(tài)分布
if p < alpha: # null hypothesis: x comes from a normal distribution
  print("The null hypothesis can be rejected") # 原假設可被拒絕,即不是正態(tài)分布
else:
  print("The null hypothesis cannot be rejected") # 原假設不可被拒絕,即使正態(tài)分布

3、求置信區(qū)間、異常值

import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
import pandas as pd


# 求列表數據的異常點
def get_outer_data(data_list):
  df = pd.DataFrame(data_list, columns=['value'])
  df = df.iloc[:, 0]
  # 計算下四分位數和上四分位
  Q1 = df.quantile(q=0.25)
  Q3 = df.quantile(q=0.75)

  # 基于1.5倍的四分位差計算上下須對應的值
  low_whisker = Q1 - 1.5 * (Q3 - Q1)
  up_whisker = Q3 + 1.5 * (Q3 - Q1)

  # 尋找異常點
  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) # 最小值,最大值,數量
mean, std = result.mean(), result.std(ddof=1) # 求均值和標準差

# 計算置信區(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') # 所有離散點
plt.scatter(x, result, marker='.', color='g') # 異常點
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、采樣點離散圖和概率圖

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'))


# 根據均值、標準差,求指定范圍的正態(tài)分布概率值
def _normfun(x, mu, sigma):
  pdf = np.exp(-((x - mu)**2)/(2*sigma**2)) / (sigma * np.sqrt(2*np.pi))
  return pdf


# 求列表數據的異常點
def get_outer_data(data_list):
  df = pd.DataFrame(data_list, columns=['value'])
  df = df.iloc[:, 0]
  # 計算下四分位數和上四分位
  Q1 = df.quantile(q=0.25)
  Q3 = df.quantile(q=0.75)

  # 基于1.5倍的四分位差計算上下須對應的值
  low_whisker = Q1 - 1.5 * (Q3 - Q1)
  up_whisker = Q3 + 1.5 * (Q3 - Q1)

  # 尋找異常點
  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) # 最小值,最大值,數量
# result = [100]*100 # 取值全相同
# result = np.array(result)
mean, std = result.mean(), result.std(ddof=1) # 求均值和標準差
# 計算置信區(qū)間,這里的0.9是置信水平
if std == 0: # 如果所有值都相同即標準差為0則無法計算置信區(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') # 畫所有離散點
plt.scatter(outer.iloc[:, 0], outer.iloc[:, 1], marker='x', color='r') # 畫異常離散點
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ū)間數字顯示
plt.text(0, conf_intveral[1], '{:.2f}'.format(conf_intveral[1])) # 置信區(qū)間數字顯示
info = 'outer count:{}'.format(len(outer.iloc[:, 0]))
plt.text(min(x), max(result)-((max(result)-min(result)) / 2), info) # 異常點數顯示
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個柱狀圖,寬度是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)分布數據,并繪圖和解析的詳細內容,更多關于python 正態(tài)分布的資料請關注腳本之家其它相關文章!

相關文章

  • Python函數默認返回None的原因及分析

    Python函數默認返回None的原因及分析

    Python函數默認返回None是因為在語法層面,解釋器會主動地為沒有return語句的函數添加一個返回邏輯,返回值為None
    2024-11-11
  • python入門課程第一講之安裝與優(yōu)缺點介紹

    python入門課程第一講之安裝與優(yōu)缺點介紹

    這篇文章主要介紹了python入門課程第一講之安裝與優(yōu)缺點,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2021-09-09
  • numpy array找出符合條件的數并賦值的示例代碼

    numpy array找出符合條件的數并賦值的示例代碼

    本文主要介紹了numpy array找出符合條件的數并賦值的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2022-05-05
  • python中怎么表示空值

    python中怎么表示空值

    在本篇內容里小編給大家整理了關于python如何表示空值的知識點內容,有興趣的朋友們可以跟著學習參考下。
    2020-06-06
  • pandas中read_csv的缺失值處理方式

    pandas中read_csv的缺失值處理方式

    今天小編就為大家分享一篇pandas中read_csv的缺失值處理方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-12-12
  • Windows下python3安裝tkinter的問題及解決方法

    Windows下python3安裝tkinter的問題及解決方法

    這篇文章主要介紹了Windows下python3安裝tkinter問題及解決方法,本文給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-01-01
  • 啟動Atom并運行python文件的步驟

    啟動Atom并運行python文件的步驟

    在本篇文章中我們給大家分享了啟動Atom并運行python文件的步驟以及具體做法,需要的朋友們參考下。
    2018-11-11
  • Python?sklearn預測評估指標混淆矩陣計算示例詳解

    Python?sklearn預測評估指標混淆矩陣計算示例詳解

    這篇文章主要為大家介紹了Python?sklearn預測評估指標混淆矩陣計算示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-02-02
  • python 處理pdf加密文件的操作代碼

    python 處理pdf加密文件的操作代碼

    這篇文章主要介紹了python 處理pdf加密文件的操作代碼,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友參考下吧
    2024-01-01
  • Python實現查找二叉搜索樹第k大的節(jié)點功能示例

    Python實現查找二叉搜索樹第k大的節(jié)點功能示例

    這篇文章主要介紹了Python實現查找二叉搜索樹第k大的節(jié)點功能,結合實例形式分析了Python二叉搜索樹的定義、查找、遍歷等相關操作技巧,需要的朋友可以參考下
    2019-01-01

最新評論

资兴市| 吉林省| 安仁县| 白玉县| 卢龙县| 沈阳市| 嘉兴市| 唐河县| 雅江县| 禄丰县| 临潭县| 南郑县| 若尔盖县| 囊谦县| 博湖县| 白山市| 青冈县| 新巴尔虎右旗| 德州市| 大丰市| 宜兴市| 佳木斯市| 牙克石市| 遂溪县| 武夷山市| 满洲里市| 汤阴县| 龙胜| 长武县| 新田县| 广安市| 舟山市| 丰原市| 丰顺县| 武邑县| 汝州市| 琼结县| 南和县| 焉耆| 兴隆县| 洪洞县|