使用Boston房价数据,训练一个一元线性模型
import tensorflow
as tf
import matplotlib
.pyplot
as plt
Boston_housing数据已经集成到Tensorflow2中了,第一次使用会自动进行下载
boston
= tf
.keras
.datasets
.boston_housing
(x_train
, y_train
), (x_test
, y_test
) = boston
.load_data
()
Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/boston_housing.npz
57344/57026 [==============================] - 1s 9us/step
查看x_train的数据类型和维度
type(x_train
)
numpy.ndarray
x_train
.shape
(404, 13)
选择x_train中的第5列数据作为训练数据集x;y_train作为训练数据集y。
绘制了x和y的散点图:
plt
.scatter
(x_train
[:,5], y_train
)
<matplotlib.collections.PathCollection at 0x27ea78eb6d0>
数据格式转换:x_train 和 y_train是numpy.ndarray类型,需要转换为tensor类型。
x
= tf
.constant
(x_train
[:,5])
type(x
)
tensorflow.python.framework.ops.EagerTensor
y
= tf
.constant
(y_train
)
type(y
)
tensorflow.python.framework.ops.EagerTensor
模型训练
通过 tf.keras.Sequential() 实例化一个model
model
= tf
.keras
.Sequential
()
通过 model.add() 向模型中添加层,这里先定义了输入数据是一个一维的。
model
.add
(tf
.keras
.Input
(shape
=(1,)))
向model中添加一个全连接层,定义输出的数据是一维的。
model
.add
(tf
.keras
.layers
.Dense
(1))
通过 summary() 查看model的信息
model
.summary
()
Model: "sequential"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
dense (Dense) (None, 1) 2
_________________________________________________________________
dense_1 (Dense) (None, 1) 2
=================================================================
Total params: 4
Trainable params: 4
Non-trainable params: 0
_________________________________________________________________
编译model,定义优化器为adam,损失函数为mse
model
.compile(optimizer
='adam',
loss
='mse'
)
history
= model
.fit
(x
, y
, epochs
=5000)
Epoch 1/5000
13/13 [==============================] - 0s 599us/step - loss: 647.3615
Epoch 2/5000
13/13 [==============================] - 0s 460us/step - loss: 642.5150
Epoch 3/5000
13/13 [==============================] - 0s 586us/step - loss: 637.8333
Epoch 4/5000
13/13 [==============================] - 0s 614us/step - loss: 633.3293
Epoch 5/5000
13/13 [==============================] - 0s 537us/step - loss: 628.9990
Epoch 6/5000
13/13 [==============================] - 0s 767us/step - loss: 624.8962
Epoch 7/5000
13/13 [==============================] - 0s 614us/step - loss: 620.8807
Epoch 8/5000
13/13 [==============================] - 0s 426us/step - loss: 617.1241
Epoch 9/5000
13/13 [==============================] - 0s 614us/step - loss: 613.4361
预测
model
.predict
(tf
.constant
([12]))
array([[72.69166]], dtype=float32)