手动实现线性回归梯度计算公式
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/020489e85936418d1e8cf7236c74d131.jpeg)
"""
X:m×n矩阵 -- m行样本n个维度
error: 列向量
"""
gradients = 1/m * tf.matmul(tf.transpose(X), error)
- 基于sklearn fetch_california_housing 数据集
import tensorflow as tf
import numpy as np
from sklearn.datasets import fetch_california_housing
from sklearn.preprocessing import StandardScaler
n_epochs = 36500
learning_rate = 0.001
housing = fetch_california_housing(data_home="../data/scikit_learn_data", download_if_missing=True)
scaler = StandardScaler().fit(housing_data_plus_bias)
scaled_housing_data_plus_bias = scaler.transform(housing_data_plus_bias)
X = tf.constant(scaled_housing_data_plus_bias, dtype=tf.float32, name='X')
y = tf.constant(housing.target.reshape(-1, 1), dtype=tf.float32, name='y')
theta = tf.Variable(tf.random_uniform([n + 1, 1], -1.0, 1.0), name='theta')
y_pred = tf.matmul(X, theta, name="predictions")
error = y_pred - y
rmse = tf.sqrt(tf.reduce_mean(tf.square(error), name="rmse"))
gradients = 2/m * tf.matmul(tf.transpose(X), error)
training_op = tf.assign(theta, theta - learning_rate * gradients)
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
for epoch in range(n_epochs):
if epoch % 100 == 0:
print("Epoch", epoch, "RMSE = ", rmse.eval())
sess.run(training_op)
best_theta = theta.eval()
print(best_theta)