019/DeepLearning

/1.11 作业/1.11作业.py
# 1.12 作业

1.12.1 代码实现

1.12.1.1 预处理数据

1.12.1.1.1 数据预处理

1.12.1.1.2 数据可视化

1.12.1.2 搭建卷积神经网络

1.12.1.2.1 构建模型

1.12.1.2.2 训练模型

1.12.1.2.3 验证模型

1.12.1.3 数据预处理

1.12.1.4 搭建卷积神经网络

1.12.1.5 模型评估

1.12.1.2.3 验证模型

1.12.1.2.3.1 验证集准确性

1.12.1.2.3.2 验证模型

1.12 代码实现

1.12.1 预处理数据

#### 1.12.1.1 数据预处理

在本次作业中,我们使用Keras库来搭建卷积神经网络模型。首先我们需要对数据进行预处理。

##### 1.12.1.1.1 数据预处理

数据预处理包括数据标准化和归一化。在本案例中,我们将使用归一化的方法对数据进行预处理。首先,我们需要将数据读入Python中,然后对数据进行归一化处理,将所有像素值归一到[0, 1]之间。归一化可以防止网络的权重过大或者过小,使网络收敛速度变慢。在归一化过程中,我们需要先计算数据的均值和方差,然后使用公式进行归一化。代码如下���

```python
import numpy as np
from keras.models import Sequential
from keras.layers import Dense, Conv2D, MaxPooling2D, Flatten
from keras.utils import to_categorical
import matplotlib.pyplot as plt

# 加载数据
(x_train, y_train), (x_test, y_test) = np.load('./data.npy', allow_pickle=True)

# 归一化数据
x_train = x_train.astype('float32') / 255.0
x_test = x_test.astype('float32') / 255.0

# 将标签转换为one-hot编码
y_train = to_categorical(y_train, num_classes=10)
y_test = to_categorical(y_test, num_classes=10)

print(x_train.shape, y_train.shape)
print(x_test.shape, y_test.shape)
```

在上述代码中,我们首先使用`np.load`函数加载数据,然后将数据的像素值归一到[0, 1]之间。接着,我们将标签转换为one-hot编码格式,以便于后续的分类任务。最后,我们输出了训练集和测试集的形状。

##### 1.12.1.1.2 数据可视化

为了更好地理解数据,我们可以使用matplotlib库来绘制一些数据点。在本案例中,我们将绘制部分训练集中的图像,并将其标签展示出来。代码如下:

```python
# 数据可视化
def show_images_labels_predictions(images, labels, predictions, num=10):
plt.figure(figsize=(20, 4))
for i in range(num):
ax = plt.subplot(1, num, i + 1)
ax.imshow(images[i].reshape(28, 28), cmap='Greys_r')

# 显示标签
ax.set_title(f"{i + 1} - {labels[i]}")

# 显示预测结果
if predictions is None:
ax.set_xlabel("No Prediction")
else:
ax.set_xlabel(f"Predict: {predictions[i]}")

ax.set_xticks([])
ax.set_yticks([])

plt.tight_layout()
plt.show()

show_images_labels_predictions(x_train[:10], y_train[:10], None)
```

在上述代码中,我们定义了一个名为`show_images_labels_predictions`的函数,用于绘制训练集中的部分图像及其标签。我们将前10张图像及其标签展示出来,并使用`ax.set_xlabel`函数来展示预测结果。最后,我们使用`plt.show`函数来显示图像。

1.12.2 搭建卷积神经网络

#### 1.12.2.1 构建模型

在构建模型时,我们将使用Sequential类来构建模型。首先,我们将添加一个卷积层,然后添加一个池化层,接着添加一个全连接层。最后,我们将添加一个输出层。代码如下:

```python
# 构建模型
model = Sequential()

# 添加卷积层
model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=x_train.shape[1:]))

# 添加池化层
model.add(MaxPooling2D(pool_size=(2, 2)))

# 添加全连接层
model.add(Flatten())
model.add(Dense(128, activation='relu'))

# 添加输出层
model.add(Dense(10, activation='softmax'))

model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
```

在上述代码中,我们首先定义了一个Sequential类的实例`model`。然后,我们添加了一个卷积层和一个池化