{"id":15501,"date":"2024-11-23T17:07:12","date_gmt":"2024-11-23T09:07:12","guid":{"rendered":"https:\/\/www.orczhou.com\/?p=15501"},"modified":"2025-12-26T17:36:22","modified_gmt":"2025-12-26T09:36:22","slug":"build-a-image-classification-neural-network-from-scratch","status":"publish","type":"post","link":"https:\/\/www.orczhou.com\/index.php\/2024\/11\/build-a-image-classification-neural-network-from-scratch\/","title":{"rendered":"\u4ece\u96f6\u6784\u5efa\u56fe\u7247\u8bc6\u522b\u7684\u795e\u7ecf\u7f51\u7edc"},"content":{"rendered":"\n\n\n\n<p style=\"margin-top:2px\">\u66f4\u8fdb\u4e00\u6b65\uff0c\u672c\u6587\u5c06\u4ece\u96f6\u6784\u5efa\u4e00\u4e2a\u6d45\u5c42\u7684\u524d\u9988\u795e\u7ecf\u7f51\u7edc\uff0c\u5b9e\u73b0\u624b\u5199\u6570\u5b570\u548c1\u7684\u8bc6\u522b\u3002\u793a\u4f8b\u624b\u5199\u6570\u5b57\u5982\u4e0b\u56fe\u6240\u793a\u3002\u6574\u4f53\u5b9e\u73b0\u5305\u62ec\u6570\u636e\u9884\u5904\u7406\u3001\u53c2\u6570\u521d\u59cb\u5316\u3001forward\/backword propagation\u3001\u8bad\u7ec3\u4e0e\u9884\u6d4b\u3002<\/p>\n\n\n\n<div class=\"wp-block-columns is-layout-flex wp-container-core-columns-is-layout-28f84493 wp-block-columns-is-layout-flex\">\n<div class=\"wp-block-column is-layout-flow wp-block-column-is-layout-flow\">\n<figure class=\"wp-block-image aligncenter size-full is-resized\"><img loading=\"lazy\" decoding=\"async\" width=\"28\" height=\"28\" src=\"https:\/\/www.orczhou.com\/wp-content\/uploads\/2024\/11\/image-27.png\" alt=\"\" class=\"wp-image-16072\" style=\"width:100px\"\/><\/figure>\n<\/div>\n\n\n\n<div class=\"wp-block-column is-layout-flow wp-block-column-is-layout-flow\">\n<figure class=\"wp-block-image aligncenter size-full is-resized\"><img loading=\"lazy\" decoding=\"async\" width=\"28\" height=\"28\" src=\"https:\/\/www.orczhou.com\/wp-content\/uploads\/2024\/11\/image-28.png\" alt=\"\" class=\"wp-image-16073\" style=\"width:100px\"\/><\/figure>\n<\/div>\n\n\n\n<div class=\"wp-block-column is-layout-flow wp-block-column-is-layout-flow\">\n<figure class=\"wp-block-image aligncenter size-full is-resized\"><img loading=\"lazy\" decoding=\"async\" width=\"28\" height=\"28\" src=\"https:\/\/www.orczhou.com\/wp-content\/uploads\/2024\/11\/image-31.png\" alt=\"\" class=\"wp-image-16076\" style=\"width:100px\"\/><\/figure>\n<\/div>\n\n\n\n<div class=\"wp-block-column is-layout-flow wp-block-column-is-layout-flow\">\n<figure class=\"wp-block-image aligncenter size-full is-resized\"><img loading=\"lazy\" decoding=\"async\" width=\"28\" height=\"28\" src=\"https:\/\/www.orczhou.com\/wp-content\/uploads\/2024\/11\/image-30.png\" alt=\"\" class=\"wp-image-16075\" style=\"width:100px\"\/><\/figure>\n<\/div>\n\n\n\n<div class=\"wp-block-column is-layout-flow wp-block-column-is-layout-flow\">\n<figure class=\"wp-block-image aligncenter size-full is-resized\"><img loading=\"lazy\" decoding=\"async\" width=\"28\" height=\"28\" src=\"https:\/\/www.orczhou.com\/wp-content\/uploads\/2024\/11\/image-32.png\" alt=\"\" class=\"wp-image-16077\" style=\"width:100px\"\/><\/figure>\n<\/div>\n<\/div>\n\n\n\n<h4 class=\"wp-block-heading\">\u95ee\u9898\u63cf\u8ff0<\/h4>\n\n\n\n<p>\u4f7f\u7528 Python \uff0c\u4f46\u4e0d\u4f7f\u7528\u4efb\u4f55\u6df1\u5ea6\u5b66\u4e60\u6846\u67b6\uff0c\u7f16\u5199\u4e00\u4e2a\u6d45\u5c42\u7684\u795e\u7ecf\u7f51\u7edc\u5b9e\u73b0\uff0c\u8bc6\u522b MNIST \u6570\u636e\u96c6\u4e2d\u7684\u624b\u5199\u6570\u5b57 0 \u548c 1\u3002<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">\u524d\u7f6e\u77e5\u8bc6<\/h4>\n\n\n\n<ul class=\"wp-block-list\">\n<li>\u719f\u6089Python \u3001NumPy\u7684\u4f7f\u7528<\/li>\n\n\n\n<li>\u4e86\u89e3\u795e\u7ecf\u7f51\u7edc\u7684\u8868\u793a\u4e0eforward propagation<\/li>\n\n\n\n<li>\u4e86\u89e3 backward propagation<\/li>\n\n\n\n<li>\u4e86\u89e3 MNIST \u6570\u636e\u96c6<\/li>\n<\/ul>\n\n\n\n<h4 class=\"wp-block-heading\">\u6570\u636e\u8bf4\u660e<\/h4>\n\n\n\n<p>\u8fd9\u91cc\u7684\u624b\u5199\u6570\u5b57\u4f7f\u7528\u4e86\u6570\u636e\u96c6 MNIST\uff0c\u8be5\u6570\u636e\u96c6\u6709\u7740\u673a\u5668\u5b66\u4e60\u754c\u7684\u201c\u679c\u8747\u201d\u4e4b\u79f0\u3002\u91cc\u9762\u5305\u542b\u4e86\u5927\u91cf\u7ecf\u8fc7\u9884\u5904\u7406\u7684\u624b\u5199\u6570\u5b57\uff0c\u8fd9\u91cc\u9009\u62e9\u5176\u4e2d\u6807\u8bb0\u4e3a0\u62161\u7684\u56fe\u7247\u8fdb\u884c\u8bad\u7ec3\u3002\u5e76\u4f7f\u7528\u5bf9\u5e94\u7684\u6d4b\u8bd5\u96c6\uff0c\u9a8c\u8bc1\u8bad\u7ec3\u7684\u795e\u7ecf\u7f51\u7edc\u7684\u6548\u679c\u3002<\/p>\n\n\n\n<p>\u8fd9\u91cc\u53d6\u4e00\u5f20 MNIST \u4e2d\u7684\u56fe\u7247\uff0c\u4ee5\u53ca\u5bf9\u5e94\u7684\u50cf\u7d20\u6570\u636e\uff0c\u4ee5\u5e2e\u52a9\u76f4\u89c2\u7406\u89e3\u5176\u4e2d\u7684\u6570\u636e\u3002MNIST \u4e2d\u7684\u56fe\u7247\u6570\u636e\u53ef\u4ee5\u7406\u89e3\u4e3a\u4e00\u4e2a\u5982\u4e0b\u7684 28*28 \u7684\u6570\u7ec4\uff0c\u5176\u6240\u4ee3\u8868\u7684\u56fe\u7247\u4e5f\u5982\u4e0b\u56fe\u6240\u793a\uff1a<\/p>\n\n\n\n<div class=\"wp-block-columns is-layout-flex wp-container-core-columns-is-layout-28f84493 wp-block-columns-is-layout-flex\">\n<div class=\"wp-block-column is-layout-flow wp-block-column-is-layout-flow\" style=\"flex-basis:66.66%\">\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"498\" src=\"https:\/\/www.orczhou.com\/wp-content\/uploads\/2024\/11\/image-24-1024x498.png\" alt=\"\" class=\"wp-image-15996\" srcset=\"https:\/\/www.orczhou.com\/wp-content\/uploads\/2024\/11\/image-24-1024x498.png 1024w, https:\/\/www.orczhou.com\/wp-content\/uploads\/2024\/11\/image-24-300x146.png 300w, https:\/\/www.orczhou.com\/wp-content\/uploads\/2024\/11\/image-24-768x374.png 768w, https:\/\/www.orczhou.com\/wp-content\/uploads\/2024\/11\/image-24-1536x748.png 1536w, https:\/\/www.orczhou.com\/wp-content\/uploads\/2024\/11\/image-24.png 1730w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n<\/div>\n\n\n\n<div class=\"wp-block-column is-layout-flow wp-block-column-is-layout-flow\" style=\"flex-basis:33.33%\">\n<div style=\"height:40px\" aria-hidden=\"true\" class=\"wp-block-spacer\"><\/div>\n\n\n\n<figure class=\"wp-block-image aligncenter size-full is-resized\"><img loading=\"lazy\" decoding=\"async\" width=\"28\" height=\"28\" src=\"https:\/\/www.orczhou.com\/wp-content\/uploads\/2024\/11\/image-25.png\" alt=\"\" class=\"wp-image-15997\" style=\"width:180px\"\/><\/figure>\n<\/div>\n<\/div>\n\n\n\n<p>\u66f4\u4e3a\u5177\u4f53\u7684\uff0c\u6570\u7ec4\u4e2d\u7684\u6bcf\u4e00\u4e2a\u6570\u503c\u4ee3\u8868\u4e86\u56fe\u7247\u4e2d\u7684\u67d0\u4e2a\u50cf\u7d20\u7684\u7070\u5ea6\u503c\uff0c0\u4ee3\u8868\u9ed1\u8272\uff0c255\u4ee3\u8868\u767d\u8272\uff0c\u8fd9\u4e4b\u95f4\u7684\u503c\u5219\u4ee3\u8868\u4ecb\u4e8e\u4e4b\u95f4\u7684\u7070\u8272\u3002<\/p>\n\n\n\n<p>MNIST \u539f\u59cb\u6570\u636e\u53ef\u4ee5\u5728\uff1a<a href=\"https:\/\/yann.lecun.com\/exdb\/mnist\/\">\u201cTHE MNIST DATABASE of handwritten digits\u201d<\/a>\u9875\u9762\u83b7\u53d6\u3002\u4e5f\u53ef\u4ee5\u76f4\u63a5\u4f7f\u7528 Python \u4e2d\u6a21\u5757<code>keras.datasets<\/code>\u83b7\u53d6\u3002\u672c\u7a0b\u5e8f\u4f7f\u7528\u540e\u8005\u65b9\u5f0f\u83b7\u53d6\u3002<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">\u5b9e\u73b0\u6982\u8ff0<\/h4>\n\n\n\n<p>\u8fd9\u91cc\u7684\u4f7f\u7528\u4e86\u4e24\u5c42\u795e\u7ecf\u7f51\u7edc\uff0c\u5373\u4e00\u4e2a\u9690\u85cf\u5c42\uff0c\u4e00\u4e2a\u8f93\u51fa\u5c42\uff0c\u56e0\u4e3a\u8fd9\u662f\u4e8c\u5206\u7c7b\u95ee\u9898\uff0c\u6240\u4ee5\u8f93\u51fa\u5c42\u4f7f\u7528logistic\u51fd\u6570\uff0c\u800c\u9690\u85cf\u5c42\u5219\u4f7f\u7528\u4e86 ReLU \u4f5c\u4e3a\u6fc0\u6d3b\u51fd\u6570\u3002\u9690\u85cf\u5c42\u7684\u795e\u7ecf\u5143\u662f\u4e00\u4e2a\u52a8\u6001\u53c2\u6570\uff08\u8d85\u53c2\u6570\uff09\uff0c\u5728\u6d4b\u8bd5\u65f6\uff0c\u53ef\u4ee5\u8c03\u6574\u4e3a10~300\u4e4b\u95f4\u4e0d\u7b49\u3002\u8f93\u5165\u5c42\u5219\u662f\uff0cMNIST \u7684\u56fe\u7247\uff0c\u4e5f\u5c31\u662f\u4e00\u4e2a28*28\u4e2a\u6570\u7ec4\u3002<\/p>\n\n\n\n<p>\u8fd9\u91cc\u4f7f\u7528\u4e86\u6700\u4e3a\u57fa\u7840\u7684Gradient Descent\u7b97\u6cd5\uff0c\u6709\u65f6\u5019\u4e5f\u88ab\u79f0\u4e3aBatch Gradient Descent\u3002<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">\u6570\u636e\u9884\u5904\u7406<\/h4>\n\n\n\n<p>\u5728 Python \u4e2d\u53ef\u4ee5\u4f7f\u7528 <code>keras.datasets<\/code>\u6a21\u5757\u4fbf\u6377\u7684\u83b7\u53d6 MNIST \u7684\u6570\u636e\u96c6\u3002\u8fd9\u91cc\u7f16\u5199\u4e86\u4e00\u4e2a\u7b80\u5355\u7684\u51fd\u6570\uff0c\u5c06\u8be5\u6570\u636e\u96c6\u4e2d0\u548c1\u76f8\u5173\u7684\u56fe\u7247\u7b5b\u9009\u51fa\u6765\uff0c\u7136\u540e\u5c06\u6570\u7ec4\u7684\u7ef4\u5ea6\uff0c\u8f6c\u5316\u4e3a\u9700\u8981\u7684\u7ef4\u5ea6\u3002\u4f8b\u5982\uff0c\u671f\u671b\u7684\u8f93\u5165\u6570\u7ec4\u7684\u7ef4\u5ea6\u4e3a\\( (n^{[0]},m) \\)\uff0c\u5176\u4e2d \\( n^{[0]} \\) \u8868\u793a\u8f93\u5165\u7684\u7279\u6027\uff08feature\uff09\u6570\u91cf\uff0c\u8fd9\u91cc\u4e5f\u5c31\u662f 784\uff08\u537328*28\uff09\uff0c\\( m \\)\u8868\u793a\u6837\u672c\u4e2a\u6570\u3002<\/p>\n\n\n\n<p>\u5177\u4f53\u4ee3\u7801\u5982\u4e0b\uff1a<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"python\" class=\"language-python\"># return only data lable 0 or 1 from MNIST for the binary classification\ndef filter_mnist_data(data_X, data_y):\n    data_filter = np.where((data_y == 0) | (data_y == 1))\n    filtered_data_X, filtered_data_y = data_X[data_filter], data_y[data_filter]\n    r_data_X = filtered_data_X.reshape(filtered_data_X.shape[0],filtered_data_X.shape[1]*filtered_data_X.shape[2])\n    return (r_data_X, filtered_data_y)\n\n(train_all_X, train_all_y), (test_all_X, test_all_y) = mnist.load_data()\n(train_X,train_y) = filter_mnist_data(train_all_X, train_all_y)\n(test_X ,test_y ) = filter_mnist_data(test_all_X, test_all_y)\n\nX  = train_X.T\nY  = train_y.reshape(1,train_y.shape[0])<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">\u8d85\u53c2\u6570\u7684\u914d\u7f6e<\/h4>\n\n\n\n<p>\u8be5\u7a0b\u5e8f\u6d89\u53ca\u7684\u8d85\u53c2\u6570\uff08hyper-parameter\uff09\u5305\u62ec\uff1a\u9690\u85cf\u5c42\u795e\u7ecf\u5143\u4e2a\u6570 \\(n_1 = 10 \\)\u3001\u5b66\u4e60\u7387 \\( \\alpha = 0.5 \\)\u3001\u8fed\u4ee3\u6b21\u6570\u7b49\u3002<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"python\" class=\"language-python\"># hyper-parameter; read the comments above for structure of the NN\nn0 = X.shape[0]   # number of input features\nn1 = 10           # nerons of the hidden layer\nn2 = 1            # nerons of the output layer\niteration_count = 500\nlearning_rate   = 0.5<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">feature scaling\u548c\u53c2\u6570\u521d\u59cb\u5316<\/h4>\n\n\n\n<p>\u4e3a\u4e86\u589e\u52a0\u8bad\u7ec3\u7684\u901f\u5ea6\uff0c\u8fd9\u91cc\u5bf9\u8f93\u5165\u8fdb\u884c\u4e86\u201c\u6807\u51c6\u5316\u201d\uff0c\u5c06\u6240\u6709\u7684\u6570\u636e\uff0c\u5f52\u4e00\u5316\u4e3a\u5747\u503c\u4e3a0\u3001\u65b9\u5dee\u4e3a1\u7684\u6570\u636e\u96c6\u3002\u5177\u4f53\u7684\u6b65\u9aa4\u5982\u4e0b\uff1a<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"python\" class=\"language-python\"># feature scaling \/ Normalization\nmean = np.mean(X,axis = 1,keepdims = True)\nstd  = np.std( X,axis = 1,keepdims = True)+0.000000001\nX  = (X-mean)\/std<\/code><\/pre>\n\n\n\n<p>\u6ce8\u610f\uff1a\u5b9e\u73b0\u8fc7\u7a0b\u4e2d\u9700\u8981\u6ce8\u610f\u7684\u662f\uff0c\u5982\u679c\u5bf9\u8f93\u5165\u8fdb\u884c\u4e86\u6807\u51c6\u5316\uff0c\u90a3\u4e48\u5728\u9884\u6d4b\u65f6\u4e5f\u9700\u8981\u5bf9\u9884\u6d4b\u7684\u8f93\u5165\u8fdb\u884c\u76f8\u540c\u7684\u5f52\u4e00\u5316\u3002\u6240\u4ee5\u8fd9\u91cc\u7684\u5747\u503c\u548c\u65b9\u5dee\uff0c\u9700\u8981\u8bb0\u5f55\u4e0b\u6765\uff0c\u4ee5\u5907\u540e\u7eed\u4f7f\u7528\u3002\u8fd9\u91cc\u7ed9\u65b9\u5dee\u989d\u5916\u52a0\u4e86\u4e00\u4e2a\u975e\u5e38\u5c0f\u7684\u6570\u5b57\uff0c\u4e00\u822c\u662f\u6ca1\u6709\u5fc5\u8981\u7684\uff0c\u8fd9\u91cc\u662f\u4e3a\u4e86\u9632\u6b62\u8f93\u5165\u6570\u636e\u5168\u90e8\u90fd\u76f8\u540c\uff0c\u5373\u65b9\u5dee\u4e3a0\u3002<\/p>\n\n\n\n<p>\u6b64\u5916\uff0c\u4e3a\u4e86\u589e\u52a0\u8bad\u7ec3\u7684\u901f\u5ea6\uff0c\u4e5f\u53c2\u8003\u4e1a\u754c\u901a\u7528\u505a\u6cd5\uff0c\u5bf9\u8f93\u5165\u4e5f\u8fdb\u884c\u4e86\u968f\u673a\u521d\u59cb\u5316\uff0c\u5177\u4f53\u5982\u4e0b\uff1a<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"python\" class=\"language-python\"># initial parameters: W1 W2 b1 b2 size\nnp.random.seed(561)\nW1 = np.random.randn(n1,n0)*0.01\nW2 = np.random.randn(n2,n1)*0.01\nb1 = np.zeros([n1,1])\nb2 = np.zeros([n2,1])<\/code><\/pre>\n\n\n\n<p><\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Forward Propagation \/ Backward Propagation<\/h4>\n\n\n\n<p>Forward Propagation \u603b\u662f\u7b80\u5355\u7684\u3002Backward Propagation \u672c\u8eab\u7684\u8ba1\u7b97\u4e0e\u63a8\u5bfc\u662f\u975e\u5e38\u590d\u6742\u7684\uff0c\u8fd9\u91cc\u4e0d\u6253\u7b97\u8be6\u8ff0\uff08\u540e\u7eed\u518d\u5355\u72ec\u4ecb\u7ecd\uff09\u3002\u8fd9\u91cc\u628a Backward Propagation \u7684\u8ba1\u7b97\u7ed3\u679c\u5217\u4e3e\u5982\u4e0b\u3002\u5bf9\u4e8e\u8f93\u51fa\u5c42\uff1a<\/p>\n\n\n<p>$$<br \/>\n\\begin{align}<br \/>\ndW^{[l]} &#038; = \\frac{\\partial J}{\\partial W^{[l]}} \\\\<br \/>\n&#038; = \\frac{\\partial J}{\\partial Z^{[l]}} @ (A^{[l-1]})^T<br \/>\n\\\\<br \/>\ndZ^{[l]} &#038; = \\frac{\\partial J}{\\partial Z^{[l]}} \\\\<br \/>\n&#038; = \\frac{1}{m}(A^{[l]} &#8211; Y)<br \/>\n\\end{align}<br \/>\n$$<\/p>\n\n\n\n<p>\u8fd9\u91cc\u7684 <code>@ <\/code>\u8868\u793a\u77e9\u9635\u4e58\u6cd5\u7b26\u53f7\u3002 \u4e0a\u6807 <code>T<\/code>\u8868\u793a\u77e9\u9635\u8f6c\u7f6e\u3002\u8fd9\u91cc\u4e00\u5171\u4e24\u5c42\uff0c\u6545\u8fd9\u91cc\u7684  \\( l = 2 \\) \u3002<\/p>\n\n\n\n<p>\u5bf9\u4e8e\u9690\u85cf\u5c42\uff1a<\/p>\n\n\n<p>$$<br \/>\n\\begin{align*}<br \/>\ndW^{[k-1]} &#038; = \\frac{\\partial J}{\\partial W^{[k-1]}} \\\\<br \/>\n&#038; = \\frac{\\partial J}{\\partial Z^{[k-1]}} @ (A^{[l-2]})^T &#038;<br \/>\n\\\\<br \/>\ndZ^{[k-1]} &#038; = \\frac{\\partial J}{\\partial Z^{[k-1]}} \\\\<br \/>\n&#038; = (W^{[k]})^T @ \\partial Z^{[k]} \\cdot g\\prime(Z^{[k-1]}) &#038;<br \/>\n\\end{align*}<br \/>\n$$<\/p>\n\n\n\n<p>\u56e0\u4e3a\u8fd9\u91cc\u53ea\u6709\u4e00\u4e2a\u9690\u85cf\u5c42\u548c\u4e00\u4e2a\u8f93\u51fa\u5c42\uff0c\u6545\u8fd9\u91cc\u7684 \\( k = 2 \\)\uff1b\u76f8\u540c\u7684\uff0c\u8fd9\u91cc\u7684 <code>@ <\/code>\u8868\u793a\u77e9\u9635\u4e58\u6cd5\u7b26\u53f7\uff1b\u8fd9\u91cc\u7684 \\( \\cdot \\) \u8868\u793a\u5bf9\u5e94\u5143\u7d20\u76f8\u4e58\uff08element-wise\uff09\uff1b\u51fd\u6570 \\( g \\) \u8868\u793a ReLU\u51fd\u6570\u3002 <\/p>\n\n\n\n<p>\u5177\u4f53\u7684\u4ee3\u7801\u5b9e\u73b0\uff1a<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"python\" class=\"language-python\">    # forward propagation\n    A0 = X\n\n    Z1 = W1@X + b1  # W1 (n1,n0)  X: (n0,m)\n    A1 = np.maximum(Z1,0) # relu\n    Z2 = W2@A1 + b2\n    A2 = logistic_function(Z2)\n\n    dZ2 = (A2-Y)\/m\n    dW2 = dZ2@A1.T\n    db2 = np.sum(dZ2,axis=1,keepdims = True)\n\n    dZ1 = W2.T@dZ2*(np.where(Z1 &gt; 0, 1, 0)) # np.where(Z1 &gt; 0, 1, 0) is derivative of relu function\n    dW1 = dZ1@A0.T\n    db1 = np.sum(dZ1,axis=1,keepdims = True)<\/code><\/pre>\n\n\n\n<p><\/p>\n\n\n\n<h4 class=\"wp-block-heading\">\u8bad\u7ec3\u8fed\u4ee3<\/h4>\n\n\n\n<p>\u6bcf\u6b21\u8bad\u7ec3\u8fed\u4ee3\u90fd\u9700\u8981\u6839\u636e\u6837\u672c\u6570\u636e\uff0c\u8fdb\u884c\u4e00\u6b21\u4e0a\u8ff0\u7684 Forward Propagation \/ Backward Propagation \uff0c\u7136\u540e\u66f4\u65b0\u65b0\u7684\u53c2\u6570\u503c\uff0c\u4ee5\u7528\u4e8e\u4e0b\u4e00\u6b21\u8fed\u4ee3\uff0c\u5177\u4f53\u7684\u5b9e\u73b0\u5982\u4e0b\uff1a<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"python\" class=\"language-python\">cost_last = np.inf # very large data,maybe better , what about np.inf\nfor i in range(iteration_count):\n    ...\n    Forward Propagation \/ Backward Propagation\n    ...\n    W1 = W1 - learning_rate*dW1\n    W2 = W2 - learning_rate*dW2\n    b1 = b1 - learning_rate*db1\n    b2 = b2 - learning_rate*db2<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">\u4f7f\u7528\u6d4b\u8bd5\u6570\u636e\u96c6\u9a8c\u8bc1\u8bad\u7ec3\u6548\u679c<\/h4>\n\n\n\n<p>\u5728\u5b8c\u6210\u8bad\u7ec3\u540e\uff0c\u5c31\u53ef\u4ee5\u5bf9\u6d4b\u8bd5\u96c6\u4e2d\u7684\u6570\u636e\u8fdb\u884c\u9a8c\u8bc1\u4e86\u3002\u9700\u8981\u6ce8\u610f\u7684\u662f\uff0c\u5728\u524d\u9762\u505a\u4e86\u201cfeature scaling\u201d\uff0c\u8fd9\u91cc\u9700\u8981\u5bf9\u5e94\u5c06\u8f93\u5165\u6570\u636e\u505a\u5bf9\u5e94\u7684\u5904\u7406\u3002\u5c06\u9884\u6d4b\u7ed3\u679c\uff0c\u4e0e\u6807\u6ce8\u6570\u636e\u8fdb\u884c\u5bf9\u6bd4\uff0c\u5c31\u53ef\u4ee5\u786e\u5b9a\u8be5\u6a21\u578b\u7684\u6548\u679c\u4e86\u3002<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"python\" class=\"language-python\"># Normalization for test dataset\nX  = (test_X.T - mean)\/std\nY  = test_y.reshape(1,test_y.shape[0])\n\nY_predict = (logistic_function(W2@np.maximum((W1@X+b1),0)+b2) &gt; 0.5).astype(int)\n\nfor index in (np.where(Y != Y_predict)[1]):\n    print(f\"failed to recognize: {index}\")\n    # np.set_printoptions(threshold=np.inf)\n    # np.set_printoptions(linewidth=np.inf)\n    # print(test_X[index].reshape(28,28))\n\nprint(\"total test set:\" + str(Y.shape[1]) + \",and err rate:\"+str((np.sum(np.square(Y-Y_predict)))\/Y.shape[1]))<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">\u5b8c\u6574\u7684\u4ee3\u7801<\/h4>\n\n\n\n<p>\u5b8c\u6574\u7684\u4ee3\u7801\u53ef\u4ee5\u53c2\u8003 GitHub \u4ed3\u5e93\u4e2d\u7684 ssnn_bear.py \u811a\u672c\uff1a<a href=\"https:\/\/github.com\/orczhou\/ssnn\">\u53c2\u8003<\/a>\u3002\u8fd9\u91cc\u5f20\u8d34\u5f53\u524d\u7248\u672c\u5982\u4e0b\uff1a<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"python\" class=\"language-python\">\"\"\"\nsuper simple neural networks (bear version)\n  * input x is matrix 784x1 (where 784 = 28*28 which is MNIST image data)\n  * 30 neurons for the only hidden layer, as n^{[1]} = 30\n  * output layer: one neuron for classification(logistic)\n  * using relu for activation function in hidden layer\n\ninput layer:\n    x: (shape 784x1)\n        X: m samples where m = 12665 , X: 784 x 12665\n        as : a^{[0]}: 784 x 12665  n^{[0]} = 784\nhidden layer:\n    n^{[1]}:  30\n    W^{[1]}: (30,784)   as (n^{[1]},n^{[0]})\n    Z^{[1]}: (30,12665) as (n^{[1]},m)\n    A^{[1]}: (30,12665) as (n^{[1]},m)\noutput layer:\n    n^{[2]}: 1\n    W^{[2]}: (1,30)     as (n^{[2]},n^{[1]})\n    Z^{[2]}: (1,12665)  as (n^{[2]},m)\n    A^{[2]}: (1,12665)  as (n^{[2]},m)\n\noutput:\n    y \\in [0,1] or  p \\in {0,1}\n        Y: (1 x m) ndarray\nstructure for only one sample:\n      x_1   -&gt;   W*X + B   -&gt;  relu  -&gt;\n      x_2   -&gt;   W*X + B   -&gt;  relu  -&gt;  \\\n      ...   -&gt;     ...     -&gt;     .. -&gt;  -&gt; w*x+b -&gt; logistic\n      x_784 -&gt;   W*X + B   -&gt;  relu  -&gt;  \/\n     ------     --------------------       ------------------\n       |                |                          |\n       V                V                          V\n     input         30 neurons                 one neuron\n    feature      relu activation             output layer\n\n  By numpy with m samples:\n    np.logistic(W2@g(W1@X+b1)+b2) as \\hat{Y}: (1 x m) ndarray\n\n    dimension analysis:\n        W2        : (n2,n1)\n        g(W1@X+b1): (n1,m)\n            W1 : (n1,n0)\n            X  : (n0,m)\n            b1 : (n1,1)  with broadcasting to (n1,m)\n        b2: (n2,1) with broadcasting to (n2,m)\n\ngrad and notaion:\n    forward propagation : A1 A2 Z1 Z2\n    backward propagation: dW1 dW2 db1 db2\n\n    more details:\n        Z1 = W1@X  + b1\n        Z2 = W2@A1 + b2\n        A1 = g(Z1)      -- g     for relu\n        A2 = \\sigma(Z2) -- sigma for logistic\n\n        dW2 = ((1\/m)*(A2-Y))@A1.T\n            dW2 = dZ2@A1.T  where dZ2 = (1\/m)*(A2-Y)\n            A2.shape:(1,m) Y.shape:(1,m) A1.T.shape:(n1,m)\n            so: dW2.shape: (1,n1)\n\n        dW1 = (W2.T@((1\/m)*(A2-Y))*g_prime(Z1))@A0.T\n            dW1 = dZ1@A1.T\n                where\n                    dZ1 = W2.T@dZ2 * g_prime(Z1)\n                    g_prime is derivative of relu\n                dW2.shape: (n1,n0)\n        note: @ for matrix multiply;   * for dot product\/element-wise\n\nChallenges\n    1. Understanding the MNIST dataset and labels\n    2. Understanding gradient caculate and the gradient descent\n    3. Understanding logistic regression loss function and the caculation\n    3. Knowing feature normalization\n\nabout it:\n    it's a simple project for human learning how machine learning\n    version ant : scalar input\/one neuron\/one layer\/binary classification\n    version bear: vector input\/30+1 neurons \/two layer\/binary classification\n    by orczhou.com\n\"\"\"\n\nfrom keras.datasets import mnist\nimport numpy as np\n\n# return only data lable 0 or 1 from MNIST for the binary classification\ndef filter_mnist_data(data_X, data_y):\n    data_filter = np.where((data_y == 0) | (data_y == 1))\n    filtered_data_X, filtered_data_y = data_X[data_filter], data_y[data_filter]\n    r_data_X = filtered_data_X.reshape(filtered_data_X.shape[0],filtered_data_X.shape[1]*filtered_data_X.shape[2])\n    return (r_data_X, filtered_data_y)\n\n(train_all_X, train_all_y), (test_all_X, test_all_y) = mnist.load_data()\n(train_X,train_y) = filter_mnist_data(train_all_X, train_all_y)\n(test_X ,test_y ) = filter_mnist_data(test_all_X, test_all_y)\n\nX  = train_X.T\nY  = train_y.reshape(1,train_y.shape[0])\n\nm = X.shape[1]    # number of samples\n\n# hyper-parameter; read the comments above for structure of the NN\nn0 = X.shape[0]   # number of input features\nn1 = 10           # nerons of the hidden layer\nn2 = 1            # nerons of the output layer\niteration_count = 500\nlearning_rate   = 0.5\n\n# feature scaling \/ Normalization\nmean = np.mean(X,axis = 1,keepdims = True)\nstd  = np.std( X,axis = 1,keepdims = True)+0.000000001\nX  = (X-mean)\/std\n\n# initial parameters: W1 W2 b1 b2 size\nnp.random.seed(561)\nW1 = np.random.randn(n1,n0)*0.01\nW2 = np.random.randn(n2,n1)*0.01\nb1 = np.zeros([n1,1])\nb2 = np.zeros([n2,1])\n\n# logistic function\ndef logistic_function(x):\n    return 1\/(1+np.exp(-x))\n\nabout_the_train = '''\\\ntry to train the model with:\n  learning rate: {:f}\n  iteration    : {:d}\n  neurons in hidden layer: {:d}\n\\\n'''\nprint(about_the_train.format(learning_rate,iteration_count,n1))\n\n# forward\/backward propagation (read the comment above:\"grad and notaion\")\ncost_last = np.inf # very large data,maybe better , what about np.inf\nfor i in range(iteration_count):\n    # forward propagation\n    A0 = X\n\n    Z1 = W1@X + b1  # W1 (n1,n0)  X: (n0,m)\n    A1 = np.maximum(Z1,0) # relu\n    Z2 = W2@A1 + b2\n    A2 = logistic_function(Z2)\n\n    dZ2 = (A2-Y)\/m\n    dW2 = dZ2@A1.T\n    db2 = np.sum(dZ2,axis=1,keepdims = True)\n\n    dZ1 = W2.T@dZ2*(np.where(Z1 &gt; 0, 1, 0)) # np.where(Z1 &gt; 0, 1, 0) is derivative of relu function\n    dW1 = dZ1@A0.T\n    db1 = np.sum(dZ1,axis=1,keepdims = True)\n\n    cost_current = np.sum(-(Y*(np.log(A2))) - ((1-Y)*(np.log(1-A2))))\/m\n    if (i+1)%(iteration_count\/20) == 0:\n        print(\"iteration: {:5d},cost_current:{:f},cost_last:{:f},cost reduce:{:f}\".format( i+1,cost_current,cost_last,cost_last-cost_current))\n\n    cost_last = cost_current\n    W1 = W1 - learning_rate*dW1\n    W2 = W2 - learning_rate*dW2\n    b1 = b1 - learning_rate*db1\n    b2 = b2 - learning_rate*db2\n\nprint(\"Label:\")\nprint(np.round( Y[0][:20]+0.,0))\nprint(\"Predict:\")\nprint(np.round(A2[0][:20],0))\n\n# Normalization for test dataset\nX  = (test_X.T - mean)\/std\nY  = test_y.reshape(1,test_y.shape[0])\n\nY_predict = (logistic_function(W2@np.maximum((W1@X+b1),0)+b2) &gt; 0.5).astype(int)\n\nfor index in (np.where(Y != Y_predict)[1]):\n    print(f\"failed to recognize: {index}\")\n    # np.set_printoptions(threshold=np.inf)\n    # np.set_printoptions(linewidth=np.inf)\n    # print(test_X[index].reshape(28,28))\n\nprint(\"total test set:\" + str(Y.shape[1]) + \",and err rate:\"+str((np.sum(np.square(Y-Y_predict)))\/Y.shape[1]))<\/code><\/pre>\n\n\n\n<p>\u7b80\u5355\u7edf\u8ba1\uff0c\u4ee3\u7801\u603b\u8ba1180\u884c\uff0c\u5176\u4e2d\u6ce8\u91ca\u7ea690\u884c\u3002<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">\u8fd0\u884c\u7ed3\u679c\u8bf4\u660e<\/h4>\n\n\n\n<p>\u8fd0\u884c\u8be5\u7a0b\u5e8f\u4f1a\u6709\u5982\u4e0b\u8f93\u51fa\uff1a<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code class=\"\">try to train the model with:\n  learning rate: 0.500000\n  iteration    : 500\n  neurons in hidden layer: 10\niteration:    25,cost_current:0.009138,cost_last:0.009497,cost reduce:0.000358\n...\niteration:   500,cost_current:0.000849,cost_last:0.000850,cost reduce:0.000001\nfailed to recognize: 1749\nfailed to recognize: 2031\ntotal test set:2115,and err rate:0.0009456264775413711<\/code><\/pre>\n\n\n\n<p>\u5728\u672c\u6b21\u8bad\u7ec3\u540e\uff0c\u5bf9\u4e8e\u6d4b\u8bd5\u96c6\u4e2d\u7684 2115 \u4e2d\u56fe\u7247\uff0c\u8bc6\u522b\u7684\u9519\u8bef\u7387\u4e3a 0.094%\uff0c\u5373\u6709\u4e24\u5f20\u56fe\u7247\u672a\u80fd\u591f\u6b63\u786e\u8bc6\u522b\u3002\u8fd9\u4e24\u5f20\u56fe\u7247\u7684\u7f16\u53f7\u5206\u522b\u662f1749\u548c2031\uff0c\u5bf9\u5e94\u7684\u56fe\u50cf\u5982\u4e0b\uff1a<\/p>\n\n\n\n<div class=\"wp-block-columns is-layout-flex wp-container-core-columns-is-layout-28f84493 wp-block-columns-is-layout-flex\">\n<div class=\"wp-block-column is-layout-flow wp-block-column-is-layout-flow\">\n<figure class=\"wp-block-image aligncenter size-full is-resized\"><img loading=\"lazy\" decoding=\"async\" width=\"28\" height=\"28\" src=\"https:\/\/www.orczhou.com\/wp-content\/uploads\/2024\/11\/image-15.png\" alt=\"\" class=\"wp-image-15784\" style=\"width:100px\"\/><\/figure>\n<\/div>\n\n\n\n<div class=\"wp-block-column is-layout-flow wp-block-column-is-layout-flow\">\n<figure class=\"wp-block-image aligncenter size-full is-resized\"><img loading=\"lazy\" decoding=\"async\" width=\"28\" height=\"28\" src=\"https:\/\/www.orczhou.com\/wp-content\/uploads\/2024\/11\/image-16.png\" alt=\"\" class=\"wp-image-15785\" style=\"width:100px\"\/><\/figure>\n<\/div>\n<\/div>\n\n\n\n<h4 class=\"wp-block-heading\">\u6700\u540e<\/h4>\n\n\n\n<p>\u8be5\u795e\u7ecf\u7f51\u7edc\u5728\u8bad\u7ec3\u540e\uff0c\u5bf9\u4e8e2115\u5f20\u6d4b\u8bd5\u96c6\u4e2d\u7684\u56fe\u7247\uff0c\u4ec5\u67092\u5f20\u8bc6\u522b\u5931\u8d25\u3002\u901a\u8fc7\u8be5\u7a0b\u5e8f\uff0c\u53ef\u4ee5\u770b\u5230\uff0c\u795e\u7ecf\u7f51\u7edc\u7684\u5f3a\u5927\u4e0e\u795e\u5947\u3002<\/p>\n\n\n\n<p>\u56e0\u4e3a\u795e\u7ecf\u7f51\u7edc\u7684 Backward Propagation \u7684\u63a8\u5bfc\u975e\u5e38\u590d\u6742\uff0c\u672c\u6587\u4e2d\u76f4\u63a5\u7ed9\u51fa\u4e86\u76f8\u5173\u516c\u5f0f\uff0c\u540e\u7eed\u5c06\u72ec\u7acb\u4ecb\u7ecd\u8be5\u90e8\u5206\u5185\u5bb9\u3002\u5982\u679c\u6709\u4efb\u4f55\u95ee\u9898\u53ef\u4ee5\u7559\u8a00\u8ba8\u8bba\u6216\u516c\u4f17\u53f7\u540e\u53f0\u7ed9\u4f5c\u8005\u7559\u8a00\u3002<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">\u8865\u5145\u8bb0\u5f55<\/h4>\n\n\n\n<p>\u5728\u8fd9\u4e2a\u8be5\u7a0b\u5e8f\u5b9e\u73b0\u4e2d\uff0c\u8fd8\u9047\u5230\u4e86\u4e00\u4e9b\u5176\u4ed6\u7684\u95ee\u9898\uff0c\u8bb0\u5f55\u5982\u4e0b\u3002<\/p>\n\n\n\n<h5 class=\"wp-block-heading\">\u4e00\u4e9b\u62a5\u9519<\/h5>\n\n\n\n<p>\u201cRuntimeWarning: overflow encountered in exp:  return 1\/(1+np.exp(-x))\u201d <\/p>\n\n\n\n<p>\u5f53\u8bad\u7ec3\u6216\u8005\u9884\u6d4b\u8ba1\u7b97\u8fc7\u7a0b\u4e2d\uff0c\u5982\u679c\u51fa\u73b0\u90e8\u5206<code>-x<\/code>\u503c\u6bd4\u8f83\u5927\uff0c\u90a3\u4e48\u5c31\u4f1a\u51fa\u73b0<code>np.exp(-x)<\/code>\u6ea2\u51fa\u7684\u95ee\u9898\u3002\u4e0d\u8fc7\uff0c\u8fd8\u597d\u8be5\u95ee\u9898\u5728\u8be5\u573a\u666f\u4e0b\u5e76\u4e0d\u4f1a\u5f71\u54cd\u8ba1\u7b97\u7ed3\u679c\uff0c\u56e0\u4e3a\u8fd9\u79cd\u60c5\u51b5\u4e0b\uff0c<code>1\/(1+np.exp(-x))<\/code>\u4f9d\u65e7\u4f1a\u8fd4\u56de0\uff0c\u800c\u8fd9\u4e5f\u662f\u9884\u671f\u4e2d\u7684\u3002<\/p>\n\n\n\n<h5 class=\"wp-block-heading\">\u96be\u4ee5\u5206\u6790<\/h5>\n\n\n\n<p>\u5728\u8fd9\u4e2a\u8bc6\u522b\u7a0b\u5e8f\u4e2d\uff0c\u6700\u540e\u53d1\u73b0\u6709\u90e8\u5206\u56fe\u7247\u662f\u96be\u4ee5\u8bc6\u522b\u7684\uff0c\u800c\u4e14\u65e0\u8bba\u5982\u4f55\u8c03\u6574\u53c2\u6570\uff0c\u90e8\u5206\u56fe\u7247\u8fd8\u662f\u96be\u4ee5\u8bc6\u522b\u3002\u6700\u597d\u7684\u5904\u7406\u65b9\u6cd5\u5f53\u7136\u662f\u589e\u52a0\u8bad\u7ec3\u6570\u636e\u96c6\uff0c\u4f46\u73b0\u5b9e\u4e2d\u53ef\u80fd\u5e76\u4e0d\u603b\u662f\u80fd\u591f\u505a\u5230\u3002<\/p>\n\n\n\n<p>\u800c\u5173\u4e8e\u6a21\u578b\u5e94\u8be5\u5982\u4f55\u4f18\u5316\uff0c\u8fd9\u4f3c\u4e4e\u662f\u96be\u4ee5\u5206\u6790\uff0c\u65e0\u4ece\u5165\u624b\u3002<\/p>\n","protected":false},"excerpt":{"rendered":"<p>\u66f4\u8fdb\u4e00\u6b65\uff0c\u672c\u6587\u5c06\u4ece\u96f6\u6784\u5efa\u4e00\u4e2a\u6d45\u5c42\u7684\u524d\u9988\u795e\u7ecf\u7f51\u7edc\uff0c\u5b9e\u73b0\u624b\u5199\u6570\u5b570\u548c1\u7684\u8bc6\u522b\u3002\u793a\u4f8b\u624b\u5199\u6570\u5b57\u5982\u4e0b\u56fe\u6240\u793a\u3002\u6574\u4f53\u5b9e\u73b0\u5305\u62ec\u6570\u636e\u9884\u5904\u7406\u3001\u53c2\u6570\u521d\u59cb\u5316\u3001forward\/backword propagation\u3001\u8bad\u7ec3\u4e0e\u9884\u6d4b\u3002<\/p>\n","protected":false},"author":1,"featured_media":21430,"comment_status":"open","ping_status":"closed","sticky":false,"template":"wp-custom-template-a-1440-px-width-template","format":"standard","meta":{"_eb_attr":"","inline_featured_image":false,"_tocer_settings":[],"footnotes":""},"categories":[137],"tags":[],"class_list":["post-15501","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-learning-more"],"_links":{"self":[{"href":"https:\/\/www.orczhou.com\/index.php\/wp-json\/wp\/v2\/posts\/15501","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.orczhou.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.orczhou.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.orczhou.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.orczhou.com\/index.php\/wp-json\/wp\/v2\/comments?post=15501"}],"version-history":[{"count":152,"href":"https:\/\/www.orczhou.com\/index.php\/wp-json\/wp\/v2\/posts\/15501\/revisions"}],"predecessor-version":[{"id":21985,"href":"https:\/\/www.orczhou.com\/index.php\/wp-json\/wp\/v2\/posts\/15501\/revisions\/21985"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.orczhou.com\/index.php\/wp-json\/wp\/v2\/media\/21430"}],"wp:attachment":[{"href":"https:\/\/www.orczhou.com\/index.php\/wp-json\/wp\/v2\/media?parent=15501"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.orczhou.com\/index.php\/wp-json\/wp\/v2\/categories?post=15501"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.orczhou.com\/index.php\/wp-json\/wp\/v2\/tags?post=15501"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}