def T_one_hot(inp_tensor, n_classes):
"""
:todo:
- Implement other methods from here:
- Compare them speed-wise for different sizes
- Implement N_one_hot for Numpy version, with speed tests.
Theano one-hot (1-of-k) from an input tensor of indecies.
If the indecies are of the shape (a0, a1, ..., an) the output
shape would be (a0, a1, ..., a2, n_classes).
:params:
- inp_tensor: any theano tensor with dtype int* as indecies and all of
them between [0, n_classes-1].
- n_classes: number of classes which determines the output size.
:usage:
>>> idx = T.itensor3()
>>> idx_val = numpy.array([[[0,1,2,3],[4,5,6,7]]], dtype='int32')
>>> one_hot = T_one_hot(t, 8)
>>> one_hot.eval({idx:idx_val})
>>> print out
array([[[[ 1., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 1., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 1., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 1., 0., 0., 0., 0.]],
[[ 0., 0., 0., 0., 1., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 1., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 1., 0.],
[ 0., 0., 0., 0., 0., 0., 0., 1.]]]])
>>> print idx_val.shape, out.shape
(1, 2, 4) (1, 2, 4, 8)
"""
flattened = inp_tensor.flatten()
z = T.zeros((flattened.shape[0], n_classes), dtype=theano.config.floatX)
one_hot = T.set_subtensor(z[T.arange(flattened.shape[0]), flattened], 1)
out_shape = [inp_tensor.shape[i] for i in xrange(inp_tensor.ndim)] + [n_classes]
one_hot = one_hot.reshape(out_shape)
return one_hot
评论列表
文章目录