0

正如https://www.tensorflow.org/api_docs/python/tf/keras/optimizers/Optimizer?hl=en#minimize中所说, minmize 的第一个参数应该满足要求,

张量或可调用。如果是可调用的,损失应该不带参数并返回值以最小化。如果是张量,则必须传递磁带参数。

第一段代码将张量作为minimize()的输入,它需要梯度带,但我不知道怎么做。

第二段代码将callable函数作为minimize()的输入,很简单

import numpy as np
import tensorflow as tf
from tensorflow import keras

x_train = [1, 2, 3]
y_train = [1, 2, 3]

W = tf.Variable(tf.random.normal([1]), name='weight')
b = tf.Variable(tf.random.normal([1]), name='bias')
hypothesis = W * x_train + b


@tf.function
def cost():
    y_model = W * x_train + b
    error = tf.reduce_mean(tf.square(y_train - y_model))
    return error


optimizer = tf.optimizers.SGD(learning_rate=0.01)

cost_value = cost()
train = tf.keras.optimizers.Adam().minimize(cost_value, var_list=[W, b])

tf.print(W)
tf.print(b)

如何添加渐变胶带,我知道下面的代码肯定有效。

import numpy as np
import tensorflow as tf
from tensorflow import keras

x_train = [1, 2, 3]
y_train = [1, 2, 3]

W = tf.Variable(tf.random.normal([1]), name='weight')
b = tf.Variable(tf.random.normal([1]), name='bias')
hypothesis = W * x_train + b


@tf.function
def cost():
    y_model = W * x_train + b
    error = tf.reduce_mean(tf.square(y_train - y_model))
    return error


optimizer = tf.optimizers.SGD(learning_rate=0.01)

cost_value = cost()
train = tf.keras.optimizers.Adam().minimize(cost, var_list=[W, b])

tf.print(W)
tf.print(b)

请帮我修改第一段代码并让它运行,谢谢!

4

2 回答 2

1

这是因为 .minimize() 需要一个函数。而cost_value& cost(), 是一个 tf.Tensor 对象, cost 是一个 tf.function。您应该直接将损失函数传递给最小化 as tf.keras.optimizers.Adam().minimize(cost, var_list=[W, b])

渐变部分的更改:

train = tf.keras.optimizers.Adam().minimize(cost(), var_list=[W, b],tape=tf.GradientTape())
于 2021-08-22T09:42:41.783 回答
0

这是一个较晚的答案(Hakan 基本上是为你得到的),但我写这篇文章是希望它能帮助未来那些被困并在谷歌上搜索这个确切问题的人(就像我一样)。这也是直接使用 tf.GradientTape() 的替代实现。

import numpy as np
import tensorflow as tf
from tensorflow import keras

x_train = [1, 2, 3]
y_train = [1, 2, 3]

W = tf.Variable(tf.random.normal([1]), trainable = True, name='weight')
b = tf.Variable(tf.random.normal([1]), trainable = True, name='bias')

@tf.function
def cost(W, b):
    y_model = W * x_train + b
    error = tf.reduce_mean(tf.square(y_train - y_model))
    return error


optimizer = tf.optimizers.SGD(learning_rate=0.01)

trainable_vars = [W,b]

epochs = 100 #(or however many iterations you want it to run)
for _ in range(epochs):
    with tf.GradientTape() as tp:
        #your loss/cost function must always be contained within the gradient tape instantiation
        cost_fn = cost(W, b)
    gradients = tp.gradient(cost_fn, trainable_vars)
    optimizer.apply_gradients(zip(gradients, trainable_vars))

tf.print(W)
tf.print(b)

这应该会在您运行的 epoch 数之后为您提供权重和偏差的值。

每次调用新的梯度磁带时,您都必须计算损失函数。然后你得到你的损失函数的梯度,然后调用 optimizer.apply_gradient 根据 tensorflow 文档在这里所说的进行最小化:https ://www.tensorflow.org/api_docs/python/tf/keras/optimizers/Optimizer#应用梯度

你可以做的一个修改(虽然除了一个简单的最小化任务之外它在任何事情上都不可行):如果你指定一个容差,你可以使它成为一个while循环而不是for循环,放置一些巨大的时期,指定一个容差损失(一些epsilon > 0,基本上是0),直到你获得低于容差的损失。

于 2021-12-02T02:07:49.000 回答