用tensorflow2创建一个完整5层的神经网络,输入层的特征数量是463,输出层的标签数量是5,激活函数可以自定义relue或sigmoid ,要防止过拟合,每训练100次打印成本,并且打印出训练样本集的准确率和测试集的准确率,把代码写出来
时间: 2024-05-12 22:17:34 浏览: 28
tensorflow建立一个简单的神经网络的方法
好的,以下是代码:
```python
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
# 加载数据
(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
# 将像素值进行归一化
x_train, x_test = x_train / 255.0, x_test / 255.0
# 定义模型
model = keras.models.Sequential([
layers.Flatten(input_shape=(28, 28)),
layers.Dense(128, activation="relu"),
layers.Dropout(0.2),
layers.Dense(64, activation="relu"),
layers.Dropout(0.2),
layers.Dense(10, activation="softmax")
])
# 编译模型
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
# 训练模型
history = model.fit(x_train, y_train, epochs=5, validation_data=(x_test, y_test))
# 打印成本和准确率
for epoch, history in enumerate(history.history['loss']):
if epoch % 100 == 0:
cost = history.history['loss'][epoch]
accuracy_train = history.history['accuracy'][epoch]
accuracy_test = history.history['val_accuracy'][epoch]
print("Epoch: {}, Cost: {:.3f}, Train Accuracy: {:.4f}, Test Accuracy: {:.4f}"
.format(epoch, cost, accuracy_train, accuracy_test))
```
希望能够满足您的需求。
阅读全文