使用 numpy.random.randn() 在 numpy 中初始化随机权重矩阵时出现“TypeError: an integer is required”

Dav*_*eAl 5 python numpy initialization matrix neural-network

所以我使用 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)
Run Code Online (Sandbox Code Playgroud)

所有变量都是预定义的;

type(input_dim) == integer
type(hidden_dims) == integer
type(self.num_layers) == integer
weight_scale == 1e-3
Run Code Online (Sandbox Code Playgroud)

但是,当我部署它时,出现以下错误:

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
Run Code Online (Sandbox Code Playgroud)

我已尝试搜索此错误,但无法获得任何相关匹配项。知道出了什么问题吗?我也尝试过使用 np.random.normal(scale=weigh_tscale, size=(input_dim, hidden_​​dims)) 并且我收到了相同的

'TypeError: an integer is required'
Run Code Online (Sandbox Code Playgroud)

提前感谢您提供任何线索!


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

小智 1

您拼写错误rangexrange。这将解决您的问题。

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)
Run Code Online (Sandbox Code Playgroud)

否则,np.random.randn(input_dim, hidden_dims)不应该是双括号中的度量大小,例如np.random.randn((input_dim, hidden_dims))