Tensorflow、py_func 或自定义函数

Tit*_*let 5 python neural-network tensorflow

我目前正在使用 Tensorflow 开发四元数神经网络(我想使用 GPU)。TensorFlow 不支持四元数,您可以将其表示为 4x4 实数矩阵,因此可以在 TensorFlow 中构建这样的神经网络。

有没有一种简单的方法来添加自定义操作或对张量进行自定义操作?

例如,我可以写:

output_activation = tf.nn.softmax(tf.matmul(hidden_activation, Weight_to_ouput))
Run Code Online (Sandbox Code Playgroud)

……这很酷!您所要做的就是添加一个损失函数,然后进行反向传播。但是,我想用四元数做同样的事情,例如:

output_activation = mySigmoid(myFunction(hidden_activation, Weight_to_output))
Run Code Online (Sandbox Code Playgroud)

但是,我需要将四元数转换为张量或将其转换为张量以优化 GPU 计算。所以我需要创建一个函数来获取一些张量作为参数并返回转换后的张量。我看过py_func,但似乎你不能返回张量。

我尝试了以下方法,但失败了:

def layerActivation(inputTensor,WeightTensor):
    newTensor = tf.matmul(inputTensor,WeightTensor)
    return newTensor
Run Code Online (Sandbox Code Playgroud)

...并在main()

x = placeholder ...
W_to_hidden = tf.Variable
test = tf.py_func(layerActivation, [x,_W_to_hidden], [tf.float32])

with tf.Session() as sess:
    tf.initialize_all_variables().run()
    king_return = sess.run(test, feed_dict={x: qtrain})
Run Code Online (Sandbox Code Playgroud)

错误:未实现:不支持的对象类型张量

理想情况下,我可以output_activation在 TensorFlow 的标准反向传播算法中使用它,但我不知道是否可行。

mrr*_*rry 4

根据所需的功能,您也许能够将操作实现为现有 TensorFlow 操作的组合,而无需使用tf.py_func().

例如,以下内容可以在 GPU 上运行:

def layer_activation(input_tensor, weight_tensor):
    return tf.matmul(input_tensor, weight_tensor)

# ...
x = tf.placeholder(...)
W_to_hidden = tf.Variable(...)
test = layer_activation(input_tensor, weight_tensor)
# ...
Run Code Online (Sandbox Code Playgroud)

使用的主要原因tf.py_func()是,如果您的操作无法使用 TensorFlow 操作来实现,并且您想要注入一些适用于张量实际值的 Python 代码(例如使用 NumPy)。

然而,如果您的mySigmoid()myFunction()操作无法用现有的 TensorFlow 操作来实现,并且您想在 GPU 上实现它们,那么 -正如 keveman 所说- 您将需要添加一个新的操作。