使用TensorFlow框架来建立模型
时间: 2024-01-10 11:04:37 浏览: 28
好的,那么我们需要先导入必要的库,包括TensorFlow和NumPy等:
```python
import tensorflow as tf
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
```
接下来,我们需要读入数据集。假设数据集文件的路径为`./boston_house_prices.csv`,那么可以使用如下代码读入数据:
```python
data = pd.read_csv('./boston_house_prices.csv')
```
接下来,我们需要对数据集进行预处理,包括数据清洗、特征选择、特征缩放等。在此处,我们选择使用所有的特征,并对每个特征进行最小-最大缩放。具体实现如下:
```python
# 选择所有特征作为输入
x_data = data.iloc[:, :-1].values
# 对每个特征进行最小-最大缩放
x_min = np.min(x_data, axis=0)
x_max = np.max(x_data, axis=0)
x_data = (x_data - x_min) / (x_max - x_min)
# 选择房价作为输出
y_data = data.iloc[:, -1].values.reshape(-1, 1)
# 对房价进行最小-最大缩放
y_min = np.min(y_data, axis=0)
y_max = np.max(y_data, axis=0)
y_data = (y_data - y_min) / (y_max - y_min)
```
接下来,我们需要将数据集分为训练集和测试集。在此处,我们选择将数据集的前80%作为训练集,剩余的20%作为测试集。
```python
# 将数据集分为训练集和测试集
train_size = int(len(x_data) * 0.8)
train_x, train_y = x_data[:train_size], y_data[:train_size]
test_x, test_y = x_data[train_size:], y_data[train_size:]
```
接下来,我们需要定义模型。在此处,我们选择使用多元线性回归模型。具体实现如下:
```python
# 定义模型
class LinearRegression:
def __init__(self):
self.W = tf.Variable(tf.zeros([13, 1]))
self.b = tf.Variable(tf.zeros([1]))
def __call__(self, x):
return tf.matmul(x, self.W) + self.b
model = LinearRegression()
```
接下来,我们需要定义损失函数和优化器。在此处,我们选择使用均方误差作为损失函数,使用梯度下降法作为优化器。具体实现如下:
```python
# 定义损失函数和优化器
def mse_loss(y_pred, y_true):
return tf.reduce_mean(tf.square(y_pred - y_true))
optimizer = tf.optimizers.SGD(learning_rate=0.01)
```
接下来,我们需要定义训练函数。具体实现如下:
```python
# 定义训练函数
def train(model, x, y, optimizer):
with tf.GradientTape() as tape:
y_pred = model(x)
loss = mse_loss(y_pred, y)
gradients = tape.gradient(loss, [model.W, model.b])
optimizer.apply_gradients(zip(gradients, [model.W, model.b]))
return loss
```
接下来,我们开始训练模型。具体实现如下:
```python
# 训练模型
num_epochs = 1000
train_losses = []
for epoch in range(num_epochs):
train_loss = train(model, train_x, train_y, optimizer)
train_losses.append(train_loss)
if epoch % 100 == 0:
print(f"Epoch [{epoch}/{num_epochs}], Loss: {train_loss:.4f}")
```
训练完成后,我们可以得到模型的参数。具体实现如下:
```python
# 得到模型的参数
W = model.W.numpy().reshape(-1)
b = model.b.numpy()[0]
# 对参数进行反缩放
W = W * (y_max - y_min) / (x_max - x_min)
b = b * (y_max - y_min) + y_min
```
接下来,我们可以使用测试集来评估模型的表现。具体实现如下:
```python
# 使用测试集来评估模型表现
test_pred = model(test_x).numpy()
test_pred = test_pred * (y_max - y_min) + y_min
test_loss = mse_loss(test_pred, test_y).numpy()
print(f"Test Loss: {test_loss:.4f}")
```
最后,我们可以绘制出拟合结果图示。具体实现如下:
```python
# 绘制拟合结果图示
plt.figure()
plt.plot(train_losses)
plt.xlabel("Epoch")
plt.ylabel("Loss")
plt.title("Training Loss")
plt.show()
plt.figure()
plt.plot(test_y, label="Ground Truth")
plt.plot(test_pred, label="Prediction")
plt.xlabel("Sample")
plt.ylabel("Price")
plt.title("Prediction vs Ground Truth")
plt.legend()
plt.show()
plt.figure()
plt.bar(range(len(W)), W)
plt.xticks(range(len(W)), data.columns[:-1], rotation=45)
plt.title("Feature Importance")
plt.show()
```
这样,我们就可以得到模型的拟合结果和特征重要性了。完整的代码如下:
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)