簡體   English   中英

我正在學習如何通過重要性采樣來擬合 python 上的數據,我正在嘗試對 x 和 y 值進行采樣並找到它們的權重,但我遇到了錯誤

[英]I am learning how to data fit on python with importance sampling, I am trying to sample x and y values and find their weights but I am getting errors

基本上,我試圖從提案分布 function 中采樣 x 和 y,然后找到樣本的權重,並創建 10 個不同的 n = 10,000 個樣本集。 我得到了一個包含 55 個半徑、mu 和 sigma 值的數組,我有 10,000 個 x 和 y 值作為樣本。

這是我的代碼:

import numpy as np
import matplotlib.pyplot as plt 

GN = 4.302**-6
A = 8445.264

mu = np.array([1,1])
C = [[1,0],[0,1]]
num = 10**4
def chi_sq(x,y):
  r = np.zeros(len(radius))
  for s in range(len(radius)):
    f_xy = np.sqrt( GN * 10**y * radius[s] / (radius[s] + 10**x )**3 ) 
    chi_sqtotal = np.sum((f_xy - mu[s] )**2 / (sigma[s])**2)
    r += chi_sqtotal 
  return r 
def P(x,y):
  return A*np.exp(-0.5*chi_sq(x,y))
for i in range(10):
  def chi_sq(x,y):
    r = np.zeros(len(radius))
    for s in range(len(radius)):
      f_xy = np.sqrt( GN * 10**y * radius[s] / (radius[s] + 10**x )**3 ) 
      chi_sqtotal = np.sum((f_xy - mu[s] )**2 / (sigma[s])**2)
      r += chi_sqtotal 
    return r 
  def P(x,y):
    return A*np.exp(-0.5*chi_sq(x,y))
  detC = np.linalg.det(C)
  Cinv = np.linalg.inv(C)
  def Q(x,y):
    r = np.array([x,y]) - mu
    prefactor = 1/(2*np.pi*np.sqrt(detC))
    exponent = 0.5*(r @ Cinv @ r)
    return prefactor*np.exp(-exponent)
  r_samples = np.random.multivariate_normal(mu,C,num)
  x_samples = r_samples[:,0]
  y_samples = r_samples[:,1]
  w = np.zeros(num)
  for j in range(num):
    x, y = r_samples[j]
    
    w[j] = P(x,y)/Q(x,y)

這是我得到的錯誤:

IndexError                                Traceback (most recent call last)
<ipython-input-114-638cc1a1b2e2> in <module>()
     41     x, y = r_samples[j]
     42 
---> 43     w[j] = P(x,y)/Q(x,y)

1 frames
<ipython-input-114-638cc1a1b2e2> in chi_sq(x, y)
     22     for s in range(len(radius)):
     23       f_xy = np.sqrt( GN * 10**y * radius[s] / (radius[s] + 10**x )**3 )
---> 24       chi_sqtotal = np.sum((f_xy - mu[s] )**2 / (sigma[s])**2)
     25       r += chi_sqtotal
     26     return r

IndexError: index 2 is out of bounds for axis 0 with size 2

該錯誤非常具有描述性:

IndexError: index 2 is out of bounds for axis 0 with size 2

如果我有一個numpy.ndarray ,我們稱之為x ,那么軸如下:

x[axis_0][axis_1]...

他們說軸的大小是 2,而你用 2 來索引它,這是超出范圍的。 注意

mu = np.array([1,1])

並且帶有mu的行有錯誤。 在這個塊中:

for s in range(len(radius)):
  f_xy = np.sqrt( GN * 10**y * radius[s] / (radius[s] + 10**x )**3 ) 
  chi_sqtotal = np.sum((f_xy - mu[s] )**2 / (sigma[s])**2)
  r += chi_sqtotal 

s高於 1,導致錯誤。 您需要在某處進行更正,而不是像len(radius)那樣高循環,因為mu只有 2 個元素。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM