Tensorflow 应用技术考试题目 一、实操题(100分) 1.实现获取fashion_mnist数据集,并对数据集归一化;(20分) 2.实现数据集的划分;(10分) 3.使用TensorFlow实现CNN神经网络构建, 其中:网络结构为2个隐层,每层进行2*2的最大池化;(30分) 4.构建损失函数;(15分) 5.实现模型训练,输出训练集损失、验证集损失及准确率(25分)
时间: 2023-12-30 16:03:06 浏览: 58
USPS_vs_MNIST.rar_MNIST_MNIST USPS_MNIST数据集_usps数据集介绍_usps数据集官网
1. 下载并导入fashion_mnist数据集,并对数据集进行归一化:
```python
from tensorflow.keras.datasets import fashion_mnist
from tensorflow.keras.utils import normalize
# 下载并加载数据集
(X_train, y_train), (X_test, y_test) = fashion_mnist.load_data()
# 对数据集进行归一化
X_train = normalize(X_train, axis=1)
X_test = normalize(X_test, axis=1)
```
2. 实现数据集的划分:
```python
from sklearn.model_selection import train_test_split
# 划分训练集和验证集
X_train, X_val, y_train, y_val = train_test_split(X_train, y_train, test_size=0.2, random_state=42)
```
3. 使用TensorFlow实现CNN神经网络构建:
```python
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout
# 构建模型
model = Sequential()
model.add(Conv2D(32, (3,3), activation='relu', input_shape=X_train.shape[1:]))
model.add(MaxPooling2D((2,2)))
model.add(Conv2D(64, (3,3), activation='relu'))
model.add(MaxPooling2D((2,2)))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(10, activation='softmax'))
```
4. 构建损失函数:
```python
from tensorflow.keras.losses import SparseCategoricalCrossentropy
# 使用SparseCategoricalCrossentropy作为损失函数
loss_fn = SparseCategoricalCrossentropy()
```
5. 实现模型训练并输出训练集损失、验证集损失及准确率:
```python
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.metrics import SparseCategoricalAccuracy
# 编译模型
model.compile(optimizer=Adam(learning_rate=0.001),
loss=loss_fn,
metrics=[SparseCategoricalAccuracy()])
# 训练模型
history = model.fit(X_train, y_train, batch_size=64, epochs=10, validation_data=(X_val, y_val))
# 输出训练集损失、验证集损失及准确率
train_loss, train_acc = model.evaluate(X_train, y_train)
val_loss, val_acc = model.evaluate(X_val, y_val)
print(f'Train Loss: {train_loss:.4f}, Train Accuracy: {train_acc:.4f}')
print(f'Val Loss: {val_loss:.4f}, Val Accuracy: {val_acc:.4f}')
```
阅读全文