gpt4 book ai didi

python-3.x - 在 Tensorflow 中训练权重矩阵中的参数

转载 作者:行者123 更新时间:2023-12-02 04:21:33 24 4
gpt4 key购买 nike

我有一个神经网络。为简单起见,只有 层和权重矩阵的形状是 2-by-2 .我需要网络的输出是输入的旋转版本,即矩阵应该是有效的旋转矩阵。我尝试了以下方法:

def rotate(val):
w1 = tf.constant_initializer([[cos45, -sin45], [sin45, cos45]])
return tf.layers.dense(inputs=val, units=2, kernel_initializer=w1, activation=tf.nn.tanh)

在训练时,我不想失去旋转矩阵的属性。换句话说,我需要层仅估计矩阵中三角函数的角度(参数)。

我读到了 kernel_constraint可以通过标准化这些值在这方面提供帮助。但申请 kernel_constraint不保证对角线条目相等并且非对角线条目彼此为负(在这种情况下)。一般来说,需要满足的两个性质是,行列式应该是1和 R^T*R = I .

有没有其他方法可以实现这一目标?

最佳答案

您可以定义您的 custom Keras layer .类似的东西:

from tensorflow.keras.layers import Layer
import tensorflow as tf

class Rotate(Layer):
def build(self, input_shape):
sh = input_shape[0]
shape = [sh, sh]

# Initial weight matrix
w = self.add_weight(shape=shape,
initializer='random_uniform')

# Set upper diagonal elements to negative of lower diagonal elements
mask = tf.cast(tf.linalg.band_part(tf.ones(shape), -1, 0), tf.float32)
w = mask * w
w -= tf.transpose(w)

# Set the same weight to the diagonal
diag_mask = 1 - tf.linalg.diag(tf.ones(sh))
w = diag_mask * w
diag_w = self.add_weight(shape=(1,),
initializer='random_uniform')
diagonal = tf.linalg.diag(tf.ones(sh)) * diag_w
self.kernel = w + diagonal

def call(self, inputs, **kwargs):
return tf.matmul(inputs, self.kernel)

请注意,可学习权重矩阵 self.kernel有这方面的: [[D, -L], [L, D]]

关于python-3.x - 在 Tensorflow 中训练权重矩阵中的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59478023/

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