【TensorFlow】筆記:基礎(chǔ)知識(shí)-線(xiàn)性回歸預(yù)測(cè)房?jī)r(jià)
點(diǎn)擊上方“公眾號(hào)”可訂閱哦!
| 年份 | 2013 | 2014 | 2015 | 2016 | 2017 |
| 房?jī)r(jià) | 12000 | 14000 | 15000 | 16500 | 17500 |
我們使用numpy和TensorFlow分別對(duì)房?jī)r(jià)數(shù)據(jù)進(jìn)行回歸分析。
現(xiàn)在,我們希望通過(guò)對(duì)該數(shù)據(jù)進(jìn)行線(xiàn)性回歸,即使用線(xiàn)性模?a?和?b?是待求的參數(shù)。
01
Numpy下的線(xiàn)性回歸
在這里,我們使用 NumPy 這一通用的科學(xué)計(jì)算庫(kù)來(lái)實(shí)現(xiàn)梯度下降方法。NumPy 提供了多維數(shù)組支持,可以表示向量、矩陣以及更高維的張量。同時(shí),也提供了大量支持在多維數(shù)組上進(jìn)行操作的函數(shù)(比如下面的?np.dot()?是求內(nèi)積,?np.sum()?是求和)。
導(dǎo)入數(shù)據(jù),歸一化處理
import numpy as npX_raw = np.array([2013, 2014, 2015, 2016, 2017], dtype=np.float32)y_raw = np.array([12000, 14000, 15000, 16500, 17500], dtype=np.float32)X = (X_raw - X_raw.min()) / (X_raw.max() - X_raw.min())y = (y_raw - y_raw.min()) / (y_raw.max() - y_raw.min())
使用梯度下降法反復(fù)迭代
a, b = 0, 0num_epoch = 10000learning_rate = 5e-4for e in range(num_epoch):# 手動(dòng)計(jì)算損失函數(shù)關(guān)于自變量(模型參數(shù))的梯度y_pred = a * X + bgrad_a, grad_b = 2 * (y_pred - y).dot(X), 2 * (y_pred - y).sum()# 更新參數(shù)a, b = a - learning_rate * grad_a, b - learning_rate * grad_bprint(a, b)
輸出:
0.9763702027872221 0.05756498831137779602
TensorFlow下的線(xiàn)性回歸
X = tf.constant(X)y = tf.constant(y)a = tf.Variable(initial_value=0.)b = tf.Variable(initial_value=0.)variables = [a, b]num_epoch = 10000optimizer = tf.keras.optimizers.SGD(learning_rate=5e-4)for e in range(num_epoch):# 使用tf.GradientTape()記錄損失函數(shù)的梯度信息with tf.GradientTape() as tape:y_pred = a * X + bloss = tf.reduce_sum(tf.square(y_pred - y))# TensorFlow自動(dòng)計(jì)算損失函數(shù)關(guān)于自變量(模型參數(shù))的梯度grads = tape.gradient(loss, variables)# TensorFlow自動(dòng)根據(jù)梯度更新參數(shù)optimizer.apply_gradients(grads_and_vars=zip(grads, variables)print(a.numpy(), b.numpy())
輸出:
0.97637 0.057565063?END
掃碼關(guān)注
微信號(hào)|sdxx_rmbj
評(píng)論
圖片
表情
