1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
| import json import gzip import paddle from paddle.vision.transforms import Normalize from paddle.io import Dataset import matplotlib.pyplot as plt import numpy as np from PIL import Image import numpy as np from PIL import Image from paddle.vision.transforms import functional as F
transform = Normalize(mean=[127.5], std=[127.5], data_format='CHW')
class MNISTDataset(Dataset):
def __init__(self, datafile, mode='train', transform=None):
super().__init__()
self.mode = mode self.transform = transform
print('loading mnist dataset from {} ......'.format(datafile))
data = json.load(gzip.open(datafile)) print('mnist dataset load done')
train_set, val_set, eval_set = data
if mode == 'train': self.imgs, self.labels = train_set[0], train_set[1] elif mode == 'valid': self.imgs, self.labels = val_set[0], val_set[1] elif mode == 'test': self.imgs, self.labels = eval_set[0], eval_set[1] else: raise Exception("mode can only be one of ['train', 'valid', 'test']")
def __getitem__(self, index): """ 实现__getitem__方法,定义指定index时如何获取数据 """ data = self.imgs[index] label = self.labels[index]
return self.transform(data), label
def __len__(self): """ 实现__len__方法,返回数据集总数目 """ return len(self.imgs)
datafile = 'D:/paddlepaddle/paddlepaddle手写数字/mnist.json.gz'
train_dataset = MNISTDataset(datafile, mode='train', transform=transform) test_dataset = MNISTDataset(datafile, mode='test', transform=transform)
train_loader = paddle.io.DataLoader(train_dataset, batch_size=64, shuffle=True, num_workers=0) test_loader = paddle.io.DataLoader(test_dataset, batch_size=64, shuffle=False, num_workers=0)
class MNIST_CNN(paddle.nn.Layer): def __init__(self): super(MNIST_CNN, self).__init__()
self.conv1 = paddle.nn.Conv2D(in_channels=1, out_channels=16, kernel_size=3, stride=1, padding=1) self.pool1 = paddle.nn.MaxPool2D(kernel_size=2, stride=2)
self.conv2 = paddle.nn.Conv2D(in_channels=16, out_channels=32, kernel_size=3, stride=1, padding=1) self.pool2 = paddle.nn.MaxPool2D(kernel_size=2, stride=2)
self.fc_input_dim = 32 * 7 * 7
self.fc1 = paddle.nn.Linear(in_features=self.fc_input_dim, out_features=128) self.fc2 = paddle.nn.Linear(in_features=128, out_features=10)
def forward(self, inputs): x = paddle.to_tensor(inputs) x = paddle.reshape(x, [-1, 1, 28, 28]) x = self.conv1(x) x = paddle.nn.functional.relu(x) x = self.pool1(x)
x = self.conv2(x) x = paddle.nn.functional.relu(x) x = self.pool2(x)
x = paddle.flatten(x, start_axis=1)
x = self.fc1(x) x = paddle.nn.functional.relu(x) x = self.fc2(x)
return x
model = MNIST_CNN()
def train(model): print('train:') model.train() opt = paddle.optimizer.Adam(learning_rate=0.001, parameters=model.parameters()) EPOCH_NUM = 40 total_losses = [] for epoch_id in range(EPOCH_NUM): print('epoch:', epoch_id) for batch_id, data in enumerate(train_loader()): images, labels = data images = paddle.to_tensor(images).astype('float32') labels = paddle.to_tensor(labels).astype('float32')
images = paddle.reshape(images, [images.shape[0], images.shape[2] * images.shape[3]])
predicts = model(images) labels_int = paddle.cast(labels, dtype='int64')
labels_onehot = paddle.nn.functional.one_hot(labels_int, num_classes=10)
loss = paddle.nn.functional.square_error_cost(predicts, labels_onehot) avg_loss = paddle.mean(loss)
probs = paddle.nn.functional.softmax(predicts, axis=1) predictions = paddle.argmax(probs, axis=1) correct = paddle.sum(paddle.cast(paddle.equal(predictions, labels_int), dtype='float32')) accuracy = correct / images.shape[0] * 100
if batch_id % 200 == 0: print("epoch: {}, batch: {}, loss is: {}, accuracy is: {}".format(epoch_id, batch_id, avg_loss.numpy(), accuracy.numpy()))
avg_loss.backward() opt.step() opt.clear_grad() total_losses.append(avg_loss.numpy())
plt.plot(total_losses) plt.xlabel('Batch') plt.ylabel('Loss') plt.title('Training Loss Curve') plt.ylim(0, 0.1) plt.show()
print("create model:")
train(model)
paddle.save(model.state_dict(), 'C:/Users/lxcqm/Desktop/model/modelhn.pdmodel') print("模型保存成功,模型参数保存在C:/Users/lxcqm/Desktop/model/modelhn.pdmodel")
model_dict = paddle.load('C:/Users/lxcqm/Desktop/model/modelhn.pdmodel') model.load_dict(model_dict) model.eval()
test_loader = paddle.io.DataLoader(test_dataset, batch_size=64, shuffle=False, num_workers=0)
for batch_id, data in enumerate(test_loader): images, labels = data images = paddle.to_tensor(images).astype('float32') labels = paddle.to_tensor(labels).astype('float32')
images = paddle.reshape(images, [images.shape[0], images.shape[2] * images.shape[3]])
predicts = model(images) test_dataset = paddle.vision.datasets.MNIST(mode='test') test_data0 = np.array(test_dataset[batch_id][0]) test_label_0 = np.array(test_dataset[batch_id][1])
plt.figure(figsize=(2, 2)) plt.imshow(test_data0, cmap=plt.cm.binary) plt.axis('on') plt.title('image') plt.show()
break
predicts_np = predicts.numpy() labels_np = labels.numpy()
print("预测各标签概率:") print(predicts_np[0]) print("实际标签:", labels_np[0])
predictions = np.array(predicts_np[0])
predicted_label = np.argmax(predictions)
print("模型认为概率最高的标签是:", predicted_label)
total_accuracy = 0.0 total_samples = 0 for batch_id, data in enumerate(test_loader()): images, labels = data images = paddle.to_tensor(images).astype('float32') labels = paddle.to_tensor(labels).astype('float32')
images = paddle.reshape(images, [images.shape[0], images.shape[2] * images.shape[3]])
predicts = model(images) labels_int = paddle.cast(labels, dtype='int64')
labels_onehot = paddle.nn.functional.one_hot(labels_int, num_classes=10)
loss = paddle.nn.functional.square_error_cost(predicts, labels_onehot) avg_loss = paddle.mean(loss)
probs = paddle.nn.functional.softmax(predicts, axis=1) predictions = paddle.argmax(probs, axis=1) correct = paddle.sum(paddle.cast(paddle.equal(predictions, labels_int), dtype='float32')) accuracy = correct / images.shape[0] * 100
if batch_id % 10 == 0: print(" batch: {}, loss is: {}, accuracy is: {}".format( batch_id, avg_loss.numpy(), accuracy.numpy())) total_accuracy += accuracy.numpy() * images.shape[0] total_samples += images.shape[0]
accuracy_total = total_accuracy / total_samples
print("- Total Accuracy: {:.5f}%".format(accuracy_total))
|