基于卷积神经网络的图像分类
TensorFlow环境搭建
TensorFlow安装参考:
https://www.cnblogs.com/HongjianChen/p/8385547.html.
首先建立一个名为TensorFlow的environment
建立TensorFlow环境后,下载TensorFlow和keras
然后打开anaconda 进入TensorFlow环境下载jupyter
进入anaconda prompt 使用activate tensorflow进入tensorflow环境,然后cd/d xxx(自己的jupyter notebook路径)到该路径下后,输入jupyter notebook打开jupyter,就可以运行程序了。
猫狗数据集下载准备
可以通过网盘下载:https://pan.baidu.com/s/13hw4LK8ihR6-6-8mpjLKDA . 密码:dmp4
使用原始数据集直接训练
导入库和数据集
可以检测你的tensorflow和keras是否安装完成
import keras
keras.__version__
import os, shutil
首先准备数据集,将下载的train文件路径添加进去,而catdog文件夹是程序会自动创建的文件夹名称。程序是将猫和狗的图片分开,并将其分为训练集和验证集。
original_dataset_dir = 'F:\\Anaconda\\jupyter-notebook\\cats and dogs\\train\\train'
# The directory where we will
# store our smaller dataset
base_dir = 'F:\\Anaconda\\jupyter-notebook\\catdog'
os.mkdir(base_dir)
# Directories for our training,
# validation and test splits
train_dir = os.path.join(base_dir, 'train')
os.mkdir(train_dir)
validation_dir = os.path.join(base_dir, 'validation')
os.mkdir(validation_dir)
test_dir = os.path.join(base_dir, 'test')
os.mkdir(test_dir)
# Directory with our training cat pictures
train_cats_dir = os.path.join(train_dir, 'cats')
os.mkdir(train_cats_dir)
# Directory with our training dog pictures
train_dogs_dir = os.path.join(train_dir, 'dogs')
os.mkdir(train_dogs_dir)
# Directory with our validation cat pictures
validation_cats_dir = os.path.join(validation_dir, 'cats')
os.mkdir(validation_cats_dir)
# Directory with our validation dog pictures
validation_dogs_dir = os.path.join(validation_dir, 'dogs')
os.mkdir(validation_dogs_dir)
# Directory with our validation cat pictures
test_cats_dir = os.path.join(test_dir, 'cats')
os.mkdir(test_cats_dir)
# Directory with our validation dog pictures
test_dogs_dir = os.path.join(test_dir, 'dogs')
os.mkdir(test_dogs_dir)
# Copy first 1000 cat images to train_cats_dir
fnames = ['cat.{}.jpg'.format(i) for i in range(1000)]
for fname in fnames:
src = os.path.join(original_dataset_dir, fname)
dst = os.path.join(train_cats_dir, fname)
shutil.copyfile(src, dst)
# Copy next 500 cat images to validation_cats_dir
fnames = ['cat.{}.jpg'.format(i) for i in range(1000, 1500)]
for fname in fnames:
src = os.path.join(original_dataset_dir, fname)
dst = os.path.join(validation_cats_dir, fname)
shutil.copyfile(src, dst)
# Copy next 500 cat images to test_cats_dir
fnames = ['cat.{}.jpg'.format(i) for i in range(1500, 2000)]
for fname in fnames:
src = os.path.join(original_dataset_dir, fname)
dst = os.path.join(test_cats_dir, fname)
shutil.copyfile(src, dst)
# Copy first 1000 dog images to train_dogs_dir
fnames = ['dog.{}.jpg'.format(i) for i in range(1000)]
for fname in fnames:
src = os.path.join(original_dataset_dir, fname)
dst = os.path.joi