SciPy - weighted() 方法



SciPy weighted() 方法不被視為內建方法,因為它允許使用者執行各種其他功能,例如加權均值、加權總和和加權運算。

此外,為了更好地闡明,我們有可能是更可靠的調查資料,在時間序列資料中,當前觀測值可能會給予更多權重。

語法

以下是 SciPy weighted() 方法中的各種相關函式 -

sum()
or,
sqrt()
or,
linregress()

引數

以下是所有上述語法的解釋 -

  • sum():計算給定資料的總和。
  • sqrt():求一個數的平方根。
  • linregress():它適用於兩組給定測量值的線性最小二乘迴歸。

返回值

它以浮點值的形式返回結果。

示例 1

以下是 SciPy weighted() 方法,使用指定權重計算給定資料陣列的平均權重。

import numpy as np
from scipy.stats import hmean

data = np.array([10, 20, 30, 40, 50])
weights = np.array([1.1, 1.2, 1.3, 1.4, 1.5])

avg_weight = np.average(data, weights = weights)
print("Weighted Harmonic Mean:", avg_weight)

輸出

以上程式碼產生以下結果 -

Weighted Harmonic Mean: 31.53846153846154

示例 2

以下是執行線性迴歸任務的示例,該任務考慮了指定權重的資料 x 和 y。

from scipy import stats
import numpy as np

x_axis = np.array([11, 12, 13, 14, 15])
y_axis = np.array([26, 37, 58, 79, 100])
weights = np.array([0.5, 0.5, 1, 1, 1])

# Weighted linear regression
slope, intercept, r_value, p_value, std_err = stats.linregress(x_axis, y_axis)
print(f"Slope: {slope}, Intercept: {intercept}")

輸出

以上程式碼產生以下結果 -

Slope: 19.0, Intercept: -187.0

示例 3

此示例說明包含加權統計的資料的詳細描述。

import numpy as np

data = np.array([11, 21, 31, 41, 51])
weights = np.array([0.11, 0.12, 0.13, 0.14, 0.15])

# weighted mean
weighted_mean = np.sum(data * weights) / np.sum(weights)

# weighted standard deviation
weighted_std = np.sqrt(np.sum(weights * (data - weighted_mean)**2) / np.sum(weights))

print(f"Weighted Mean: {weighted_mean:.2f}")
print(f"Weighted Standard Deviation: {weighted_std:.2f}")

輸出

以上程式碼產生以下結果 -

Weighted Mean: 3.67
Weighted Standard Deviation: 1.25
scipy_reference.htm
廣告
© . All rights reserved.