{"id":94,"date":"2023-12-19T05:50:43","date_gmt":"2023-12-19T05:50:43","guid":{"rendered":"https:\/\/www.cutexyz.com\/edu\/mlearning2309\/?p=94"},"modified":"2023-12-19T05:50:46","modified_gmt":"2023-12-19T05:50:46","slug":"2023-09-26-%e8%aa%b2%e7%a8%8b%e8%a3%9c%e5%85%85%e8%b3%87%e6%96%99-week-03-2-2-2-3-2","status":"publish","type":"post","link":"https:\/\/www.cutexyz.com\/edu\/mlearning2309\/?p=94","title":{"rendered":"2023-12-19 \u8ab2\u7a0b\u88dc\u5145\u8cc7\u6599 Week 15"},"content":{"rendered":"\n<p>Demo Project<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>\u624b\u5beb\u8fa8\u8b58\u7cfb\u7d71 by MNIST<\/li>\n<\/ol>\n\n\n\n<pre class=\"wp-block-code has-white-color has-black-background-color has-text-color has-background\"><code>\nimport os\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# plt.rcParams&#91;'figure.figsize'] = (7, 7)  # Make the figures a bit bigger\n\nfrom keras.datasets import mnist\nfrom keras.models import Sequential\nfrom keras.layers.core import Dense, Dropout, Activation\nfrom keras.utils import np_utils\nfrom keras.models import load_model\n\nnb_classes = 10\n\n(train_images, train_labels), (test_images, test_labels) = mnist.load_data()\nprint(\"train_images original shape\", train_images.shape)\nprint(\"train_labels original shape\", train_labels.shape)\n\nfrom keras import models\nfrom keras import layers\nfrom keras.utils import to_categorical\n\nmodeFileName = \".\/model_by_me.h5\"\nif (os.path.exists(modeFileName)):\n    network = load_model(modeFileName)\n    print(\"Read the previous model\")\n    fix_test_images = test_images.reshape((10000, 28 * 28)).astype('float32') \/ 255\n    fix_test_labels = to_categorical(test_labels)\n\n    test_loss, test_acc = network.evaluate(fix_test_images, fix_test_labels)\n    print('test_loss:', test_loss)\n    print('test_acc:', test_acc)\nelse:\n    network = models.Sequential()\n    print(\"Start to build the fresh model\")\n\n    # Hidden layer\n    network.add(layers.Dense(512, activation='relu', input_shape=(28 * 28,)))\n\n    # Output layer\n    network.add(layers.Dense(10, activation='softmax'))\n\n    network.compile(optimizer='rmsprop',  # \u512a\u5316\u5668\u9078\u64c7\n                    loss='categorical_crossentropy',  # \u640d\u5931\u51fd\u6578\n                    metrics=&#91;'accuracy'])  # \u7528\u6e96\u78ba\u5ea6\u505a\u8a55\u91cf\n\n    fix_train_images = train_images.reshape((60000, 28 * 28)).astype('float32') \/ 255\n    fix_train_labels = to_categorical(train_labels)\n\n    fix_test_images = test_images.reshape((10000, 28 * 28)).astype('float32') \/ 255\n    fix_test_labels = to_categorical(test_labels)\n\n    result = network.fit(\n        fix_train_images,  # training data\n        fix_train_labels,  # \u6b63\u78ba\u7b54\u6848\n        epochs=12,  # \u4ee3\u8868\u8981\u8dd1\u5e7e\u6b21\n        batch_size=128,  # \u6bcf\u6b21\u8a13\u7df4\u4f7f\u7528\u5e7e\u7b46\u8cc7\u6599, \u6240\u4ee5 60000 \/128 \u7d04\u7b49\u65bc 469 \u7d44\n        validation_data=(fix_test_images, fix_test_labels))\n\n    test_loss, test_acc = network.evaluate(fix_test_images, fix_test_labels)\n    print('test_loss:', test_loss)\n    print('test_acc:', test_acc)\n\n    # \u5132\u5b58 model\n    network.save('model_by_me.h5')  # creates a HDF5 file 'model_by_me.h5'\n\n    # for draw chart, \u756b\u51fa\u5b78\u7fd2\u66f2\u7dda by \u6e96\u78ba\u7387\n    history_dict = result.history\n    loss_values = history_dict&#91;'loss']\n    val_loss_values = history_dict&#91;'val_loss']\n    epochs = range(1, len(loss_values) + 1)\n\n    plt.clf()\n    acc = history_dict&#91;'accuracy']\n    val_acc = history_dict&#91;'val_accuracy']\n\n    plt.plot(epochs, acc, 'bo', label='Training acc')\n    plt.plot(epochs, val_acc, 'b', label='Validation acc')\n    plt.title('Training and validation accuracy')\n    plt.xlabel('Epochs')\n    plt.ylabel('Accuracy')\n    plt.legend()\n    plt.show()\n\n# \u67e5\u770b\u8f38\u51fa\u7d50\u679c\n# predicted_classes = models.predict_classes(test_images)\n# predict_x = network.predict(test_images)\npredicted_classes = network.predict(fix_test_images)\npredicted_classes = np.argmax(predicted_classes, axis=1)\ncorrect_indices = np.nonzero(predicted_classes == test_labels)&#91;0]\nincorrect_indices = np.nonzero(predicted_classes != test_labels)&#91;0]\nplt.figure()\nfor i, correct in enumerate(correct_indices&#91;:9]):\n    plt.subplot(3, 3, i + 1)\n    plt.imshow(test_images&#91;correct].reshape(28, 28), cmap='gray', interpolation='none')\n    plt.title(\"Predicted {}, Class {}\".format(predicted_classes&#91;correct], test_labels&#91;correct]))\nplt.tight_layout()\nplt.show()\nplt.figure()\nfor i, incorrect in enumerate(incorrect_indices&#91;:9]):\n    plt.subplot(3, 3, i + 1)\n    plt.imshow(test_images&#91;incorrect].reshape(28, 28), cmap='gray', interpolation='none')\n    plt.title(\"Predicted {}, Class {}\".format(predicted_classes&#91;incorrect], test_labels&#91;incorrect]))\nplt.tight_layout()\nplt.show()\n\n<\/code><\/pre>\n\n\n\n<p><br><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Demo Project<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"site-container-style":"default","site-container-layout":"default","site-sidebar-layout":"default","disable-article-header":"default","disable-site-header":"default","disable-site-footer":"default","disable-content-area-spacing":"default","footnotes":""},"categories":[4],"tags":[],"class_list":["post-94","post","type-post","status-publish","format-standard","hentry","category-4"],"_links":{"self":[{"href":"https:\/\/www.cutexyz.com\/edu\/mlearning2309\/index.php?rest_route=\/wp\/v2\/posts\/94","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.cutexyz.com\/edu\/mlearning2309\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.cutexyz.com\/edu\/mlearning2309\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.cutexyz.com\/edu\/mlearning2309\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.cutexyz.com\/edu\/mlearning2309\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=94"}],"version-history":[{"count":1,"href":"https:\/\/www.cutexyz.com\/edu\/mlearning2309\/index.php?rest_route=\/wp\/v2\/posts\/94\/revisions"}],"predecessor-version":[{"id":95,"href":"https:\/\/www.cutexyz.com\/edu\/mlearning2309\/index.php?rest_route=\/wp\/v2\/posts\/94\/revisions\/95"}],"wp:attachment":[{"href":"https:\/\/www.cutexyz.com\/edu\/mlearning2309\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=94"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.cutexyz.com\/edu\/mlearning2309\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=94"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.cutexyz.com\/edu\/mlearning2309\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=94"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}