DL之DNN:自定义2层神经网络TwoLayerNet模型(计算梯度两种方法)利用MNIST数据集进行训练、预测
生活随笔
收集整理的這篇文章主要介紹了
DL之DNN:自定义2层神经网络TwoLayerNet模型(计算梯度两种方法)利用MNIST数据集进行训练、预测
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
DL之DNN:自定義2層神經(jīng)網(wǎng)絡TwoLayerNet模型(計算梯度兩種方法)利用MNIST數(shù)據(jù)集進行訓練、預測
導讀
利用python的numpy計算庫,進行自定義搭建2層神經(jīng)網(wǎng)絡TwoLayerNet模型。分別利用兩種計算梯度兩種方法,數(shù)值微分計算法和反向傳播算法,對MNIST數(shù)據(jù)集進行訓練,輸出loss變化曲線,并輸出訓練集、測試集的預測準確度。經(jīng)過對比,發(fā)現(xiàn),反向傳播算法速度比微分求值算法快的多的多。
?
目錄
輸出結果
設計思路
核心代碼
?
?
?
相關文章
DL之DNN:自定義2層神經(jīng)網(wǎng)絡TwoLayerNet模型(計算梯度兩種方法)利用MNIST數(shù)據(jù)集進行訓練、預測
輸出結果
T1、因為采用T1法,半個多小時還沒有出現(xiàn)下一個結果,博主果斷放棄!采用了T2
T2、
?
?
?
設計思路
?
核心代碼
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為True的情況下,標簽作為one-hot數(shù)組返回one-hot數(shù)組是指[0,0,1,0,0,0,0,0,0,0]這樣的數(shù)組flatten : 是否將圖像展開為一維數(shù)組Returns-------(訓練圖像, 訓練標簽), (測試圖像, 測試標簽)"""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ù)字化實踐50位技術專家共同創(chuàng)作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的DL之DNN:自定义2层神经网络TwoLayerNet模型(计算梯度两种方法)利用MNIST数据集进行训练、预测的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: HighNewTech:重磅!来自深度学
- 下一篇: DL之CG:Computational