38.2_从Variable对象调用reshape

38.2 从Variable对象调用reshape

我们的下一个目标是使DeZero中reshape函数的用法更接近NumPy中reshape函数的用法。在NumPy中,reshape的用法如下所示。

$\mathbf{x} =$  np.random.randint(1,2,3)  
y=x.reshape((2,3)) #传递元组  
y=x.reshape([2,3]) #传递列表  
y=xreshape(2,3) #直接(展开后)传递参数

如上面的代码所示,reshape可作为ndarray实例的方法使用,我们也可以向reshape传递可变长参数,如x.reshape(2,3)。我们想办法在DeZero中也实现这种用法。为此,要在Variable类中添加以下代码①。

dezero/core.py

importdezero   
classVariable: defreshape(self,\*shape): iflen(shape)  $= =$  1andisinstance(shape[0],tuple,list)): shape  $=$  shape[0] returndezero-functions.reshape(self,shape)

上面的代码在Variable类中实现了reshape方法。该方法接收可变长参数,然后调整传来的参数。下面调用刚刚实现的DeZero的reshape函数,代码如下所示。

$\mathbf{x} =$  Variable(np.random.randint(1,2,3))  
y=x.reshape((2,3))  
y=x.reshape(2,3)

如上面的代码所示,我们可以将reshape函数作为Variable实例的方法来调用。这样就能更轻松地改变Variable的形状了。到这里,reshape函数的实现就全部结束了。