I want to transform a P
vector of n
elements into a Z
vector of n+1
elements using the following formula:
I was able to do that in python with:
import numpy as np
def p_to_Z(p):
k = len(p)
Z = np.zeros(k+1)
Z[0] = p[0]
Z[1:k] = [p[i] / (1 - sum(p[range(i)])) for i in range(1,k)]
Z[-1] = 1
return Z
Example:
p_ex = np.array([0.3,0.4,0.1,0.2])
p_to_Z(p_ex)
output:
array([ 0.3, 0.57142857, 0.33333333, 1. , 1. ])
and for a matrix with:
M = np.array([[0.2, 0.05, 0.1],
[0.5, 2.0, 0.2],
[0.1, 0.2, 1.0]])
np.apply_along_axis(p_to_Z, 1, M)
array([[ 0.2 , 0.0625 , 0.13333333, 1.],
[ 0.5 , 4. ,-0.13333333, 1.],
[ 0.1 , 0.22222222, 1.42857143, 1.]])
I have been trying to translate this into theano but I have been getting my ass kicked by the scan function. Could some one help me define these functions in theano? I would be forever grateful.
EDIT: Failed attempts
import theano.tensor as tt
import numpy as np
import theano
from theano.compile.ops import as_op
p = tt.vector('p')
results, updates = theano.scan(lambda i: p[i] / (1 - tt.sum(p[:i-1])), sequences=tt.arange(1,N))
fn = theano.function([p,N],results)
p_ex = np.array([0.3,0.4,0.1,0.2])
Z = fn(p_ex,tt.get_vector_length(p_ex))
and with decorator:
@as_op(itypes=[tt.dvector],otypes=[tt.dvector])
def p_to_Z_theno(p):
N = tt.get_vector_length(p)
Z= theano.scan(lambda i: p[i] / (1 - tt.sum(p[:i - 1])), sequences=tt.arange(1, N))
fn = theano.function([p, N], results)
Z[0]=p[0]
Z[-1]=Z
return(Z)
The first one obviously do not generate the expected results, while the second gives:
Traceback (most recent call last): File "/usr/lib/python3/dist-packages/IPython/core/interactiveshell.py", line 2882, in run_code
exec(code_obj, self.user_global_ns, self.user_ns) File "<ipython-input-21-211efc53b449>", line 1, in <module>
p_to_Z_theno(p_ex) File "/usr/local/lib/python3.6/dist-packages/theano/gof/op.py", line 615, in __call__
node = self.make_node(*inputs, **kwargs) File "/usr/local/lib/python3.6/dist-packages/theano/gof/op.py", line 983, in make_node
if not all(inp.type == it for inp, it in zip(inputs, self.itypes)): File "/usr/local/lib/python3.6/dist-packages/theano/gof/op.py", line 983, in <genexpr>
if not all(inp.type == it for inp, it in zip(inputs, self.itypes)): AttributeError: 'numpy.ndarray' object has no attribute 'type'