使用梯度下降法优化线性回归模型参数Python代码
时间: 2023-06-03 10:06:28 浏览: 67
以下是使用梯度下降法优化线性回归模型参数的Python代码:
```python
import numpy as np
def gradient_descent(X, y, alpha=0.01, num_iters=1000):
m, n = np.shape(X)
theta = np.ones(n)
for i in range(num_iters):
h = np.dot(X, theta)
loss = h - y
gradient = np.dot(X.T, loss) / m
theta = theta - alpha * gradient
return theta
```
其中,X为训练数据的特征矩阵,y为训练数据的标签向量,alpha为学习率,num_iters为迭代次数。函数返回训练后得到的参数向量theta。
相关问题
使用梯度下降法优化线性回归模型参数并实现对波士顿房价进行预测python代码
以下是使用梯度下降法优化线性回归模型参数并实现对波士顿房价进行预测的 Python 代码:
```python
import numpy as np
from sklearn.datasets import load_boston
from sklearn.preprocessing import StandardScaler
# 加载波士顿房价数据集并进行标准化处理
boston = load_boston()
X = StandardScaler().fit_transform(boston.data)
y = boston.target.reshape(-1, 1)
# 定义梯度下降函数
def gradient_descent(X, y, theta, alpha, num_iters):
m = y.size
J_history = np.zeros(num_iters)
for i in range(num_iters):
h = X.dot(theta)
theta = theta - alpha * (1/m) * (X.T.dot(h-y))
J_history[i] = 1/(2*m) * np.sum((h-y)**2)
return (theta, J_history)
# 初始化模型参数
theta = np.zeros((X.shape[1]+1, 1))
alpha = 0.01
num_iters = 1000
# 在特征向量中加入偏置项
X = np.hstack((np.ones((X.shape[0], 1)), X))
# 调用梯度下降函数进行模型训练
theta, J_history = gradient_descent(X, y, theta, alpha, num_iters)
# 打印模型参数与损失值
print('模型参数:')
print(theta)
print('损失值:')
print(J_history[-1])
# 测试模型效果
test_data = StandardScaler().fit_transform(np.array([[0.1, 20, 6, 0, 0.4, 6, 50, 6, 4, 300, 16, 396, 20]]))
test_data = np.hstack((np.ones((1, 1)), test_data))
print('预测值:')
print(test_data.dot(theta))
```
注意:此代码仅供参考,真实数据建议根据实际情况进行调优和验证。
使用梯度下降法优化线性回归模型参数并实现波士顿房价的预测
好的,我们来一步一步实现使用梯度下降法优化线性回归模型参数并实现波士顿房价的预测。
首先,我们需要导入必要的库。在这个实例中,我们将使用 NumPy 和 Pandas 库。
```python
import numpy as np
import pandas as pd
```
接着,我们需要加载数据集。这里我们使用 Scikit-learn 库内置的波士顿房价数据集。
```python
from sklearn.datasets import load_boston
boston = load_boston()
X = boston.data
y = boston.target
```
数据集中的 X 是一个包含了 13 个特征的矩阵,而 y 则是一个包含 506 个样本的向量。
接下来,我们需要对数据进行预处理,包括对特征进行标准化处理和添加偏置项。
```python
# 标准化处理
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
X = scaler.fit_transform(X)
# 添加偏置项
X = np.concatenate([np.ones((X.shape[0], 1)), X], axis=1)
```
现在我们已经完成了数据预处理的步骤,接下来我们需要定义代价函数并使用梯度下降法来最小化代价函数。
```python
# 定义代价函数
def cost_function(X, y, theta):
m = len(y)
J = np.sum((X @ theta - y) ** 2) / (2 * m)
return J
# 定义梯度下降函数
def gradient_descent(X, y, theta, alpha, num_iters):
m = len(y)
J_history = np.zeros(num_iters)
for i in range(num_iters):
theta = theta - alpha * (X.T @ (X @ theta - y)) / m
J_history[i] = cost_function(X, y, theta)
return theta, J_history
```
在定义代价函数和梯度下降函数之后,我们需要初始化模型参数并调用梯度下降函数进行训练。
```python
# 初始化模型参数
theta = np.zeros(X.shape[1])
# 训练模型
alpha = 0.01
num_iters = 1000
theta, J_history = gradient_descent(X, y, theta, alpha, num_iters)
```
训练完成后,我们可以使用训练好的模型来预测新的房价。
```python
# 预测房价
X_new = np.array([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3])
X_new = (X_new - scaler.mean_) / scaler.scale_
X_new = np.concatenate([np.array([1]), X_new])
y_new = X_new @ theta
print(f"Predicted house price: ${y_new:.2f}")
```
以上就是使用梯度下降法优化线性回归模型参数并实现波士顿房价的预测的完整代码。