十元最小多元函数

2024-04-26 22:15:10 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有以下几个变量函数的简单例子

@tf.function
def f(A, Y, X):
  AX = tf.matmul(A, X)
  norm = tf.norm(Y - AX)
  return norm

N = 2
A = tf.Variable(np.array([[1, 2], [3, 4]]))
Y = tf.Variable(np.identity(N))
X = tf.Variable(np.zeros((N, N)))

我如何找到用Tensorflow最小化f的{}? 我会对一个通用的解决方案感兴趣,当有一个以上声明的函数,当有一个以上的变量优化。在


Tags: 函数normreturntftensorflowdefnpzeros
2条回答

avanwyk基本上是正确的,不过请注意:1)为了简单起见,您可以直接使用优化器的^{}方法;2)如果您只想优化X,则应确保这是您要更新的唯一变量。在

import tensorflow as tf

@tf.function
def f(A, Y, X):
  AX = tf.matmul(A, X)
  norm = tf.norm(Y - AX)
  return norm

# Input data
N = 2
A = tf.Variable([[1., 2.], [3., 4.]], tf.float32)
Y = tf.Variable(tf.eye(N, dtype=tf.float32))
X = tf.Variable(tf.zeros((N, N), tf.float32))
# Initial function value
print(f(A, Y, X).numpy())
# 1.4142135

# Setup a stochastic gradient descent optimizer
opt = tf.keras.optimizers.SGD(learning_rate=0.01)
# Define loss function and variables to optimize
loss_fn = lambda: f(A, Y, X)
var_list = [X]
# Optimize for a fixed number of steps
for _ in range(1000):
    opt.minimize(loss_fn, var_list)

# Optimized function value
print(f(A, Y, X).numpy())
# 0.14933111

# Optimized variable
print(X.numpy())
# [[-2.0012102   0.98504114]
#  [ 1.4754106  -0.5111093 ]]

假设Tensorflow 2,可以使用Keras优化器:

@tf.function
def f(A, Y, X):
    AX = tf.matmul(A, X)
    norm = tf.norm(Y - AX)
    return norm

N = 2
A = tf.Variable(np.array([[1., 2.], [3., 4.]]))
Y = tf.Variable(np.identity(N))
X = tf.Variable(np.zeros((N, N)))

optimizer = tf.keras.optimizers.SGD()
for iteration in range(0, 100):
    with tf.GradientTape() as tape:
        loss = f(X, Y, X)
        print(loss)

    grads = tape.gradient(loss, [A, Y, X])
    optimizer.apply_gradients(zip(grads, [A, Y, X]))

print(A, Y, X)

这对任何可微函数都有效。对于不可微函数,可以参考其他优化技术(如遗传算法或群优化)。{a1}的实现有^。在

相关问题 更多 >