手写波士顿房价梯度房价代码
时间: 2023-11-12 19:04:26 浏览: 91
波士顿房价预测代码pyspark-python-sklearn
4星 · 用户满意度95%
好的,以下是手写的波士顿房价梯度下降代码:
```python
import numpy as np
from sklearn.datasets import load_boston
# 加载数据集
boston = load_boston()
X = boston.data
y = boston.target
# 特征缩放
mu = np.mean(X, axis=0)
sigma = np.std(X, axis=0)
X = (X - mu) / sigma
# 初始化参数
n_features = X.shape[1]
theta = np.zeros(n_features + 1)
# 添加一列全为1的特征
X = np.hstack([np.ones((X.shape[0], 1)), X])
# 定义损失函数
def mse_loss(X, y, theta):
m = X.shape[0]
y_pred = np.dot(X, theta)
loss = np.sum((y_pred - y) ** 2) / (2 * m)
return loss
# 定义梯度下降函数
def gradient_descent(X, y, theta, alpha, num_iters):
m = X.shape[0]
for i in range(num_iters):
y_pred = np.dot(X, theta)
error = y_pred - y
grad = np.dot(X.T, error) / m
theta -= alpha * grad
loss = mse_loss(X, y, theta)
print(f"iteration:{i}, loss:{loss}")
return theta
# 训练模型
alpha = 0.01
num_iters = 1000
theta = gradient_descent(X, y, theta, alpha, num_iters)
# 预测
X_test = np.array([0.1, 0.2, 0.3, 4.4, 0.5, 6.6, 7.7, 0.8, 0.9, 1.0, 2.2, 3.3, 4.4])
X_test = (X_test - mu) / sigma
X_test = np.hstack([1, X_test])
y_pred = np.dot(X_test, theta)
print(f"Predicted house price: {y_pred}")
```
以上代码中,首先加载波士顿房价数据集,然后进行特征缩放和添加一列全为1的特征。接着定义了损失函数和梯度下降函数,最后使用梯度下降算法训练模型,并进行预测。
阅读全文