TF01-03:Tensorflow中Keras提供的數(shù)據(jù)集說明

學(xué)習(xí)Tensorflow從數(shù)據(jù)集開始,先弄清楚Tensorflow的Keras框架提供的數(shù)據(jù)集。Keras提供了7個(gè)數(shù)據(jù)集,類型比較全面,基本上滿足Tensorflow的入門學(xué)習(xí)。對(duì)數(shù)據(jù)集掌握如下幾個(gè)方面
??1. 數(shù)據(jù)集的原始來源與說明;
??2. 數(shù)據(jù)集的加載;
??3. 數(shù)據(jù)集的格式;


一. Tensorflow數(shù)據(jù)集概述

  • 從Tensorflow的數(shù)據(jù)集開始掌握Tensorflow2.0與Keras。

1.1. Tensorflow提供的數(shù)據(jù)集模塊

  1. boston_housing 模塊:
    • 波士頓住房?jī)r(jià)格回歸數(shù)據(jù)集。
  2. cifar10 模塊:
    • CIFAR10小圖像分類數(shù)據(jù)集。
  3. cifar100 模塊:
    • CIFAR100小圖像分類數(shù)據(jù)集。
  4. fashion_mnist 模塊:
    • 時(shí)尚mnist數(shù)據(jù)集。
  5. imdb 模塊:
    • IMDB情緒分類數(shù)據(jù)集。
  6. mnist 模塊:
    • mnist手寫數(shù)字?jǐn)?shù)據(jù)集。
  7. reuters 模塊:
    • 路透社主題分類數(shù)據(jù)集。

1.2. 數(shù)據(jù)集模塊函數(shù)-load_data


    tf.keras.datasets.fashion_mnist.load_data()

返回的數(shù)據(jù)集格式如下:

    (x_train, y_train), (x_test, y_test)
  • 上面的數(shù)據(jù)集因?yàn)間oogle的緣故,所以有的數(shù)據(jù)集無法訪問。但是可以通過sklearn庫(kù)獲取。
  • 能通過tensorflow模塊訪問的如下,其他則無法訪問。

二. CIFAR10小圖像分類數(shù)據(jù)集

2.1. CIFAR-10數(shù)據(jù)集介紹

  • CIFAR-10數(shù)據(jù)集是一個(gè)包含60000張圖片的數(shù)據(jù)集。
    1. 其中每張照片為32*32的彩色照片,每個(gè)像素點(diǎn)包括RGB三個(gè)數(shù)值,數(shù)值范圍 0 ~ 255。
    2. 所有照片分屬10個(gè)不同的類別,分別是 'airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck'
    3. 其中五萬張圖片被劃分為訓(xùn)練集,剩下的一萬張圖片屬于測(cè)試集。

2.2. 數(shù)據(jù)集的讀取

2.2.1. 使用tensorflow模塊加載

  1. 數(shù)據(jù)加載與數(shù)據(jù)格式
import matplotlib.pyplot as plt
import tensorflow as tf
import tensorflow.keras.datasets.cifar10 as cifar10

(x_train, y_train), (x_test, y_test) = cifar10.load_data()
x_train.shape, y_train.shape, x_test.shape, y_test.shape
((50000, 32, 32, 3), (50000, 1), (10000, 32, 32, 3), (10000, 1))
  1. 數(shù)據(jù)可視化
%matplotlib inline
import matplotlib.pyplot as plt

plt.imshow(x_train[0])
plt.show()

y_train[0]    # 青蛙:frog。
圖像數(shù)據(jù)可視化
array([6], dtype=uint8)
  1. 類別說明
    • 官網(wǎng)介紹地址:http://www.cs.toronto.edu/~kriz/cifar.html
      官網(wǎng)分類數(shù)據(jù)分類介紹

-類別索引: 類別下標(biāo)從0開始
- 0:airplane
- 1:automobile
- 2:bird
- 3:cat
- 4:deer
- 5:dog
- 6:frog
- 7:horse
- 8:ship
- 9:truck

2.2.2. 從解壓的本地文件讀取

  • 可以從http://www.cs.toronto.edu/~kriz/cifar.html下載tar.gz壓縮格式的CIFAR10數(shù)據(jù)集。
  • 下載解壓縮的數(shù)據(jù)文件如下:
    下載解壓的數(shù)據(jù)文件
  1. 讀取方式可以從官網(wǎng)獲取例子代碼
import pickle   # python的序列化歸檔模塊


with open('01datasets/cifar-10-batches-py/data_batch_1', 'rb') as fo:   # 打開文件
    dict = pickle.load(fo, encoding='bytes')    # 讀取文件
    
# 顯示數(shù)據(jù)結(jié)構(gòu)
print('數(shù)據(jù)項(xiàng):', dict.keys())
print('數(shù)據(jù)批次:', dict[b'batch_label'])
# 只讀取第一個(gè)圖像數(shù)據(jù)的信息
print('標(biāo)簽:', dict[b'labels'][0])
print('數(shù)據(jù):', dict[b'data'][0])
print('文件名:', dict[b'filenames'][0])
數(shù)據(jù)項(xiàng): dict_keys([b'batch_label', b'labels', b'data', b'filenames'])
數(shù)據(jù)批次: b'training batch 1 of 5'
標(biāo)簽: 6
數(shù)據(jù): [ 59  43  50 ... 140  84  72]
文件名: b'leptodactylus_pentadactylus_s_000004.png'
  1. 可視化圖像
%matplotlib inline
import matplotlib.pyplot as plt
print(dict[b'data'].shape)
print(type(dict[b'data'][0]))   # 顯示數(shù)據(jù)的數(shù)據(jù)類型

img = dict[b'data'][0].reshape((3, 32, 32))
# 坐標(biāo)軸交換方法
# img = img.swapaxes(0, 1)   # 0->1
# img = img.swapaxes(1, 2)    # 0->2
# 矩陣維度轉(zhuǎn)換方法
img = img.transpose(1, 2, 0)  # 這是正常的圖像順序
plt.imshow(img)
plt.show()
(10000, 3072)
<class 'numpy.ndarray'>
圖像數(shù)據(jù)可視化
  1. meta文件的讀取
import pickle   # python的序列化歸檔模塊


with open('01datasets/cifar-10-batches-py/batches.meta', 'rb') as fo:   # 打開文件
    dict = pickle.load(fo, encoding='bytes')    # 讀取文件
    
print(dict.keys())
print(dict[b'num_cases_per_batch'])   # 每個(gè)文件中的樣本數(shù)量
print(dict[b'label_names'])   # 標(biāo)簽名(標(biāo)簽的編號(hào)是按照類別的字典序的序號(hào))
print(dict[b'num_vis'])   # 每個(gè)圖像的數(shù)據(jù)個(gè)數(shù)
dict_keys([b'num_cases_per_batch', b'label_names', b'num_vis'])
10000
[b'airplane', b'automobile', b'bird', b'cat', b'deer', b'dog', b'frog', b'horse', b'ship', b'truck']
3072

2.2.3. 直接從下載的壓縮文件中讀取

  • Python提供了.tar.gz歸檔文件讀取方式。
  1. 讀取歸檔的文件列表
import tarfile
import os.path


#  要讀取的壓縮歸檔文件
list_files = 'data_batch_1'
with tarfile.open('01datasets/cifar-10-python.tar.gz', mode='r') as fz:
    # 得到歸檔文件中的文件列表
    filenames = fz.getnames()
    # 遍歷文件列表
    for filename  in filenames:
        print(filename)

cifar-10-batches-py
cifar-10-batches-py/data_batch_4
cifar-10-batches-py/readme.html
cifar-10-batches-py/test_batch
cifar-10-batches-py/data_batch_3
cifar-10-batches-py/batches.meta
cifar-10-batches-py/data_batch_2
cifar-10-batches-py/data_batch_5
cifar-10-batches-py/data_batch_1
  1. 讀歸檔文件內(nèi)容
import tarfile
import os.path


#  要讀取的壓縮歸檔文件
list_files = 'data_batch_1'
with tarfile.open('01datasets/cifar-10-python.tar.gz', mode='r') as fz:
    # 得到歸檔文件中的文件列表
    filenames = fz.getnames()
    # 遍歷文件列表
    for filename  in filenames:
        print('文件名:',filename)
        # 把文件解析成不同組件
        base_name = os.path.basename(filename)
        # 只讀取指定的文件
        if base_name == list_files: 
            # 抽取文件內(nèi)容
            buffer_reader = fz.extractfile(filename)
            print('抽取的返回值類型:', type(buffer_reader))
            # 可以使用序列化工具實(shí)現(xiàn)反序列化(buffer_reader的類型是ExFileOObject對(duì)象,就是一個(gè)打開的文件,使用load)
            dict = pickle.load(buffer_reader, encoding='bytes')
            break

print('-------------------------')
print('讀取的數(shù)據(jù)字典key:', dict.keys())
文件名: cifar-10-batches-py
文件名: cifar-10-batches-py/data_batch_4
文件名: cifar-10-batches-py/readme.html
文件名: cifar-10-batches-py/test_batch
文件名: cifar-10-batches-py/data_batch_3
文件名: cifar-10-batches-py/batches.meta
文件名: cifar-10-batches-py/data_batch_2
文件名: cifar-10-batches-py/data_batch_5
文件名: cifar-10-batches-py/data_batch_1
抽取的返回值類型: <class 'tarfile.ExFileObject'>
-------------------------
讀取的數(shù)據(jù)字典key: dict_keys([b'batch_label', b'labels', b'data', b'filenames'])
  1. 讀取的數(shù)據(jù)可視化
%matplotlib inline
import matplotlib.pyplot as plt


img = dict[b'data'][0].reshape((3, 32, 32))
# 坐標(biāo)軸交換方法
img = img.swapaxes(0, 1)   # 0->1
img = img.swapaxes(1, 2)    # 0->2
# 矩陣維度轉(zhuǎn)換方法
# img = img.transpose(1, 2, 0)  # 這是正常的圖像順序
plt.imshow(img)
plt.show()
圖像數(shù)據(jù)可視化

三. CIFAR100小圖像分類數(shù)據(jù)集

3.1. CIFAR100數(shù)據(jù)集說明

  • CIFAR100數(shù)據(jù)集與CIFAR10數(shù)據(jù)集一樣,差別在于類別與圖像數(shù)不同:

    • CIFAR100一共100類數(shù)據(jù);
      • 100類圖像又分成20個(gè)大類;
    • 每類數(shù)據(jù)600個(gè)圖像;
  • 每個(gè)類別的說明:

    • 詳細(xì)的資料可以參考官網(wǎng):http://www.cs.toronto.edu/~kriz/cifar.html
      官網(wǎng)類別說明

3.2. 數(shù)據(jù)集的讀取

3.2.1. 使用tensorflow模塊加載

  1. 數(shù)據(jù)加載與數(shù)據(jù)格式
import matplotlib.pyplot as plt
import tensorflow as tf
import tensorflow.keras.datasets.cifar100 as cifar100

(x_train, y_train), (x_test, y_test) = cifar100.load_data()
x_train.shape, y_train.shape, x_test.shape, y_test.shape
((50000, 32, 32, 3), (50000, 1), (10000, 32, 32, 3), (10000, 1))
  1. 數(shù)據(jù)可視化
%matplotlib inline
import matplotlib.pyplot as plt

plt.imshow(x_train[0])
plt.show()

y_train[0]    # 牛,返回的是細(xì)分類別的標(biāo)簽(就是類別名的字典排序的序號(hào))
圖像數(shù)據(jù)可視化
array([19])
  1. 類別說明
  • 100種類別有點(diǎn)多,這里不意義對(duì)應(yīng)羅列。正如上面cifar10的規(guī)律,其中細(xì)分類別的標(biāo)簽是細(xì)分類別的名字的字典序的序號(hào);
  • 直接從meta文件中讀??;
  • 大的類別在數(shù)據(jù)中沒有;
with open('01datasets/cifar-100-python/meta', 'rb') as fo:   # 打開文件
    dict = pickle.load(fo, encoding='bytes')    # 讀取文件
    print(dict.keys())
    print('細(xì)分類型:', dict[b'fine_label_names'])
    print('大類型:', dict[b'coarse_label_names'])
dict_keys([b'fine_label_names', b'coarse_label_names'])
細(xì)分類型: [b'apple', b'aquarium_fish', b'baby', b'bear', b'beaver', b'bed', b'bee', b'beetle', b'bicycle', b'bottle', b'bowl', b'boy', b'bridge', b'bus', b'butterfly', b'camel', b'can', b'castle', b'caterpillar', b'cattle', b'chair', b'chimpanzee', b'clock', b'cloud', b'cockroach', b'couch', b'crab', b'crocodile', b'cup', b'dinosaur', b'dolphin', b'elephant', b'flatfish', b'forest', b'fox', b'girl', b'hamster', b'house', b'kangaroo', b'keyboard', b'lamp', b'lawn_mower', b'leopard', b'lion', b'lizard', b'lobster', b'man', b'maple_tree', b'motorcycle', b'mountain', b'mouse', b'mushroom', b'oak_tree', b'orange', b'orchid', b'otter', b'palm_tree', b'pear', b'pickup_truck', b'pine_tree', b'plain', b'plate', b'poppy', b'porcupine', b'possum', b'rabbit', b'raccoon', b'ray', b'road', b'rocket', b'rose', b'sea', b'seal', b'shark', b'shrew', b'skunk', b'skyscraper', b'snail', b'snake', b'spider', b'squirrel', b'streetcar', b'sunflower', b'sweet_pepper', b'table', b'tank', b'telephone', b'television', b'tiger', b'tractor', b'train', b'trout', b'tulip', b'turtle', b'wardrobe', b'whale', b'willow_tree', b'wolf', b'woman', b'worm']
大類型: [b'aquatic_mammals', b'fish', b'flowers', b'food_containers', b'fruit_and_vegetables', b'household_electrical_devices', b'household_furniture', b'insects', b'large_carnivores', b'large_man-made_outdoor_things', b'large_natural_outdoor_scenes', b'large_omnivores_and_herbivores', b'medium_mammals', b'non-insect_invertebrates', b'people', b'reptiles', b'small_mammals', b'trees', b'vehicles_1', b'vehicles_2']

3.2.2. 從解壓的本地文件讀取

  • 下載地址:http://www.cs.toronto.edu/~kriz/cifar.html
  • 解壓縮的文件如下:


    下載解壓縮的文件列表
  1. 讀取數(shù)據(jù)
import pickle   # python的序列化歸檔模塊


with open('01datasets/cifar-100-python/train', 'rb') as fo:   # 打開文件
    dict = pickle.load(fo, encoding='bytes')    # 讀取文件
    
# 顯示數(shù)據(jù)結(jié)構(gòu)
print('數(shù)據(jù)項(xiàng):', dict.keys())
print('數(shù)據(jù)批次:', dict[b'batch_label'])
# 只讀取第一個(gè)圖像數(shù)據(jù)的信息
print('標(biāo)簽:', dict[b'fine_labels'][0])    # 細(xì)分類型
print('標(biāo)簽:', dict[b'coarse_labels'][0])   # 大類型
print('數(shù)據(jù):', dict[b'data'][0])
print('文件名:', dict[b'filenames'][0])
數(shù)據(jù)項(xiàng): dict_keys([b'filenames', b'batch_label', b'fine_labels', b'coarse_labels', b'data'])
數(shù)據(jù)批次: b'training batch 1 of 1'
標(biāo)簽: 19
標(biāo)簽: 11
數(shù)據(jù): [255 255 255 ...  10  59  79]
文件名: b'bos_taurus_s_000507.png'
  1. 類別說明

    • 0:aquatic mammals

    • 1:fish

    • 2:flowers

    • 3:food containers

    • 4:fruit and vegetables

    • 5:household electrical devices

    • 6:household furniture

    • 7:insects

    • 8:large carnivores

    • 9:large man-made outdoor things

    • 10:large natural outdoor scenes

    • 11:large omnivores and herbivores

    • 12:medium-sized mammals

    • 13:non-insect invertebrates

    • 14:people

    • 15:reptiles

    • 16:small mammals

    • 17:trees

    • 18:vehicles 1

    • 19:vehicles 2

    • 其中coarse_labels是大類的類名的字典序的序號(hào)。

  2. 數(shù)據(jù)可視化

%matplotlib inline
import matplotlib.pyplot as plt


img = dict[b'data'][0].reshape((3, 32, 32))
# 坐標(biāo)軸交換方法
img = img.swapaxes(0, 1)   # 0->1
img = img.swapaxes(1, 2)    # 0->2
# 矩陣維度轉(zhuǎn)換方法
# img = img.transpose(1, 2, 0)  # 這是正常的圖像順序
plt.imshow(img)
plt.show()
圖像數(shù)據(jù)可視化

3.2.3. 直接從壓縮文件中讀取

(略)

四. mnist手寫數(shù)字?jǐn)?shù)據(jù)集

4.1. mnist手寫數(shù)字?jǐn)?shù)據(jù)集說明

  • 數(shù)據(jù)集一共70000個(gè)樣本,包含60000個(gè)訓(xùn)練樣本與10000個(gè)測(cè)試集樣本。
  • 返回的數(shù)據(jù)結(jié)構(gòu)是元組:
    • 元組第一個(gè)元素也是元組,
      • 60000個(gè)訓(xùn)練樣本,元組格式(訓(xùn)練集,標(biāo)簽集)
    • 元組第一個(gè)元素也是元組
      • 10000個(gè)訓(xùn)練樣本,元組格式(訓(xùn)練集,標(biāo)簽集)

4.2. 數(shù)據(jù)集的讀取

4.2.1. 使用tensorflow模塊加載數(shù)據(jù)集

  1. 數(shù)據(jù)集加載代碼
import tensorflow as tf
import tensorflow.keras.datasets.mnist as mnist


(data_train, label_train), (data_test, label_test) = mnist.load_data()

print(data_train.shape, label_train.shape)   # 訓(xùn)練樣本集
print(data_test.shape, label_test.shape)   # 測(cè)試樣本集


(60000, 28, 28) (60000,)
(10000, 28, 28) (10000,)
  1. 數(shù)據(jù)集可視化
%matplotlib inline
import matplotlib.pyplot as plt
plt.imshow(data_train[0], cmap='gray')
plt.show()
數(shù)字圖像數(shù)據(jù)可視化

4.2.2. 從本地加載數(shù)據(jù)

4.2.2.1. 下載本地文件說明

  1. 下載地址

    • http://yann.lecun.com/exdb/mnist/
  2. 下載的文件說明:

    • 訓(xùn)練數(shù)據(jù):train-images.idx3-ubyte
    • 訓(xùn)練標(biāo)簽:train-labels.idx1-ubyte
    • 測(cè)試數(shù)據(jù):t10k-images.idx3-ubyte
    • 測(cè)試標(biāo)簽:t10k-labels.idx1-ubyte
  3. 數(shù)據(jù)集種圖像文件與標(biāo)簽文件的格式

圖像文件與標(biāo)簽文件的格式說明

4.2.2.2. 加載圖像數(shù)據(jù)集

  1. 加載圖像數(shù)據(jù)集的頭部meta信息
import struct
with open('./01datasets/minist/t10k-images.idx3-ubyte', 'br') as fd:
    # 讀取圖像的信息
    header_buf = fd.read(16)   # 16字節(jié),4個(gè)int整數(shù)
    # 按照字節(jié)解析頭信息(具體參考python SL的struct幫助)
    magic, nums, width, height = struct.unpack('>iiii', header_buf)  # 解析成四個(gè)整數(shù):>表示大端字節(jié)序,i表示4字節(jié)整數(shù)
    print('magic number:', magic)   # 魔法字一般用來表示文件類型與格式類型
    print('圖像數(shù)量:', nums)
    print('寬度:', width)
    print('高度:', height)
magic number: 2051
圖像數(shù)量: 10000
寬度: 28
高度: 28
  1. 加載圖像數(shù)據(jù)-循環(huán)方式
import struct
import numpy as np
imgs = []   # 格式1

with open('./01datasets/minist/t10k-images.idx3-ubyte', 'br') as fd:
    # 讀取圖像的信息
    header_buf = fd.read(16)   # 16字節(jié),4個(gè)int整數(shù)
    # 按照字節(jié)解析頭信息(具體參考python SL的struct幫助)
    magic, nums, width, height = struct.unpack('>iiii', header_buf)  # 解析成四個(gè)整數(shù):>表示大端字節(jié)序,i表示4字節(jié)整數(shù)
    # 保存成ndarray對(duì)象
    np_imgs = np.empty((nums, height, width))   # 格式2
    # 循環(huán)讀取圖像
    for i in range(nums):
        # 圖像緩沖
        img_buf = fd.read(width * height)
        # 解析圖像為
        img = struct.unpack('>'+str(width * height)+'B', img_buf)
        imgs.append(img)
        
        # ndarrary保存格式
        np_imgs[i] = np.array(img).reshape(height, width)
        
  1. 可視化圖像
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np

# 顯示讀取的格式1圖像
ax1 = plt.subplot(121)
ax1.imshow(np.array(imgs[0]).reshape(height, width), cmap='gray')

# 顯示讀取的格式2圖像
ax2 = plt.subplot(122)
ax2.imshow(np_imgs[0], cmap='gray')
plt.show()
數(shù)組圖像可視化
  1. 加載圖像-使用nparray的load功能
import struct

with open('./01datasets/minist/t10k-images.idx3-ubyte', 'br') as fd:
    # 讀取圖像的信息
    header_buf = fd.read(16)   # 16字節(jié),4個(gè)int整數(shù)
    # 按照字節(jié)解析頭信息(具體參考python SL的struct幫助)
    magic, nums, width, height = struct.unpack('>iiii', header_buf)  # 解析成四個(gè)整數(shù):>表示大端字節(jié)序,i表示4字節(jié)整數(shù)
    # 保存成ndarray對(duì)象
    imgs = np.fromfile(fd, dtype=np.uint8)
        
# 返回的所有剩余數(shù)據(jù)對(duì)象的格式
print(type(imgs))
print(imgs.shape)

# 重新reshape一下。
imgs = imgs.reshape(nums, height, width)
print(imgs.shape)

# 可視化讀取的圖像,驗(yàn)證是否正確
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np

plt.imshow(imgs[0], cmap='gray')
plt.show()
<class 'numpy.ndarray'>
(7840000,)
(10000, 28, 28)
數(shù)字圖像可視化

4.2.2.3. 加載標(biāo)簽數(shù)據(jù)

  1. 讀取標(biāo)簽頭
# t10k-labels.idx1-ubyte
import struct

with open('./01datasets/minist/t10k-labels.idx1-ubyte', 'br') as fd:
    # 讀取頭,8字節(jié)
    header_buf = fd.read(8)   # 16字節(jié),4個(gè)int整數(shù)
    # 解析頭信息
    magic, nums = struct.unpack('>ii' ,header_buf)  # 解析成2個(gè)整數(shù)
    print('魔法字:', magic)
    print('標(biāo)簽個(gè)數(shù)', nums)
魔法字: 2049
標(biāo)簽個(gè)數(shù) 10000
  1. 讀取標(biāo)簽- 循環(huán)字節(jié)方式
import struct

labels = []
with open('./01datasets/minist/t10k-labels.idx1-ubyte', 'br') as fd:
    # 讀取頭,8字節(jié)
    header_buf = fd.read(8)   # 16字節(jié),4個(gè)int整數(shù)
    # 解析頭信息
    magic, nums = struct.unpack('>ii' ,header_buf)  # 解析成2個(gè)整數(shù)
    # 循環(huán)讀取標(biāo)簽,每個(gè)標(biāo)簽一個(gè)字節(jié)
    for i in range(nums):
        label_buf = fd.read(1)   # 讀取一個(gè)字節(jié)
        labels.append(struct.unpack('>B', label_buf))    # 記得返回的是元組
print(labels[0])        
(7,)
  1. 讀取標(biāo)簽-ndarray的fromfile函數(shù)
import struct

with open('./01datasets/minist/t10k-labels.idx1-ubyte', 'br') as fd:
    # 讀取頭,8字節(jié)
    header_buf = fd.read(8)   # 16字節(jié),4個(gè)int整數(shù)
    # 解析頭信息
    magic, nums = struct.unpack('>ii' ,header_buf)  # 解析成2個(gè)整數(shù)
    # 循環(huán)讀取標(biāo)簽,每個(gè)標(biāo)簽一個(gè)字節(jié)
    labels = np.fromfile(fd, np.uint8) 

print(labels[0])
7

4.2.3. 圖片格式的數(shù)據(jù)集

  • 還可以下載到原始的圖片格式的手寫數(shù)字?jǐn)?shù)據(jù)集。
  • 圖片的處理與加載速度慢一點(diǎn),處理麻煩點(diǎn),需要可以手工處理;

五. 時(shí)尚mnist數(shù)據(jù)集

5.1. 時(shí)尚mnist數(shù)據(jù)集介紹

  • 該數(shù)據(jù)集與mnist手寫數(shù)字?jǐn)?shù)據(jù)集一樣,也是70000樣本,分成10類,差別就是類別是單件服飾等物品。

  • 該數(shù)據(jù)集因?yàn)?code>https://storage.googleapis.com/tensorflow/tf-keras-datasets/train-labels-idx1-ubyte.gz無法訪問,所以我們可以從其他地方獲取。

    • https://github.com/zalandoresearch/fashion-mnist

5.2. 數(shù)據(jù)集的讀取

5.2.1. 使用tensorflow讀取

  • 這種方式因?yàn)閿?shù)據(jù)集在google的官網(wǎng),該官網(wǎng)在中國(guó)目前無法訪問,所以下面代碼執(zhí)行一般會(huì)報(bào)網(wǎng)絡(luò)錯(cuò)誤。
  • 錯(cuò)誤提示為:
    • Exception: URL fetch failure on https://storage.googleapis.com/tensorflow/tf-keras-datasets/train-labels-idx1-ubyte.gz: None -- [Errno 65] No route to host
%matplotlib inline
import matplotlib.pyplot as plt
import tensorflow as tf
import tensorflow.keras.datasets.fashion_mnist as fashion_mnist


# (data_train, label_train), (data_test, label_test) = fashion_mnist.load_data()

# print(data_train.shape, label_train.shape)   # 訓(xùn)練樣本集
# print(data_test.shape, label_test.shape)   # 測(cè)試樣本集

# plt.imshow(data_train[0], cmap='gray')
# plt.show()

5.2.2. 從本地加載數(shù)據(jù)

5.2.2.1. 下載本地文件

  1. 下載地址:

    • https://github.com/zalandoresearch/fashion-mnist/tree/master/data/fashion
    • https://www.kaggle.com/zalando-research/fashionmnist
  2. 下載文件說明:

    • 訓(xùn)練圖像文件:train-images-idx3-ubyte
    • 訓(xùn)練標(biāo)簽文件:train-labels-idx1-ubyte
    • 測(cè)試圖像文件:t10k-images-idx3-ubyte
    • 測(cè)試標(biāo)簽文件:t10k-labels-idx1-ubyte


      下載的文件列表
  1. 讀取圖像數(shù)據(jù)并可視化
import struct

with open('./01datasets/fashion-mnist/t10k-images-idx3-ubyte', 'br') as fd:
    # 讀取圖像的信息
    header_buf = fd.read(16)   # 16字節(jié),4個(gè)int整數(shù)
    # 按照字節(jié)解析頭信息(具體參考python SL的struct幫助)
    magic, nums, width, height = struct.unpack('>iiii', header_buf)  # 解析成四個(gè)整數(shù):>表示大端字節(jié)序,i表示4字節(jié)整數(shù)
    # 保存成ndarray對(duì)象
    imgs = np.fromfile(fd, dtype=np.uint8)

# 重新reshape一下。
imgs = imgs.reshape(nums, height, width)
print(imgs.shape)

# 可視化讀取的圖像,驗(yàn)證是否正確
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np

plt.imshow(imgs[0], cmap='gray')
plt.show()
(10000, 28, 28)
圖像數(shù)據(jù)可視化
  1. 讀取標(biāo)簽數(shù)據(jù)
import struct

with open('./01datasets/fashion-mnist/t10k-labels-idx1-ubyte', 'br') as fd:
    # 讀取頭,8字節(jié)
    header_buf = fd.read(8)   # 16字節(jié),4個(gè)int整數(shù)
    # 解析頭信息
    magic, nums = struct.unpack('>ii' ,header_buf)  # 解析成2個(gè)整數(shù)
    # 循環(huán)讀取標(biāo)簽,每個(gè)標(biāo)簽一個(gè)字節(jié)
    labels = np.fromfile(fd, np.uint8) 

print(labels[0])
9
  1. 類別說明
    • 關(guān)于fashion-mnist的說明在如下網(wǎng)站有詳細(xì)介紹:https://www.kaggle.com/zalando-research/fashionmnist
      • 0:T恤(T-shirt/top)
      • 1:褲子(Trouser)
      • 2:套頭衫(Pullover)
      • 3:連衣裙(Dress)
      • 4:外套(Coat)
      • 5:涼鞋(Sandal)
      • 6:襯衫(Shirt)
      • 7:運(yùn)動(dòng)鞋(Sneaker)
      • 8:包(Bag)
      • 9:靴子(Ankle boot)

六. IMDB情緒分類數(shù)據(jù)集

6.1. IMDB數(shù)據(jù)集說明

  1. MDB數(shù)據(jù)集包含來自互聯(lián)網(wǎng)的50000條嚴(yán)重兩極分化的評(píng)論,該數(shù)據(jù)被分為用于訓(xùn)練的25000條評(píng)論和用于測(cè)試的25000條評(píng)論,訓(xùn)練集和測(cè)試集都包含50%的正面評(píng)價(jià)和50%的負(fù)面評(píng)價(jià)。

  2. 該數(shù)據(jù)集已經(jīng)經(jīng)過預(yù)處理:評(píng)論(單詞序列)已經(jīng)被轉(zhuǎn)換為整數(shù)序列,其中每個(gè)整數(shù)代表字典中的某個(gè)單詞。

6.2. 數(shù)據(jù)集讀取

6.2.1. 使用tensorflow模塊加載

  • 該加載方式因?yàn)闊o法訪問google官方站點(diǎn),所以不能使用,可以在網(wǎng)絡(luò)其他地方下載。
import tensorflow.keras.datasets.imdb as imdb
# (x_train, y_train), (x_test, y_test) = imdb.load_data()

6.2.2. 從本地文件加載數(shù)據(jù)

  1. 文件下載
    • 下載keras支持的格式
      • https://download.csdn.net/download/luffysman/10959289
        • 或者通過網(wǎng)絡(luò)搜索
    • 下載地址完整的文本數(shù)據(jù)
      • http://ai.stanford.edu/~amaas/data/sentiment/
下載的情感分類數(shù)據(jù)集文件
  1. 文件說明

    • 詞匯表索引文件:imdb_word_index.json
    • IMDB數(shù)據(jù)集文件:imdb.npz
  2. 使用數(shù)據(jù)集文件

    • 因?yàn)閿?shù)據(jù)集使用二進(jìn)制存放,需要知道數(shù)據(jù)集的格式,目前沒有數(shù)據(jù)集格式說明,所以使用keras的本地機(jī)制來加載IMDB數(shù)據(jù)集。
    • 使用方法:
      • 下載好文件;
      • 拷貝到默認(rèn)工作目錄:'~/.keras/datasets/',因?yàn)樵撃夸浭悄J(rèn)加載路徑;
      • 在load_data中使用path參數(shù)指定加載的文件


        Keras默認(rèn)的數(shù)據(jù)集緩沖目錄
  1. 加載數(shù)據(jù)集代碼
import tensorflow.keras.datasets.imdb as imdb
(x_train, y_train), (x_test, y_test) = imdb.load_data(path='imdb.npz')
x_train.shape, y_train.shape, x_test.shape, y_test.shape, 
((25000,), (25000,), (25000,), (25000,))
  1. 數(shù)據(jù)格式
    • 數(shù)據(jù)是處理好的整數(shù)格式。
print(x_train[0])
[1, 14, 22, 16, 43, 530, 973, 1622, 1385, 65, 458, 4468, 66, 3941, 4, 173, 36, 256, 5, 25, 100, 43, 838, 112, 50, 670, 22665, 9, 35, 480, 284, 5, 150, 4, 172, 112, 167, 21631, 336, 385, 39, 4, 172, 4536, 1111, 17, 546, 38, 13, 447, 4, 192, 50, 16, 6, 147, 2025, 19, 14, 22, 4, 1920, 4613, 469, 4, 22, 71, 87, 12, 16, 43, 530, 38, 76, 15, 13, 1247, 4, 22, 17, 515, 17, 12, 16, 626, 18, 19193, 5, 62, 386, 12, 8, 316, 8, 106, 5, 4, 2223, 5244, 16, 480, 66, 3785, 33, 4, 130, 12, 16, 38, 619, 5, 25, 124, 51, 36, 135, 48, 25, 1415, 33, 6, 22, 12, 215, 28, 77, 52, 5, 14, 407, 16, 82, 10311, 8, 4, 107, 117, 5952, 15, 256, 4, 31050, 7, 3766, 5, 723, 36, 71, 43, 530, 476, 26, 400, 317, 46, 7, 4, 12118, 1029, 13, 104, 88, 4, 381, 15, 297, 98, 32, 2071, 56, 26, 141, 6, 194, 7486, 18, 4, 226, 22, 21, 134, 476, 26, 480, 5, 144, 30, 5535, 18, 51, 36, 28, 224, 92, 25, 104, 4, 226, 65, 16, 38, 1334, 88, 12, 16, 283, 5, 16, 4472, 113, 103, 32, 15, 16, 5345, 19, 178, 32]
  1. 加載詞匯索引數(shù)據(jù)集
    • 返回字典類型:key是單詞,values是索引
word_dict = imdb.get_word_index(path='imdb_word_index.json')
word_dict['woods']  
1408
  1. 把情緒分類數(shù)據(jù)還原為文本
x_ints = x_train[0]
x_texts = []
for item in x_ints:
    x_texts.append(list (word_dict.keys()) [list (word_dict.values()).index (item)])
    
print(x_texts)

['the', 'as', 'you', 'with', 'out', 'themselves', 'powerful', 'lets', 'loves', 'their', 'becomes', 'reaching', 'had', 'journalist', 'of', 'lot', 'from', 'anyone', 'to', 'have', 'after', 'out', 'atmosphere', 'never', 'more', 'room', 'titillate', 'it', 'so', 'heart', 'shows', 'to', 'years', 'of', 'every', 'never', 'going', 'villaronga', 'help', 'moments', 'or', 'of', 'every', 'chest', 'visual', 'movie', 'except', 'her', 'was', 'several', 'of', 'enough', 'more', 'with', 'is', 'now', 'current', 'film', 'as', 'you', 'of', 'mine', 'potentially', 'unfortunately', 'of', 'you', 'than', 'him', 'that', 'with', 'out', 'themselves', 'her', 'get', 'for', 'was', 'camp', 'of', 'you', 'movie', 'sometimes', 'movie', 'that', 'with', 'scary', 'but', 'pratfalls', 'to', 'story', 'wonderful', 'that', 'in', 'seeing', 'in', 'character', 'to', 'of', '70s', 'musicians', 'with', 'heart', 'had', 'shadows', 'they', 'of', 'here', 'that', 'with', 'her', 'serious', 'to', 'have', 'does', 'when', 'from', 'why', 'what', 'have', 'critics', 'they', 'is', 'you', 'that', "isn't", 'one', 'will', 'very', 'to', 'as', 'itself', 'with', 'other', 'tricky', 'in', 'of', 'seen', 'over', 'landed', 'for', 'anyone', 'of', "gilmore's", 'br', "show's", 'to', 'whether', 'from', 'than', 'out', 'themselves', 'history', 'he', 'name', 'half', 'some', 'br', 'of', "'n", 'odd', 'was', 'two', 'most', 'of', 'mean', 'for', '1', 'any', 'an', 'boat', 'she', 'he', 'should', 'is', 'thought', 'frog', 'but', 'of', 'script', 'you', 'not', 'while', 'history', 'he', 'heart', 'to', 'real', 'at', 'barrel', 'but', 'when', 'from', 'one', 'bit', 'then', 'have', 'two', 'of', 'script', 'their', 'with', 'her', 'nobody', 'most', 'that', 'with', "wasn't", 'to', 'with', 'armed', 'acting', 'watch', 'an', 'for', 'with', 'heartfelt', 'film', 'want', 'an']
  1. 字典的key與value交換
# 可以把字典的key與value交換
new_word_dict = {v : k for k, v in word_dict.items()}
print(new_word_dict[1])
the

七. 路透社主題分類數(shù)據(jù)集

7.1. 路透社主題分類數(shù)據(jù)集說明

  • 數(shù)據(jù)集來源于路透社的 11,228 條新聞文本,總共分為 46 個(gè)主題。
  • 與 IMDB 數(shù)據(jù)集一樣,每條新聞都被編碼為一個(gè)詞索引的序列。

7.2. 加載數(shù)據(jù)集

7.2.1. 使用tensorflow加載數(shù)據(jù)集

  • 因?yàn)間oogle無法訪問的緣故,所以直接從網(wǎng)絡(luò)下載會(huì)出現(xiàn)失敗。
import tensorflow.keras.datasets.reuters as reuters
# (x_train, y_train), (x_test, y_test) = reuters.load_data()
# x_train.shape, y_train.shape, x_test.shape, y_test.shape, 

7.2.2. 使用本地?cái)?shù)據(jù)集

  1. 下載
    • 完整原始數(shù)據(jù)集下載:http://www.daviddlewis.com/resources/testcollections/reuters21578/
    • npz文件下載:使用網(wǎng)絡(luò)搜索
  2. 拷貝到用戶主目錄下:
    • ~/.keras/datasets/
      數(shù)據(jù)集緩沖目錄
  1. 加載數(shù)據(jù)集代碼
import tensorflow.keras.datasets.reuters as reuters
(x_train, y_train), (x_test, y_test) = reuters.load_data(path='reuters.npz')
x_train.shape, y_train.shape, x_test.shape, y_test.shape, 
((8982,), (8982,), (2246,), (2246,))
  1. 數(shù)據(jù)集顯示
print(x_train[0])
[1, 27595, 28842, 8, 43, 10, 447, 5, 25, 207, 270, 5, 3095, 111, 16, 369, 186, 90, 67, 7, 89, 5, 19, 102, 6, 19, 124, 15, 90, 67, 84, 22, 482, 26, 7, 48, 4, 49, 8, 864, 39, 209, 154, 6, 151, 6, 83, 11, 15, 22, 155, 11, 15, 7, 48, 9, 4579, 1005, 504, 6, 258, 6, 272, 11, 15, 22, 134, 44, 11, 15, 16, 8, 197, 1245, 90, 67, 52, 29, 209, 30, 32, 132, 6, 109, 15, 17, 12]
  1. 把路透社主題數(shù)據(jù)集還原為文本
word_dict = imdb.get_word_index(path='reuters_word_index.json')
x_ints = x_train[0]
x_texts = []
for item in x_ints:
    x_texts.append(list (word_dict.keys()) [list (word_dict.values()).index (item)])
    
print(x_texts)
['the', 'kazuo', 'operandi', 'in', 'out', 'i', 'several', 'to', 'have', 'always', 'place', 'to', 'catholic', 'plot', 'with', 'women', 'horror', 'made', 'can', 'br', "don't", 'to', 'film', 'characters', 'is', 'film', 'does', 'for', 'made', 'can', 'great', 'you', 'lead', 'he', 'br', 'what', 'of', 'good', 'in', 'believable', 'or', 'comedy', 'work', 'is', 'old', 'is', 'first', 'this', 'for', 'you', '10', 'this', 'for', 'br', 'what', 'it', 'christians', 'ideas', "they're", 'is', 'although', 'is', 'different', 'this', 'for', 'you', 'while', 'has', 'this', 'for', 'with', 'in', 'between', 'military', 'made', 'can', 'very', 'all', 'comedy', 'at', 'an', 'say', 'is', 'being', 'for', 'movie', 'that']

八. 波士頓住房?jī)r(jià)格數(shù)據(jù)集

  • 該數(shù)據(jù)集與上面一樣。下面直接上代碼(記得下載數(shù)據(jù)集文件,并拷貝到用戶主目錄下:~/.keras/datasets/)。
    Keras數(shù)據(jù)緩沖目錄

8.1. 波士頓住房?jī)r(jià)格數(shù)據(jù)集說明

  • 該數(shù)據(jù)集是一個(gè)回歸數(shù)據(jù)集。
  • 每個(gè)類的觀察值數(shù)量是均等的,共有 506 個(gè)觀察,13 個(gè)輸入變量和1個(gè)輸出變量。每條數(shù)據(jù)包含房屋以及房屋周圍的詳細(xì)信息。
    • 輸入數(shù)據(jù):
      1. CRIM:城鎮(zhèn)人均犯罪率。
      2. ZN:住宅用地超過 25000 sq.ft. 的比例。
      3. INDUS:城鎮(zhèn)非零售商用土地的比例。
      4. CHAS:查理斯河空變量(如果邊界是河流,則為1;否則為0)。
      5. NOX:一氧化氮濃度。
      6. RM:住宅平均房間數(shù)。
      7. AGE:1940 年之前建成的自用房屋比例。
      8. DIS:到波士頓五個(gè)中心區(qū)域的加權(quán)距離。
      9. RAD:輻射性公路的接近指數(shù)。
      10. TAX:每 10000 美元的全值財(cái)產(chǎn)稅率。
      11. PTRATIO:城鎮(zhèn)師生比例。
      12. B:1000(Bk-0.63)^ 2,其中 Bk 指代城鎮(zhèn)中黑人的比例。
      13. LSTAT:人口中地位低下者的比例。
      14. MEDV:自住房的平均房?jī)r(jià),以千美元計(jì)。
    • 輸出數(shù)據(jù):
      • 預(yù)測(cè)平均值的基準(zhǔn)性能的均方根誤差(RMSE)是約 9.21 千美元。

8.2. 加載數(shù)據(jù)集

  • 因?yàn)樵摂?shù)據(jù)集也是在google.com中,所以直接使用本地?cái)?shù)據(jù)集。
    • 也可以直接使用sklearn獲取boston房?jī)r(jià)數(shù)據(jù)集。
import tensorflow.keras.datasets.boston_housing as boston_housing
(x_train, y_train), (x_test, y_test) = boston_housing.load_data(path='boston_housing.npz')
x_train.shape, y_train.shape, x_test.shape, y_test.shape, 
((404, 13), (404,), (102, 13), (102,))

九. 備注

  1. 在調(diào)用的時(shí)候,容易出現(xiàn)的問題
    ValueError: Object arrays cannot be loaded when allow_pickle=False
  • 出問題的原因是numpy的版本不匹配造成的。
  1. 本文種,路透社主題分類數(shù)據(jù)集加載需要的numpy版本是1.16.2。在1.16.3環(huán)境中會(huì)報(bào)錯(cuò)。
    • ValueError: Object arrays cannot be loaded when allow_pickle=False
  1. 在sklearn能獲取的數(shù)據(jù)集


    sklearn提供的波士頓數(shù)據(jù)集

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容