Hướng dẫn what is 95 confidence interval in python? - khoảng tin cậy 95 trong python là gì?


A & nbsp; Khoảng tin cậy cho giá trị trung bình & nbsp; là một loạt các giá trị có khả năng chứa một dân số có nghĩa là với một mức độ tin cậy nhất định.confidence interval for a mean is a range of values that is likely to contain a population mean with a certain level of confidence.

Nó được tính là:

Khoảng tin cậy = & nbsp; x & nbsp; +/-& nbsp; t*(s/√n)x  +/-  t*(s/√n)

where:

  • x: & nbsp; trung bình mẫusample mean
  • T: & nbsp; giá trị t tương ứng với mức độ tin cậyt-value that corresponds to the confidence level
  • s: & nbsp; độ lệch chuẩn mẫusample standard deviation
  • n: & nbsp; cỡ mẫusample size

Hướng dẫn này giải thích cách tính toán khoảng tin cậy trong Python.

Khoảng tin cậy sử dụng phân phối T

Nếu chúng tôi làm việc với một mẫu nhỏ (n

Ví dụ sau đây cho thấy cách tính khoảng tin cậy cho chiều cao trung bình dân số thực (tính bằng inch) của một loài thực vật nhất định, sử dụng mẫu 15 cây:

import numpy as np
import scipy.stats as st

#define sample data
data = [12, 12, 13, 13, 15, 16, 17, 22, 23, 25, 26, 27, 28, 28, 29]

#create 95% confidence interval for population mean weight
st.t.interval(alpha=0.95, df=len(data)-1, loc=np.mean(data), scale=st.sem(data)) 

(16.758, 24.042)

Khoảng tin cậy 95% cho chiều cao trung bình dân số thực sự là & nbsp; (16.758, 24.042).(16.758, 24.042).

Bạn sẽ nhận thấy rằng mức độ tin cậy càng lớn, khoảng tin cậy càng rộng. Ví dụ, ở đây, cách tính toán 99% C.I. Đối với cùng một dữ liệu:

#create 99% confidence interval for same sample
st.t.interval(alpha=0.99, df=len(data)-1, loc=np.mean(data), scale=st.sem(data)) 

(15.348, 25.455)

Khoảng tin cậy 99% cho chiều cao trung bình dân số thực sự là & nbsp; (15.348, 25.455). Lưu ý rằng khoảng thời gian này rộng hơn khoảng tin cậy 95% trước đó.(15.348, 25.455). Notice that this interval is wider than the previous 95% confidence interval.

Khoảng tin cậy sử dụng phân phối bình thường

Nếu chúng tôi làm việc với các mẫu lớn hơn (N≥30), chúng tôi có thể giả sử rằng phân phối lấy mẫu của giá trị trung bình mẫu thường được phân phối (nhờ định lý giới hạn trung tâm) và thay vào đó có thể sử dụng hàm định mức.Interval () từ scipy .Stats Thư viện.

Ví dụ sau đây cho thấy cách tính khoảng tin cậy cho chiều cao trung bình dân số thực (tính bằng inch) của một loài thực vật nhất định, sử dụng mẫu 50 cây:

import numpy as np
import scipy.stats as st

#define sample data
np.random.seed(0)
data = np.random.randint(10, 30, 50)

#create 95% confidence interval for population mean weight
st.norm.interval(alpha=0.95, loc=np.mean(data), scale=st.sem(data))

(17.40, 21.08)

Khoảng tin cậy 95% cho chiều cao trung bình dân số thực sự là & nbsp; (17,40, 21,08).(17.40, 21.08).

Và tương tự như phân phối T, mức độ tin cậy lớn hơn dẫn đến khoảng tin cậy rộng hơn. Ví dụ, ở đây, cách tính toán 99% C.I. Đối với cùng một dữ liệu:

#create 99% confidence interval for same sample
st.norm.interval(alpha=0.99, loc=np.mean(data), scale=st.sem(data))

(16.82, 21.66)

Khoảng tin cậy 95% cho chiều cao trung bình dân số thực sự là & nbsp; (17,82, 21,66).(17.82, 21.66).

Cách diễn giải khoảng tin cậy

Giả sử khoảng tin cậy 95% của chúng ta đối với chiều cao trung bình dân số thực sự của một loài thực vật là:

Khoảng tin cậy 95% = (16.758, 24.042)

Cách để giải thích khoảng tin cậy này như sau:

Có 95% cơ hội rằng khoảng tin cậy của [16.758, 24.042] chứa chiều cao trung bình dân số thực sự của thực vật.

Một cách khác để nói điều tương tự là chỉ có 5% cơ hội rằng dân số thực sự có nghĩa là nằm ngoài khoảng tin cậy 95%. Đó là, chỉ có 5% cơ hội rằng chiều cao trung bình của dân số thực sự của cây dưới 16,758 inch hoặc lớn hơn 24.042 inch.

Dựa trên bản gốc nhưng với một số ví dụ cụ thể:

import numpy as np

def mean_confidence_interval(data, confidence: float = 0.95) -> tuple[float, np.ndarray]:
    """
    Returns (tuple of) the mean and confidence interval for given data.
    Data is a np.arrayable iterable.

    ref:
        - https://stackoverflow.com/a/15034143/1601580
        - https://github.com/WangYueFt/rfs/blob/f8c837ba93c62dd0ac68a2f4019c619aa86b8421/eval/meta_eval.py#L19
    """
    import scipy.stats
    import numpy as np

    a: np.ndarray = 1.0 * np.array(data)
    n: int = len(a)
    if n == 1:
        import logging
        logging.warning('The first dimension of your data is 1, perhaps you meant to transpose your data? or remove the'
                        'singleton dimension?')
    m, se = a.mean(), scipy.stats.sem(a)
    tp = scipy.stats.t.ppf((1 + confidence) / 2., n - 1)
    h = se * tp
    return m, h

def ci_test_float():
    import numpy as np
    # - one WRONG data set of size 1 by N
    data = np.random.randn(1, 30)  # gives an error becuase len sets n=1, so not this shape!
    m, ci = mean_confidence_interval(data)
    print('-- you should get a mean and a list of nan ci (since data is in wrong format, it thinks its 30 data sets of '
          'length 1.')
    print(m, ci)

    # right data as N by 1
    data = np.random.randn(30, 1)
    m, ci = mean_confidence_interval(data)
    print('-- gives a mean and a list of length 1 for a single CI (since it thinks you have a single dat aset)')
    print(m, ci)

    # multiple data sets (7) of size N (=30)
    data = np.random.randn(30, 7)
    print('-- gives 7 CIs for the 7 data sets of length 30. 30 is the number ud want large if you were using z(p)'
          'due to the CLT.')
    m, ci = mean_confidence_interval(data)
    print(m, ci)

ci_test_float()

output:

-- you should get a mean and a list of nan ci (since data is in wrong format, it thinks its 30 data sets of length 1.
0.1431623130952463 [nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan
 nan nan nan nan nan nan nan nan nan nan nan nan]
-- gives a mean and a list of length 1 for a single CI (since it thinks you have a single dat aset)
0.04947206018132864 [0.40627264]
-- gives 7 CIs for the 7 data sets of length 30. 30 is the number ud want large if you were using z(p)due to the CLT.
-0.03585104402718902 [0.31867309 0.35619134 0.34860011 0.3812853  0.44334033 0.35841138
 0.40739732]

Tôi nghĩ rằng num_samples của num_datasets là đúng nhưng nếu nó không cho tôi biết trong phần bình luận.


Đối với loại dữ liệu nào nó hoạt động cho?

Tôi nghĩ rằng nó có thể được sử dụng cho bất kỳ dữ liệu nào vì những điều sau đây:

Tôi tin rằng nó ổn vì giá trị trung bình và STD được tính toán cho dữ liệu số chung và giá trị Z_P/T_P chỉ có trong khoảng tin cậy và kích thước dữ liệu, do đó, nó độc lập với các giả định về phân phối dữ liệu.

Vì vậy, nó có thể được sử dụng để hồi quy và phân loại tôi tin.


Như một phần thưởng, một triển khai ngọn đuốc gần như chỉ sử dụng ngọn đuốc:

def torch_compute_confidence_interval(data: Tensor,
                                      confidence: float = 0.95
                                      ) -> Tensor:
    """
    Computes the confidence interval for a given survey of a data set.
    """
    n: int = len(data)
    mean: Tensor = data.mean()
    # se: Tensor = scipy.stats.sem(data)  # compute standard error
    # se, mean: Tensor = torch.std_mean(data, unbiased=True)  # compute standard error
    se: Tensor = data.std(unbiased=True) / (n ** 0.5)
    t_p: float = float(scipy.stats.t.ppf((1 + confidence) / 2., n - 1))
    ci = t_p * se
    return mean, ci

Một số nhận xét về CI (hoặc xem https://stats.stackexchange.com/questions/554332/confidence-pterval-given-the-population-mean-and-standard-deviation?noredirect=1&lq=1):

"""
Review for confidence intervals. Confidence intervals say that the true mean is inside the estimated confidence interval
(the r.v. the user generates). In particular it says:
    Pr[mu^* \in [mu_n +- t.val(p) * std_n / sqrt(n) ] ] >= p
e.g. p = 0.95
This does not say that for a specific CI you compute the true mean is in that interval with prob 0.95. Instead it means
that if you surveyed/sampled 100 data sets D_n = {x_i}^n_{i=1} of size n (where n is ideally >=30) then for 95 of those
you'd expect to have the truee mean inside the CI compute for that current data set. Note you can never check for which
ones mu^* is in the CI since mu^* is unknown. If you knew mu^* you wouldn't need to estimate it. This analysis assumes
that the the estimator/value your estimating is the true mean using the sample mean (estimator). Since it usually uses
the t.val or z.val (second for the standardozed r.v. of a normal) then it means the approximation that mu_n ~ gaussian
must hold. This is most likely true if n >= 0. Note this is similar to statistical learning theory where we use
the MLE/ERM estimator to choose a function with delta, gamma etc reasoning. Note that if you do algebra you can also
say that the sample mean is in that interval but wrt mu^* but that is borning, no one cares since you do not know mu^*
so it's not helpful.

An example use could be for computing the CI of the loss (e.g. 0-1, CE loss, etc). The mu^* you want is the expected
risk. So x_i = loss(f(x_i), y_i) and you are computing the CI for what is the true expected risk for that specific loss
function you choose. So mu_n = emperical mean of the loss and std_n = (unbiased) estimate of the std and then you can
simply plug in the values.

Assumptions for p-CI:
    - we are making a statement that mu^* is in mu+-pCI = mu+-t_p * sig_n / sqrt n, sig_n ~ Var[x] is inside the CI
    p% of the time.
    - we are estimating mu^, a mean
    - since the quantity of interest is mu^, then the z_p value (or p-value, depending which one is the unknown), is
    computed using the normal distribution.
    - p(mu) ~ N(mu; mu_n, sig_n/ sqrt n), vial CTL which holds for sample means. Ideally n >= 30.
    - x ~ p^*(x) are iid.

Std_n vs t_p*std_n/ sqrt(n)
    - std_n = var(x) is more pessimistic but holds always. Never shrinks as n->infity
    - but if n is small then pCI might be too small and your "lying to yourself". So if you have very small data
    perhaps doing std_n for the CI is better. That holds with prob 99.9%. Hopefuly std is not too large for your
    experiments to be invalidated.

ref:
    - https://stats.stackexchange.com/questions/554332/confidence-interval-given-the-population-mean-and-standard-deviation?noredirect=1&lq=1
    - https://stackoverflow.com/questions/70356922/what-is-the-proper-way-to-compute-95-confidence-intervals-with-pytorch-for-clas
    - https://www.youtube.com/watch?v=MzvRQFYUEFU&list=PLUl4u3cNGP60hI9ATjSFgLZpbNJ7myAg6&index=205
"""

Khoảng tin cậy 95% có nghĩa là gì?

Nói đúng, khoảng tin cậy 95% có nghĩa là nếu chúng ta lấy 100 mẫu khác nhau và tính khoảng tin cậy 95% cho mỗi mẫu, thì khoảng 95 trong số 100 khoảng tin cậy sẽ chứa giá trị trung bình thực (μ).if we were to take 100 different samples and compute a 95% confidence interval for each sample, then approximately 95 of the 100 confidence intervals will contain the true mean value (μ).

Mức độ tự tin trong Python là gì?

Cách tiếp cận này được sử dụng để tính toán khoảng tin cậy cho bộ dữ liệu nhỏ trong đó n trong đó n trong đócall the t. interval() function from the scipy. stats library to get the confidence interval for a population means of the given dataset in python.