theano功能的可选参数

时间:2015-06-17 07:46:24

标签: python numpy theano

我在theano中有一个函数f,它有两个参数,其中一个是可选的。当我使用可选参数None调用该函数时,f内的检查失败。此脚本重现错误:

import theano
import theano.tensor as T
import numpy as np

# function setup
def f(b, c=None):
    if c is not None:
        return (c*b).mean()
    else:
        return b.mean()

y = T.vector()
c = T.vector()
ins = [y,c]
tfn = theano.function(ins, f(y,c), allow_input_downcast=True, mode=None)

# eval function
first = np.array([1])
second = np.array([2])
second = None
res = tfn(first, second)
print res

失败并显示错误消息

ValueError: expected an ndarray, not None
Apply node that caused the error: Elemwise{mul,no_inplace}(<TensorType(float64, vector)>, <TensorType(float64, vector)>)
Inputs types: [TensorType(float64, vector), TensorType(float64, vector)]
Inputs shapes: ['No shapes', (1,)]
Inputs strides: ['No strides', (8,)]
Inputs values: [None, array([ 1.])]

Backtrace when the node is created:
  File "test_theano.py", line 14, in f
    return (c*b).mean()

c没有输入形状或输入步幅是有道理的。但我想知道为什么if内的f检查似乎不起作用。

如何在f内进行检查,以便正确处理可选参数c

2 个答案:

答案 0 :(得分:2)

我将尝试更完整的回复。

1)条件&#34; c不是None&#34;在构建图形时仅运行一次。由于c是符号变量,因此将始终执行else路径。如果要在运行时执行条件,请参阅此文档页面:

http://deeplearning.net/software/theano/tutorial/conditions.html

2)Theano有一个特殊的Type for None。但我不建议您使用它。它在大多数情况下都没用,也没有记录。因此,在你更熟悉Theano之前不要使用它。

3)告诉使用2个功能的另一个答案是可行的。

4)在这种简单的情况下,你可以传递一个正确大小的向量,只有一个而不是None。那也行,但要慢一些。

答案 1 :(得分:1)

Theano不支持可选参数。通过将函数的输入参数指定为ins=[y,c],您告诉Theano该函数具有两个1维(向量)参数。就Theano而言,两者都是强制性的。当您尝试传递None for c Theano检查您传入的值的类型是否与编译函数时声明的类型(即两个向量)匹配,但显然None是不是向量,因此引发此异常。

解决方案是编译两个Theano函数,一个只接受一个参数,另一个接受两个参数。您甚至可以将现有的Python函数f用于两者。