numpy 绘制自相关函数图时,获取UFuncTypeError

puruo6ea  于 2023-05-17  发布在  其他
关注(0)|答案(1)|浏览(155)

绘制自相关函数图时gettingUFuncTypeError:无法将ufunc 'divide'输出从dtype('float64 ')转换为dtype('int32'),在注解# Plot the autocorrelation function for X and Y之后发生错误。我需要将跟踪x和y转换为浮点数吗?

import numpy as np
import matplotlib.pyplot as plt

# Define the probability matrix
p = np.array([[10/66, 15/66, 3/66], [20/66, 12/66, 0], [6/66, 0, 0]])

# Initialize starting values for X and Y
x = 0
y = 0

# Create arrays to store trace plots
trace_x = []
trace_y = []

# Run 12,000 iterations of Gibbs sampling (with 2,000 burn-in)
for i in range(12000):
    # Sample a new value for X given the current value of Y
    py = np.sum(p[y])
    x = np.random.choice([0, 1, 2], p=p[y] / py)
    # Sample a new value for Y given the current value of X
    px = np.sum(p[:, x])
    y = np.random.choice([0, 1, 2], p=p[:, x] / px)
    # Append the new values to the trace plots after the burn-in period
    if i >= 2000:
        trace_x.append(x)
        trace_y.append(y)

# Plot the autocorrelation function for X and Y
plt.acorr(trace_x, maxlags=50)
plt.title('Autocorrelation plot for X')
plt.xlabel('Lag')
plt.ylabel('Autocorrelation')
plt.show()

plt.acorr(trace_y, maxlags=50)
plt.title('Autocorrelation plot for Y')
plt.xlabel('Lag')
plt.ylabel('Autocorrelation')
plt.show()
wljmcqd8

wljmcqd81#

对回溯的研究表明,错误是由行引起的

if normed:
        correls /= np.sqrt(np.dot(x, x) * np.dot(y, y))

matplotlib源代码中,位于https://github.com/matplotlib/matplotlib/blob/main/lib/matplotlib/axes/_axes.py
出现此错误是由于在使用就地操作时阻止numpy库中的自动向上转换。这在SO用户的回答中得到了很好的解释:pokehere。现在,为了回答OP的问题,我们需要避开就地操作。
因此,对于OP的具体问题,有三种解决方案:

  • 解决方案1.* 如果不需要归一化值,则可以将normed=False作为参数传入plt.acorr函数,如下所示:
plt.acorr(trace_x, maxlags=50, normed=False)

输出:

  • 解决方案2.* 如果需要归一化值,请首先将输入转换为float:
plt.acorr(np.array(trace_x, dtype=float), maxlags=50)

输出:

  • 解决方案3.* 修复可以在matplotlib的代码本身中应用。将在位运算符更改为常规赋值:
correls = correls / np.sqrt(np.dot(x, x) * np.dot(y, y))

输出(与解决方案2相同):

我向matplotlib here提交了一个pull请求,并引用了OP的问题。如果我的pull请求被批准,我将更新答案。

**编辑:**拉取请求已审核通过。acorr函数可以按预期工作,即使在使用全整数的列表或numpy数组时也是如此。

相关问题