Jua*_*ang 6 theano keras tensorflow
我正在keras中实现一个操作,这样它就可以同时处理theano和tensorflow后端.假设操作的输入是:
array([[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11]], dtype=int64)
Run Code Online (Sandbox Code Playgroud)
那么它的输出应该是:
array([[ 0, 1, 2, 3, 4, 5],
[ 3, 4, 5, 0, 1, 2],
[ 6, 7, 8, 9, 10, 11],
[ 9, 10, 11, 6, 7, 8]], dtype=int64)
Run Code Online (Sandbox Code Playgroud)
我的代码如下:
from keras import backend as K
def pairreshape(x,target_dim,input_shape):
x1, x2 = x[0::2,], x[1::2,]
x1_concate = K.concatenate((x1,x2), axis=target_dim)
x2_concate = K.concatenate((x2,x1), axis=target_dim)
if K.image_dim_ordering() == 'th':
import theano.tensor as T
x_new = T.repeat(x,2,axis=target_dim)
x_new = T.set_subtensor(x_new[0::2], x1_concate)
x_new = T.set_subtensor(x_new[1::2], x2_concate)
elif K.image_dim_ordering() == 'tf':
import tensorflow as tf
repeats = [1] * len(input_shape)
repeats[target_dim] = 2
x_new = tf.tile(x, repeats)
x_new[0::2] = x1_concate #TypeError: 'Tensor' object does not support item assignment
x_new[1::2] = x2_concate #TypeError: 'Tensor' object does not support item assignment
Run Code Online (Sandbox Code Playgroud)
我已经成功实现了theano,但我无法弄清楚如何通过tensorflow分配张量.tensorflow中最后两行张量分配将报告错误.张量流中是否有T.set_subtensor等价?或者你能否推荐一个更好的操作实施?谢谢.
TensorFlow 张量是只读的。为了修改你需要使用变量和.assign
(=不能在Python中被覆盖)
tensor = tf.Variable(tf.ones((3,3)))
sess.run(tf.initialize_all_variables())
sess.run(tensor[1:, 1:].assign(2*tensor[1:,1:]))
print(tensor.eval())
Run Code Online (Sandbox Code Playgroud)
输出
[[ 1. 1. 1.]
[ 1. 2. 2.]
[ 1. 2. 2.]]
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1795 次 |
最近记录: |