# coding: utf-8
# In[2]:
import urllib.request
import os
import tarfile
import pickle as p
import numpy as np
import tensorflow as tf
# ## 1、下载数据集
# In[3]:
filepath = 'data/cifar-10-python.tar.gz'
if not os.path.exists("data/cifar-10-batches-py"):
tfile = tarfile.open("data/cifar-10-python.tar.gz" , 'r:gz')
result=tfile.extractall("data/")
print("Extracted to ./data/cifar-10-batches-py/")
else:
print("Directory already exists.")
# # 2、导入CIFAR数据集
# In[4]:
def load_CIFAR_batch(filename):
""" load single batch of cifar """
with open(filename, 'rb')as f:
#—个样本由标签和图像数据组成
# <i x label> <3072 x pixel>(3072=32x32x3)
#..
# <1 x label> <3072 x pixel>
data_dict = p.load(f,encoding='bytes')
images= data_dict[b'data']
labels = data_dict[b'labels']
#把原始数据结构调整为:BCWH
images = images.reshape(10000,3,32,32)
# tensorflow处理图像数据的结构:BWHC
#把通道数据C移动到最后一个维度
images = images.transpose (0,2,3,1)
labels = np.array(labels)
return images, labels
# In[5]:
def load_CIFAR_data(data_dir):
"""load CIFAR data"""
images_train=[]
labels_train=[]
for i in range(5):
f=os.path.join(data_dir,'data_batch_%d'% (i+1))
print('loading ',f)
#调用load_CIFAR_batch( )获得批量的图像及其对应的标签
image_batch,label_batch=load_CIFAR_batch(f)
images_train.append(image_batch)
labels_train.append(label_batch)
Xtrain=np.concatenate(images_train)
Ytrain=np.concatenate(labels_train)
del image_batch ,label_batch
Xtest, Ytest=load_CIFAR_batch(os.path.join(data_dir, 'test_batch'))
print('finished loadding CIFAR-10 data')
#返回训练集的图像和标签,测试集的图像和标签
return Xtrain,Ytrain,Xtest,Ytest
data_dir = 'data/cifar-10-batches-py/&
CNN卷积神经网络实现图像识别
于 2021-05-13 11:21:51 首次发布
本文详细介绍了如何利用Python和TensorFlow库构建卷积神经网络(CNN)进行图像识别。通过实例,深入探讨了CNN的架构、训练过程以及如何优化模型性能。读者将学习到如何预处理数据、定义网络层、训练模型并评估其在图像识别任务上的表现。
摘要由CSDN通过智能技术生成