我有一段来自S. Nikolenko的《深度学习》这本好书中的TensorFlow 1代码。
这是一个简单的线性回归,学习k
和b
分别为2和1。
%tensorflow_version 1.ximport numpy as np,tensorflow as tfimport pandas as pdn_samples, batch_size, num_steps = 1000, 100, 20000 #设置学习常量X_data = np.random.uniform(1, 10, (n_samples, 1)) #生成从1到10的数组,形状为(1000,1)print(X_data.shape)y_data = 2 * X_data + 1 + np.random.normal(0, 2, (n_samples, 1)) #生成正确答案并添加噪声(使其分散)X = tf.placeholder(tf.float32, shape=(batch_size, 1)) #定义占位符以放入session.runy = tf.placeholder(tf.float32, shape=(batch_size, 1))with tf.variable_scope('linear-regression'): k = tf.Variable(tf.random_normal((1, 1)), name='slope') #定义形状为(1,1)的2个变量 b = tf.Variable(tf.zeros((1,)), name='bias') #和形状为(1,) print(k.shape,b.shape)y_pred = tf.matmul(X, k) + b #批次中所有预测的y,表示线性公式k*x + bloss = tf.reduce_sum((y - y_pred) ** 2) #均方误差optimizer = tf.train.GradientDescentOptimizer(0.0001).minimize(loss)display_step = 100with tf.Session() as sess: sess.run(tf.initialize_variables([k,b])) for i in range(num_steps): indices = np.random.choice(n_samples, batch_size) #随机选择索引 X_batch, y_batch = X_data[indices], y_data[indices] #从生成的示例中获取x和y _, loss_val, k_val, b_val = sess.run([optimizer, loss, k, b ], feed_dict = { X : X_batch, y : y_batch }) if (i+1) % display_step == 0: print('Epoch %d: %.8f, k=%.4f, b=%.4f' % (i+1, loss_val, k_val, b_val))
我努力将其移植到TensorFlow 2上
长时间以来,我无法理解应该使用什么来代替sess.run()
和feed_dict
,它们在幕后做着神奇的事情,官方文档详细介绍了编写模型类的内容,但我希望尽可能保持简单平坦。
还建议使用tf.GradientTape
计算导数,但我很难将其正确应用到我的例子中
%tensorflow_version 2.ximport numpy as np,tensorflow as tfimport pandas as pdn_samples, batch_size, num_steps = 1000, 100, 200X_data = np.random.uniform(1, 10, (n_samples, 1))y_data = 2 * X_data + 1 + np.random.normal(0, 2, (n_samples, 1))X = tf.Variable(tf.zeros((batch_size, 1)), dtype=tf.float32, shape=(batch_size, 1))y = tf.Variable(tf.zeros((batch_size, 1)), dtype=tf.float32, shape=(batch_size, 1))k = tf.Variable(tf.random_normal((1, 1)), name='slope')b = tf.Variable(tf.zeros((1,)), name='bias')loss = lambda: tf.reduce_sum((y - (tf.matmul(X, k) + b)) ** 2)optimizer = tf.keras.optimizers.SGD(0.01).minimize(loss, [k, b, X, y])display_step = 100for i in range(num_steps): indices = np.random.choice(n_samples, batch_size) X_batch, y_batch = X_data[indices], y_data[indices]
我需要SGD优化器最小化给定的损失函数,并学习k和b的值,从这里我该如何实现?
回答:
在查阅了大量手册后,我明白了TensorFlow 1中sess.run
背后隐藏的内容,但没有优化器:
- 计算损失
- 计算相对于训练变量的梯度
- 调整每个训练变量的函数增长速度相对于学习率
- 为
k
和b
分配新值
X_batch, y_batch = X_data[indices], y_data[indices]X.assign(tf.convert_to_tensor(X_batch))y.assign(tf.convert_to_tensor(y_batch))with tf.GradientTape(persistent=True) as tape: loss_val = loss()dy_dk = tape.gradient(loss_val, k)dy_db = tape.gradient(loss_val, b)k.assign_sub(dy_dk * learn_rate)b.assign_sub(dy_db * learn_rate)if (i+1) % display_step == 0: print('Epoch %d: %.8f, k=%.4f, b=%.4f' % (i+1, loss_val, k.numpy(), b.numpy()))