在 Python 中計算累積分佈函式
    
    
            Najwa Riyaz
    2023年1月30日
    
    Python
    Python Math
    
 
術語累積分佈函式或 CDF 是一個函式 y=f(x),其中 y 表示整數 x 或任何低於 x 的數字從分佈中隨機選擇的概率。
它是通過使用 NumPy 庫中的以下函式在 Python 中計算的。
- numpy.arange()函式返回一個- ndarray的均勻間隔值。
- numpy.linspace()函式返回給定間隔內均勻間隔值的- ndarray。
在 Python 中使用 numpy.arange() 計算 CDF
NumPy 標準庫包含用於在 Python 中確定 CDF 的 arange() 函式。
為此,首先匯入 NumPy 庫。
arange() 函式返回一個由均勻間隔的值組成的 ndarray。
下面的示例演示了使用 Python 中的 numpy.arange() 函式實現 CDF 函式。
import matplotlib.pyplot as plt
import numpy
data = numpy.random.randn(5)
print("The data is-", data)
sorted_random_data = numpy.sort(data)
p = 1.0 * numpy.arange(len(sorted_random_data)) / float(len(sorted_random_data) - 1)
print("The CDF result is-", p)
fig = plt.figure()
fig.suptitle("CDF of data points")
ax2 = fig.add_subplot(111)
ax2.plot(sorted_random_data, p)
ax2.set_xlabel("sorted_random_data")
ax2.set_ylabel("p")
在這裡,randn() 函式用於返回使用標準正態分佈的資料樣本。由於提到了 randn(5),因此使用 5 個隨機值構建了一個 1Darray。
接下來,使用 sort() 函式對資料進行排序,然後使用 arange() 函式計算 CDF。
輸出 :
The data is- [ 0.14213322 -1.28760908  0.94533922  0.82004319  1.08232731]
The CDF result is- [0.   0.25 0.5  0.75 1.  ]
圖形按照 CDF 函式顯示。

在 Python 中使用 numpy.linspace() 計算 CDF
NumPy 標準庫包含用於在 Python 中確定 CDF 的 linspace() 函式。為此,首先匯入 NumPy 庫。
linspace() 函式返回指定間隔內均勻間隔數字的 ndarray。
這是一個示例,演示了在 Python 中使用 numpy.linspace() 實現 CDF 函式。
import matplotlib.pyplot as plt
import numpy as np
data = np.random.randn(5)
print("The data is-", data)
sorted_random_data = np.sort(data)
np.linspace(0, 1, len(data), endpoint=False)
print("The CDF result using linspace =\n", p)
fig = plt.figure()
fig.suptitle("CDF of data points")
ax2 = fig.add_subplot(111)
ax2.plot(sorted_random_data, p)
ax2.set_xlabel("sorted_random_data")
ax2.set_ylabel("p")
在這裡,randn() 函式用於返回使用標準正態分佈的資料樣本。接下來,使用 sort() 函式對資料進行排序,然後使用 arange() 函式計算 CDF。
輸出:
The data is- [-0.92106668 -0.05998132  0.02102705 -0.84778184  0.90815869]
The CDF result using linspace =
 [0.   0.25 0.5  0.75 1.  ]
圖表按照 CDF 函式顯示,如下所示。

        Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe