如何使用TensorFlow和鲍鱼数据集构建顺序模型?
可以使用Keras中的‘Sequential’方法构建顺序模型。此方法中指定了层数和类型。
阅读更多: 什么是TensorFlow以及Keras如何与TensorFlow一起创建神经网络?
我们将使用鲍鱼数据集,其中包含一组鲍鱼的测量值。鲍鱼是一种海螺。目标是根据其他测量值预测年龄。
我们使用Google Colaboratory来运行以下代码。Google Colab或Colaboratory帮助在浏览器上运行Python代码,无需任何配置,并可免费访问GPU(图形处理器)。Colaboratory构建在Jupyter Notebook之上。
print("The sequential model is being built") abalone_model = tf.keras.Sequential([ layers.Dense(64), layers.Dense(1) ]) abalone_model.compile(loss = tf.losses.MeanSquaredError(),optimizer = tf.optimizers.Adam()) print("The data is being fit to the model") abalone_model.fit(abalone_features, abalone_labels, epochs=10)
代码来源:https://tensorflowcn.cn/tutorials/load_data/csv
输出
The sequential model is being built The data is being fit to the model Epoch 1/10 104/104 [==============================] - 0s 963us/step - loss: 84.2213 Epoch 2/10 104/104 [==============================] - 0s 924us/step - loss: 16.0268 Epoch 3/10 104/104 [==============================] - 0s 860us/step - loss: 9.4125 Epoch 4/10 104/104 [==============================] - 0s 898us/step - loss: 8.9159 Epoch 5/10 104/104 [==============================] - 0s 912us/step - loss: 7.9076 Epoch 6/10 104/104 [==============================] - 0s 936us/step - loss: 6.8316 Epoch 7/10 104/104 [==============================] - 0s 992us/step - loss: 7.1021 Epoch 8/10 104/104 [==============================] - 0s 1ms/step - loss: 7.0550 Epoch 9/10 104/104 [==============================] - 0s 1ms/step - loss: 6.2762 Epoch 10/10 104/104 [==============================] - 0s 883us/step - loss: 6.5584 <tensorflow.python.keras.callbacks.History at 0x7fda82a35160>
解释
- 构建了一个回归模型来预测鲍鱼数据集的“年龄”列。
- 由于只有一个输入张量,因此构建了一个顺序模型。
- 编译(训练)模型,然后将特征和标签传递给“Model.fit”方法。
广告