'TypeError: an integer is required'使用 numpy.random.randn() 初始化 numpy 中的随机权重矩阵时



所以我使用numpy从矩阵构建一个神经网络,并且我有以下代码用于初始化:

for i in xrange(self.num_layers-1):
    self.params['W%d' % i] = np.random.randn(input_dim, hidden_dims) * weight_scale
    self.params['b%d' % i] = np.zeros(hidden_dims)

所有变量都是预定义的;

type(input_dim) == integer
type(hidden_dims) == integer
type(self.num_layers) == integer
weight_scale == 1e-3

然而,当我部署它时,我得到以下错误:

Traceback (most recent call last):
  File "...", line 201, in __init__
self.params['W%d' % i] = np.random.randn(input_dim, hidden_dims) * weight_scale
  File "mtrand.pyx", line 1680, in mtrand.RandomState.randn (numpy/random/mtrand/mtrand.c:17783)
  File "mtrand.pyx", line 1810, in mtrand.RandomState.standard_normal (numpy/random/mtrand/mtrand.c:18250)
  File "mtrand.pyx", line 163, in mtrand.cont0_array (numpy/random/mtrand/mtrand.c:2196)
TypeError: an integer is required

我已经尝试搜索此错误,但无法获得任何相关匹配。知道是哪里出了问题吗?我也试过使用np.random。normal(scale=weigh_tscale, size=(input_dim, hidden_dims))和我收到了相同的

'TypeError: an integer is required'

提前感谢你的任何线索!


更新:这是使用python2,而不是3

您将range拼错为xrange。这将解决你的问题。

for i in range(self.num_layers-1):
    self.params['W%d' % i] = np.random.randn(input_dim, hidden_dims) * weight_scale
    self.params['b%d' % i] = np.zeros(hidden_dims)

否则,np.random.randn(input_dim, hidden_dims)不应该像np.random.randn((input_dim, hidden_dims))

那样用双括号表示度量值大小。

最新更新