简体   繁体   English

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

[英]'TypeError: an integer is required' when initializing random weight matrix in numpy with numpy.random.randn()

So I am using numpy to build a neural net from matrices, and I have the following code for initialization:所以我使用 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)

All variables are predefined;所有变量都是预定义的;

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

However, when I deploy this, I get the following error:但是,当我部署它时,出现以下错误:

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

I have tried searching for this error but cannot get any relevant matches.我已尝试搜索此错误,但无法获得任何相关匹配项。 Any idea what could have gone wrong?知道出了什么问题吗? I have also tried using np.random.normal(scale=weigh_tscale, size=(input_dim, hidden_dims)) and I have received the same我也尝试过使用 np.random.normal(scale=weigh_tscale, size=(input_dim, hidden_​​dims)) 并且我收到了相同的

'TypeError: an integer is required'

Thank you in advance for any clues!提前感谢您提供任何线索!


Update: This was using python2, not 3更新:这是使用 python2,而不是 3

You have misspelled range to xrange .您将range拼错为xrange This will solve your problem.这将解决您的问题。

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)

Otherwise, np.random.randn(input_dim, hidden_dims) should not be the metrics size in double braces like np.random.randn((input_dim, hidden_dims))否则, np.random.randn(input_dim, hidden_dims)不应像np.random.randn((input_dim, hidden_dims))那样是双括号中的度量大小

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM