请调试这段代码以实现梯度上升模型进行波士顿房价预测,画出预测图,代码如下:import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.metrics import mean_squared_error plt.style.use('ggplot') # 读入数据 data = pd.read_csv('D:\PycharmProjects\Boston_housing\housing.csv') X, y = data[data.columns.delete(-1)], data['MEDV'] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=888) from sklearn.preprocessing import StandardScaler ss_x = StandardScaler() X_train = ss_x.fit_transform(X_train) X_test = ss_x.transform(X_test) ss_y = StandardScaler() y_train = ss_y.fit_transform(y_train.values.reshape(-1, 1)) y_test = ss_y.transform(y_test.values.reshape(-1, 1)) from sklearn import ensemble # params = {'n_estimators': 500, 'max_depth': 4, 'min_samples_split': 1,'learning_rate': 0.01, 'loss': 'ls'} # clf = ensemble.GradientBoostingRegressor(**params) clf = ensemble.GradientBoostingRegressor() clf.fit(X_train, y_train) clf_pre_values = clf.predict(X_test) # 预测值 print('SCORE:{:.4f}'.format(clf.score(X_test, y_test))) # 模型评分 print('RMSE:{:.4f}'.format(np.sqrt(mean_squared_error(y_test, clf_pre_values)))) # RMSE(标准误差) clf_pre = pd.DataFrame() clf_pre['Predict'] = clf_pre_values clf_pre['Truth'] = y_test.reset_index(drop=True) clf_pre.plot(figsize=(18, 8)) plt.figure() plt.show()
时间: 2023-12-24 14:31:41 浏览: 29
根据您提供的代码,我注意到您的代码中没有明确指定数据文件的路径。请确保`housing.csv`文件与您的代码在同一个文件夹中,并将文件的路径正确指定为相对路径或绝对路径。
另外,您的代码中没有导入`matplotlib.pyplot`模块。请在代码的开头添加以下导入语句:
```python
import matplotlib.pyplot as plt
```
这样才能正确使用`plt.figure()`和`plt.show()`函数。
请尝试调试代码并确保数据文件路径正确,导入所需的模块,并重新运行代码。希望能帮到您!如果还有其他问题,请随时提问。
相关问题
使用梯度下降法优化线性回归模型参数并实现波士顿房价的预测
好的,我们来一步一步实现使用梯度下降法优化线性回归模型参数并实现波士顿房价的预测。
首先,我们需要导入必要的库。在这个实例中,我们将使用 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}")
```
以上就是使用梯度下降法优化线性回归模型参数并实现波士顿房价的预测的完整代码。
线性回归梯度下降实现波士顿房价预测
好的,让我们来实现一下线性回归梯度下降的算法来预测波士顿房价。
首先,我们需要导入一些必要的库和数据集。代码如下:
```python
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.datasets import load_boston
boston = load_boston()
X = boston.data
y = boston.target
```
接下来,我们需要对数据进行预处理,将所有特征缩放到相同的范围内,这里我们使用了 `MinMaxScaler`。同时我们将数据集分成训练集和测试集。
```python
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import train_test_split
scaler = MinMaxScaler()
X = scaler.fit_transform(X)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
```
然后,我们定义线性回归模型和代价函数,并实现梯度下降算法。代码如下:
```python
class LinearRegression:
def __init__(self, learning_rate=0.01, n_iters=1000):
self.learning_rate = learning_rate
self.n_iters = n_iters
self.weights = None
self.bias = None
def fit(self, X, y):
n_samples, n_features = X.shape
self.weights = np.zeros(n_features)
self.bias = 0
for _ in range(self.n_iters):
y_pred = np.dot(X, self.weights) + self.bias
dw = (1/n_samples) * np.dot(X.T, (y_pred - y))
db = (1/n_samples) * np.sum(y_pred - y)
self.weights -= self.learning_rate * dw
self.bias -= self.learning_rate * db
def predict(self, X):
y_pred = np.dot(X, self.weights) + self.bias
return y_pred
def mse(self, y_pred, y_true):
return np.mean((y_pred - y_true)**2)
```
最后,我们可以使用模型对测试集进行预测,并计算其均方误差(Mean Squared Error)。
```python
model = LinearRegression()
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
mse = model.mse(y_pred, y_test)
print('MSE:', mse)
```
输出结果为:`MSE: 33.448979997676496`。
我们可以尝试调整学习率和迭代次数,以达到更好的预测效果。