python - 手写数字识别问题: Wrong number of dimensions

标签 python neural-network deep-learning theano tensor

我正在尝试训练我的神经网络模型来识别手写数字,但我卡住了。

我面临的问题是,当我尝试训练我的神经网络时,我试图将我的训练数据传递给该函数,但是当我这样做时,我得到了维数错误的错误。

我的代码:

import theano
import lasagne as lse
import theano.tensor as T

def build_nn(input_var=None):
    l_input=lse.layers.InputLayer(shape=(None,1,28,28),input_var=input_var)
    ldrop=lse.layers.DropoutLayer(l_input,p=0.2)
    l_hid1=lse.layers.DenseLayer(ldrop,num_units=800,
                                  nonlinearity=lse.nonlinearities.rectify,
                                  W=lse.init.GlorotUniform())
    l_hid1_drop=lse.layers.DropoutLayer(l_hid1,p=0.5)

    l_hid2=lse.layers.DenseLayer(l_hid1_drop,num_units=800,
                                  nonlinearity=lse.nonlinearities.rectify,
                                  W=lse.init.GlorotUniform())
    l_hid2_drop=lse.layers.DropoutLayer(l_hid2,p=0.5)

    l_output=lse.layers.DenseLayer(l_hid2_drop,num_units=10,nonlinearity=lse.nonlinearities.softmax)

    return l_output

input_var=T.tensor4('inputs')
target_var=T.lvector('targets')

network=build_nn(input_var)
prediction=lse.layers.get_output(network)

loss=lse.objectives.categorical_crossentropy(prediction,target_var)

loss=loss.mean()

params=lse.layers.get_all_params(network,trainable=True)

update=lse.updates.nesterov_momentum(loss,params,learning_rate=1,momentum=0.9)
tain_fn=theano.function([input_var,target_var],loss,updates=update)

num_training_step=1000

for steps in range(num_training_step):
    train_err=tain_fn(x_train,y_train)
    print('Step '+str(steps))

错误:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-33-2827076f729d> in <module>
      2 
      3 for steps in range(num_training_step):
----> 4     train_err=tain_fn(x_train,y_train)
      5     print('Step '+str(steps))

~\Anaconda3\lib\site-packages\theano\compile\function_module.py in __call__(self, *args, **kwargs)
    811                         s.storage[0] = s.type.filter(
    812                             arg, strict=s.strict,
--> 813                             allow_downcast=s.allow_downcast)
    814 
    815                     except Exception as e:

~\Anaconda3\lib\site-packages\theano\tensor\type.py in filter(self, data, strict, allow_downcast)
    176             raise TypeError("Wrong number of dimensions: expected %s,"
    177                             " got %s with shape %s." % (self.ndim, data.ndim,
--> 178                                                         data.shape))
    179         if not data.flags.aligned:
    180             try:

TypeError: Bad input argument to theano function with name "<ipython-input-32-e01e77ca594c>:14" at index 0 (0-based).  
Backtrace when that variable is created:

  File "C:\Users\hp\Anaconda3\lib\site-packages\ipykernel\zmqshell.py", line 536, in run_cell
    return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs)
  File "C:\Users\hp\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 2819, in run_cell
    raw_cell, store_history, silent, shell_futures)
  File "C:\Users\hp\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 2845, in _run_cell
    return runner(coro)
  File "C:\Users\hp\Anaconda3\lib\site-packages\IPython\core\async_helpers.py", line 67, in _pseudo_sync_runner
    coro.send(None)
  File "C:\Users\hp\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 3020, in run_cell_async
    interactivity=interactivity, compiler=compiler, result=result)
  File "C:\Users\hp\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 3185, in run_ast_nodes
    if (yield from self.run_code(code, result)):
  File "C:\Users\hp\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 3267, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-32-e01e77ca594c>", line 1, in <module>
    input_var=T.tensor4('inputs')
Wrong number of dimensions: expected 4, got 3 with shape (60000, 28, 28).

最佳答案

根据您的代码,您期望输入张量的形状为 (X, 1, 28, 28)

l_input=lse.layers.InputLayer(shape=(None,1,28,28),input_var=input_var)

其中 1 是 channel 数。如果您计划只使用一个 channel (灰度),您可以将您的输入重构为 shape=(None,28,28),或者将您的数据重构为具有额外的维度以适应输入层。

关于python - 手写数字识别问题: Wrong number of dimensions,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54849722/

相关文章:

neural-network - theano 中 ifelse 和 switch 的用途是什么?

machine-learning - 一般情况下使用深度自动编码器/深度学习时具有足够的均方误差

python - 无法使用贡献模块让 PELU 或 SineRelu 激活函数在 keras 中工作

deep-learning - 如何为情感分析构建和标记非英文数据集

python - 如何有条件地重新排列行顺序

Python Pandas - 根据组中值的存在来过滤组

python - 在python中,我想根据字典值的字典对字典进行排序

python - Linux 上的 OpenCv + Gstreamer + python

python - 使用 inception V3 在 Tensorflow 中本地化对象

python - 计算损失时检查标签( tensorflow )