DL之DNN:自定义2层神经网络TwoLayerNet模型(计算梯度两种方法)利用MNIST数据集进行训练、预测
DL之DNN:自定義2層神經(jīng)網(wǎng)絡(luò)TwoLayerNet模型(計(jì)算梯度兩種方法)利用MNIST數(shù)據(jù)集進(jìn)行訓(xùn)練、預(yù)測(cè)
導(dǎo)讀
利用python的numpy計(jì)算庫(kù),進(jìn)行自定義搭建2層神經(jīng)網(wǎng)絡(luò)TwoLayerNet模型。分別利用兩種計(jì)算梯度兩種方法,數(shù)值微分計(jì)算法和反向傳播算法,對(duì)MNIST數(shù)據(jù)集進(jìn)行訓(xùn)練,輸出loss變化曲線,并輸出訓(xùn)練集、測(cè)試集的預(yù)測(cè)準(zhǔn)確度。經(jīng)過(guò)對(duì)比,發(fā)現(xiàn),反向傳播算法速度比微分求值算法快的多的多。
?
目錄
輸出結(jié)果
設(shè)計(jì)思路
核心代碼
?
?
?
相關(guān)文章
DL之DNN:自定義2層神經(jīng)網(wǎng)絡(luò)TwoLayerNet模型(計(jì)算梯度兩種方法)利用MNIST數(shù)據(jù)集進(jìn)行訓(xùn)練、預(yù)測(cè)
輸出結(jié)果
T1、因?yàn)椴捎肨1法,半個(gè)多小時(shí)還沒(méi)有出現(xiàn)下一個(gè)結(jié)果,博主果斷放棄!采用了T2
T2、
?
?
?
設(shè)計(jì)思路
?
核心代碼
load_mnist數(shù)據(jù)集代碼
# coding: utf-8 try:import urllib.request except ImportError:raise ImportError('You should use Python 3.x') import os.path import gzip import pickle import os import numpy as npurl_base = 'http://yann.lecun.com/exdb/mnist/' key_file = {'train_img':'train-images-idx3-ubyte.gz','train_label':'train-labels-idx1-ubyte.gz','test_img':'t10k-images-idx3-ubyte.gz','test_label':'t10k-labels-idx1-ubyte.gz' }dataset_dir = os.path.dirname(os.path.abspath(__file__)) save_file = dataset_dir + "/mnist.pkl"train_num = 60000 test_num = 10000 img_dim = (1, 28, 28) img_size = 784def _download(file_name):file_path = dataset_dir + "/" + file_nameif os.path.exists(file_path):returnprint("Downloading " + file_name + " ... ")urllib.request.urlretrieve(url_base + file_name, file_path)print("Done")def download_mnist():for v in key_file.values():_download(v)def _load_label(file_name):file_path = dataset_dir + "/" + file_nameprint("Converting " + file_name + " to NumPy Array ...")with gzip.open(file_path, 'rb') as f:labels = np.frombuffer(f.read(), np.uint8, offset=8)print("Done")return labelsdef _load_img(file_name):file_path = dataset_dir + "/" + file_nameprint("Converting " + file_name + " to NumPy Array ...") with gzip.open(file_path, 'rb') as f:data = np.frombuffer(f.read(), np.uint8, offset=16)data = data.reshape(-1, img_size)print("Done")return datadef _convert_numpy():dataset = {}dataset['train_img'] = _load_img(key_file['train_img'])dataset['train_label'] = _load_label(key_file['train_label']) dataset['test_img'] = _load_img(key_file['test_img'])dataset['test_label'] = _load_label(key_file['test_label'])return datasetdef init_mnist():download_mnist()dataset = _convert_numpy()print("Creating pickle file ...")with open(save_file, 'wb') as f:pickle.dump(dataset, f, -1)print("Done!")def _change_one_hot_label(X):T = np.zeros((X.size, 10))for idx, row in enumerate(T):row[X[idx]] = 1return Tdef load_mnist(normalize=True, flatten=True, one_hot_label=False):"""讀入MNIST數(shù)據(jù)集Parameters----------normalize : 將圖像的像素值正規(guī)化為0.0~1.0one_hot_label : one_hot_label為T(mén)rue的情況下,標(biāo)簽作為one-hot數(shù)組返回one-hot數(shù)組是指[0,0,1,0,0,0,0,0,0,0]這樣的數(shù)組flatten : 是否將圖像展開(kāi)為一維數(shù)組Returns-------(訓(xùn)練圖像, 訓(xùn)練標(biāo)簽), (測(cè)試圖像, 測(cè)試標(biāo)簽)"""if not os.path.exists(save_file):init_mnist()with open(save_file, 'rb') as f:dataset = pickle.load(f)if normalize:for key in ('train_img', 'test_img'):dataset[key] = dataset[key].astype(np.float32)dataset[key] /= 255.0if one_hot_label:dataset['train_label'] = _change_one_hot_label(dataset['train_label'])dataset['test_label'] = _change_one_hot_label(dataset['test_label'])if not flatten:for key in ('train_img', 'test_img'):dataset[key] = dataset[key].reshape(-1, 1, 28, 28)return (dataset['train_img'], dataset['train_label']), (dataset['test_img'], dataset['test_label']) if __name__ == '__main__':init_mnist()?
?
?
?
?
《新程序員》:云原生和全面數(shù)字化實(shí)踐50位技術(shù)專(zhuān)家共同創(chuàng)作,文字、視頻、音頻交互閱讀總結(jié)
以上是生活随笔為你收集整理的DL之DNN:自定义2层神经网络TwoLayerNet模型(计算梯度两种方法)利用MNIST数据集进行训练、预测的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: HighNewTech:重磅!来自深度学
- 下一篇: 成功解决read_data_sets (