gpt4 book ai didi

python - 创建运算矩阵张量

转载 作者:行者123 更新时间:2023-12-01 02:52:39 25 4
gpt4 key购买 nike

我正在尝试在 TensorFlow 中实现一种非线性滤波器,但我在实现一个步骤时遇到了麻烦。该步骤基本上是这样的:

x_update = x.assign(tf.matmul(A, x))

问题是矩阵A的结构如下:

A = [[1, 0.1, 0, 0, 0],
[0, 1, 0, 0, 0],
[0, 0, f1(x), f2(x), f3(x)],
[0, 0, f4(x), f5(x), f6(x)],
[0, 0, 0, 0, 1]]

其中每个fn(x)是我的状态的非线性函数;类似 tf.sin(x[4]) 甚至 x[2]**2 * tf.sin(x[4]) + x[3]**2 * tf .cos(x[4]).

我不知道如何创建我的 A 矩阵以嵌入这些操作。我首先用一些值初始化它:

A_mat = np.eye(5)
A_mat[0, 1] = 0.1
A = tf.Variable(A_mat, dtype=tf.float32, trainable=False, name='A')

然后我尝试使用 tf.scatter_update 进行一些切片更新,例如:

# Define my nonlinear operations.
f1 = tf.cos(...)
f2 = tf.sin(...)
# ...

# Define the part that I want to substitute.
new_part = tf.constant(tf.convert_to_tensor([[f1, f2, f3],
[f4, f5, f6]]))

# Define slice indices and update the matrix.
inds = [vals for vals in zip(np.arange(1, 3), np.arange(2, 5))]
A_update = tf.scatter_update(A, tf.constant(inds), new_part, name='A_update')

这给了我一个错误:

ValueError: Shapes must be equal rank, but are 1 and 0

From merging shape 1 with other shapes. for 'packed/0' (op: 'Pack') with input shapes: [1], [1], [], [], [], [].

我也尝试将我的矩阵 new_part 分配回 numpy 定义的 A_mat,但我收到了不同的错误,我认为这是由于意外的数据类型造成的当一个数值数组突然被分配张量元素时。

那么有人知道如何定义一个在像这样使用矩阵时更新的操作矩阵吗?

理想情况下,我想定义矩阵A,以便在A内更新的所有操作都是对A调用的一部分并自动发生。这样我就可以完全避免切片分配,而且感觉更像 TensorFlow-y。

谢谢!

<小时/>

更新:

我通过将操作包装在 tf.reshape(op_name, []) 中并将更新更改为:

new_part = tf.convert_to_tensor([[0, 0, f1, f2, f3],
[0, 0, f4, f5, f6]]))
rows = np.arange(start_row, end_row)
A_update = tf.scatter_update(A, rows, new_part, name='A_update')

事实证明tf.scatter_update只能对变量的第一个维度进行操作,因此我必须向其提供完整的行以及我想要放置它们的行索引。这有帮助,但仍然留下我的问题:

<小时/>

我的问题:

定义此矩阵的最佳、最符合 TensorFlow 风格的方法是什么,以便那些恒定的元素保持恒定,并且那些作为我的图上其他张量的运算的元素嵌入到A 本身就是这样吗?我希望在图表上调用 A 来检查并运行这些更新,而无需手动执行此 tf.scatter_update。或者这是正确的方法吗?

最佳答案

更新子矩阵的最简单方法是使用tensorflow的python切片操作。

import numpy as np
import tensorflow as tf
A = tf.Variable(np.zeros((5, 5), dtype=np.float32), trainable=False)
new_part = tf.ones((2,3))

update_A = A[2:4,2:5].assign(new_part)

sess = tf.InteractiveSession()
tf.global_variables_initializer().run()
print(update_A.eval())
# array([[ 0., 0., 0., 0., 0.],
# [ 0., 0., 0., 0., 0.],
# [ 0., 0., 1., 1., 1.],
# [ 0., 0., 1., 1., 1.],
# [ 0., 0., 0., 0., 0.]], dtype=float32)

关于python - 创建运算矩阵张量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44570632/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com