使用tf.optimizers.Adam.minimize()时,对象不可调用。

问题描述 投票:0回答:1
我是tensorflow(2.0)的新手,所以我想通过简单的线性回归来简化。我有以下代码,但我不知道为什么它是错误的。

我已经尝试过使用文档,但到目前为止我还没有答案。

x = np.random.normal(loc=10., scale = 0.1, size=170) y = np.repeat(10.,170) a_init = tf.random_normal_initializer() a = tf.Variable(initial_value=a_init(shape = [1], dtype = 'float32'),trainable=True) pred = tf.multiply(a,x) loss = tf.nn.l2_loss(pred-y) optim = tf.optimizers.Adam(lr = 0.002) entreno = optim.minimize(loss, [a])

我收到以下错误,

Traceback (most recent call last) <ipython-input-45-e1a191781d0a> in <module> 2 loss = tf.nn.l2_loss(pred-y) 3 optim = tf.optimizers.Adam(lr = 0.002) ----> 4 entreno = optim.minimize(loss, [a]) TypeError: 'tensorflow.python.framework.ops.EagerTensor' object is not callable

如果有帮助,我有一个tensorflow 1代码:

import tensorflow import numpy as np tf = tensorflow.compat.v1 x = np.random.normal(loc=1.,scale=0.1, size = 220) y = np.repeat(14.37,220) tf.disable_eager_execution() x_d = tf.placeholder(shape = [1], dtype=tf.float32) y_t = tf.placeholder(shape = [1], dtype = tf.float32) A = tf.Variable(tf.random_normal(shape=[1])) my_pred = tf.multiply(A,x_d) loss = tf.square(my_pred-y_t) optim = tf.train.GradientDescentOptimizer(learning_rate=0.02) train_step = optim.minimize(loss) init = tf.global_variables_initializer() session = tf.Session() session.run(init) for _ in range(241): idx = np.random.choice(220) ranx = [x[idx]] rany = [y[idx]] session.run(train_step, feed_dict ={x_d : ranx, y_t : rany}) if _%20 == 0: print("A = {}, Loss : {}".format(session.run(A), session.run(loss, feed_dict={x_d:ranx, y_t:rany})))

我是tensorflow(2.0)的新手,所以我想通过简单的线性回归来简化。我有以下代码,但我不知道为什么它是错误的。我已经尝试过文档,但到目前为止我还没有...
python tensorflow machine-learning regression linear-regression
1个回答
0
投票
Tensorflow提供了有关如何精确执行此操作的指南:https://www.tensorflow.org/guide/eager但是代码是
© www.soinside.com 2019 - 2024. All rights reserved.