使用TensorFlow TF2.0对波士顿房价模型进行编程实现。
时间: 2024-05-07 17:23:44 浏览: 12
好的,下面是使用 TensorFlow 2.0 对波士顿房价进行编程实现的代码:
首先,我们需要导入所需的库和数据集:
```
import tensorflow as tf
from tensorflow import keras
from sklearn.datasets import load_boston
# 加载数据集
boston = load_boston()
# 获取特征和标签
features, labels = boston.data, boston.target
```
接下来,我们需要将数据集分为训练集和测试集:
```
from sklearn.model_selection import train_test_split
# 将数据集分为训练集和测试集
train_features, test_features, train_labels, test_labels = train_test_split(features, labels, test_size=0.2)
```
然后,我们需要定义一个模型并编译它:
```
# 定义模型
model = keras.Sequential([
keras.layers.Dense(64, activation='relu', input_shape=[train_features.shape[1]]),
keras.layers.Dense(64, activation='relu'),
keras.layers.Dense(1)
])
# 编译模型
model.compile(loss='mean_squared_error', optimizer=tf.keras.optimizers.RMSprop())
```
接下来,我们可以训练模型并评估其性能:
```
# 训练模型
history = model.fit(train_features, train_labels, epochs=100, validation_split=0.2)
# 评估模型
test_loss = model.evaluate(test_features, test_labels)
print('Test loss:', test_loss)
```
最后,我们可以使用模型对新数据进行预测:
```
# 对新数据进行预测
predictions = model.predict(test_features[0:5])
# 输出预测结果
print('Predictions:', predictions)
```
完整代码如下:
```
import tensorflow as tf
from tensorflow import keras
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
# 加载数据集
boston = load_boston()
# 获取特征和标签
features, labels = boston.data, boston.target
# 将数据集分为训练集和测试集
train_features, test_features, train_labels, test_labels = train_test_split(features, labels, test_size=0.2)
# 定义模型
model = keras.Sequential([
keras.layers.Dense(64, activation='relu', input_shape=[train_features.shape[1]]),
keras.layers.Dense(64, activation='relu'),
keras.layers.Dense(1)
])
# 编译模型
model.compile(loss='mean_squared_error', optimizer=tf.keras.optimizers.RMSprop())
# 训练模型
history = model.fit(train_features, train_labels, epochs=100, validation_split=0.2)
# 评估模型
test_loss = model.evaluate(test_features, test_labels)
print('Test loss:', test_loss)
# 对新数据进行预测
predictions = model.predict(test_features[0:5])
# 输出预测结果
print('Predictions:', predictions)
```