作者:huangpeishan49 | 来源:互联网 | 2024-12-22 19:56
本教程详细介绍了如何使用TensorFlow2.0构建和训练多层感知机(MLP)网络,涵盖回归和分类任务。通过具体示例和代码实现,帮助初学者快速掌握TensorFlow的核心概念和操作。
1. 使用 TensorFlow 2.0 构建基础 MLP 网络
本文基于 TensorFlow 2.0 官方文档和个人学习笔记整理而成,提供中文讲解,适合喜欢阅读中文教程的读者。完整代码可以在 GitHub 仓库 中找到。
2. 回归任务实例
我们将使用波士顿房价数据集进行回归任务的演示:
# 导入数据
(x_train, y_train), (x_test, y_test) = keras.datasets.boston_housing.load_data()
print(x_train.shape, ' ', y_train.shape)
print(x_test.shape, ' ', y_test.shape)
# 构建模型
model = keras.Sequential([
layers.Dense(32, activation='sigmoid', input_shape=(13,)),
layers.Dense(32, activation='sigmoid'),
layers.Dense(32, activation='sigmoid'),
layers.Dense(1)
])
# 配置模型
model.compile(optimizer=keras.optimizers.SGD(0.1),
loss='mean_squared_error',
metrics=['mse'])
model.summary()
# 训练模型
model.fit(x_train, y_train, batch_size=50, epochs=50, validation_split=0.1, verbose=1)
# 评估模型
result = model.evaluate(x_test, y_test)
print(model.metrics_names)
print(result)
3. 分类任务实例
接下来,我们使用乳腺癌数据集进行二分类任务的演示:
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
whole_data = load_breast_cancer()
x_data = whole_data.data
y_data = whole_data.target
x_train, x_test, y_train, y_test = train_test_split(x_data, y_data, test_size=0.3, random_state=7)
print(x_train.shape, ' ', y_train.shape)
print(x_test.shape, ' ', y_test.shape)
# 构建模型
model = keras.Sequential([
layers.Dense(32, activation='relu', input_shape=(30,)),
layers.Dense(32, activation='relu'),
layers.Dense(1, activation='sigmoid')
])
# 配置模型
model.compile(optimizer=keras.optimizers.Adam(),
loss=keras.losses.binary_crossentropy,
metrics=['accuracy'])
model.summary()
# 训练模型
model.fit(x_train, y_train, batch_size=64, epochs=10, verbose=1)
# 评估模型
model.evaluate(x_test, y_test)
print(model.metrics_names)
参考:buomsoo-kim/Easy-deep-learning-with-Keras