【问题标题】:numpy reshape function - Type-error: order must be str, not intnumpy reshape 函数 - 类型错误:顺序必须是 str,而不是 int
【发布时间】:2020-12-01 09:50:18
【问题描述】:

我遇到了这种类型的错误:

Traceback (most recent call last):
  File "BoxMuller.py", line 34, in <module>
    y = boxmuller(1000)
  File "BoxMuller.py", line 31, in boxmuller
    y = np.reshape(str(y),2*str(n),1)
  File "<__array_function__ internals>", line 5, in reshape
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/numpy/core/fromnumeric.py", line 299, in reshape
    return _wrapfunc(a, 'reshape', newshape, order=order)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/numpy/core/fromnumeric.py", line 55, in _wrapfunc
    return _wrapit(obj, method, *args, **kwds)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/numpy/core/fromnumeric.py", line 44, in _wrapit
    result = getattr(asarray(obj), method)(*args, **kwds)
TypeError: order must be str, not int

虽然我把y = np.reshape(y,2*n,1)改成了y = np.reshape(str(y),2*str(n),1),还是不行。

完整代码:

# Code from Chapter 15 of Machine Learning: An Algorithmic Perspective (2nd Edition)
# by Stephen Marsland (http://stephenmonika.net)

# You are free to use, change, or redistribute the code in any way you wish for
# non-commercial purposes, but please maintain the name of the original author.
# This code comes with no warranty of any kind.

# Stephen Marsland, 2008, 2014

# The Box-Muller algorithm for constructing pseudo-random Gaussian-distributed numbers

import pylab as pl
import numpy as np

def boxmuller(n):
    
    x = np.zeros((n,2))
    y = np.zeros((n,2))
    
    for i in range(n):
        x[i,:] = np.array([2,2])
        x2 = x[i,0]*x[i,0]+x[i,1]*x[i,1]
        while (x2)>1:
            x[i,:] = np.random.rand(2)*2-1
            x2 = x[i,0]*x[i,0]+x[i,1]*x[i,1]

        y[i,:] = x[i,:] * np.sqrt((-2*np.log(x2))/x2)
    
    y = np.reshape(y,2*n,1)
    return y

y = boxmuller(1000)
pl.hist(y,normed=1,fc='k')
x = np.arange(-4,4,0.1)
pl.plot(x,1/np.sqrt(2*np.pi)*np.exp(-0.5*x**2),'k',lw=6)
pl.xlabel('x',fontsize=24)
pl.ylabel('p(x)',fontsize=24)
pl.show()

感谢您的帮助

【问题讨论】:

    标签: python string numpy


    【解决方案1】:

    Order 是numpy.reshape 中的第三个参数。我认为您要做的是将形状元组作为第二个参数传递。见doc。 试试这个y = np.reshape(y,(2*n,1))

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-21
      • 2018-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-05
      • 2019-12-05
      • 1970-01-01
      相关资源
      最近更新 更多