CNN卷积神经网络实现图像识别

本文详细介绍了如何利用Python和TensorFlow库构建卷积神经网络(CNN)进行图像识别。通过实例,深入探讨了CNN的架构、训练过程以及如何优化模型性能。读者将学习到如何预处理数据、定义网络层、训练模型并评估其在图像识别任务上的表现。
摘要由CSDN通过智能技术生成

# 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/&
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

tong_brickmoving

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值