本篇文章内容来自 Coursera: Convolutional Neural Networks in TensorFlow Week 1-2。提供方 deeplearning.ai,讲师 Laurence Moroney。
Case: 实现猫狗图像的智能识别,Dogs vs. Cats (已结束)
Code on GitHub 基本模型, Augmentation
Code on Google Colab 基本模型, Augmentation
Google Colab 类似一个在线的 IPython Notebook,不需要另外准备数据,但国内应该是需要梯子才能上。 GitHub 上提供了数据的路径和完整的 code。
接上一篇文章所说,我最近选择 DeepLearning.AI TensorFlow Developer 专业证书 作为接着 Machine Learning 后的另一个学习的项目。因为 Tensorflow 是主攻 Deep Learning,相比之前常用的 scikit-learn 中的工具还是有一些区别,并且在当下的 AI 大趋势下出现的频率越来越高,所以我就想分享一些我在学习中接触到的新的、容易上手的项目,帮助感兴趣的同学可以快速了解和运用这些工具,同时也可以帮助到未来失忆的我,hhh
基本模型
相比之前 Kaggle 上 Titanic 或者 House Price 的项目,这次的数据是以图片的形式存在的,所以它也有另外的标注方法。Keras 中使用的是通过将不同 category 数据存入不同文件路径实现 training set 数据的标注。以Dogs vs. Cats 为例,这里首先需要两层的分类。第一层将所有数据分为 training 和 testing,前者用于训练模型,后者用于 cross validation。第二层将 training 和 testing 中的数据归入 cats 和 dogs 实现数据的标注。
在数据的预处理中,如果数据来源只有 cats 和 dogs 两个分类,那么就需要按照一定的比例将原始数据随机的归入到 training set 和 testing set 中。下面的 code 主要就是实现了这一功能,(来自课程作业…)
# 这里假设原文件为两个文件夹,分别存有cats的图片文件和dogs的图片文件
# create directories
try:
os.mkdir('/tmp/cats-v-dogs')
os.mkdir('/tmp/cats-v-dogs/training')
os.mkdir('/tmp/cats-v-dogs/testing')
os.mkdir('/tmp/cats-v-dogs/training/cats')
os.mkdir('/tmp/cats-v-dogs/training/dogs')
os.mkdir('/tmp/cats-v-dogs/testing/cats')
os.mkdir('/tmp/cats-v-dogs/testing/dogs')
except OSError:
pass
这里有必要先筛选掉空白文件,以免在之后的模型处理中造成困难,
# 创建函数,首先移除无效文件,之后根据SPLIT_SIZE将原数据随机分入training和testing sets
def split_data(SOURCE, TRAINING, TESTING, SPLIT_SIZE):
# SOURCE表示数据原文件
# TRAINING和TESTING表示储存分离后文件的dictionaries
files = []
for filename in os.listdir(SOURCE):
file = SOURCE + filename
if os.path.getsize(file) > 0:
files.append(filename)
else:
print(filename + " is zero length, so ignoring it!")
training_length = int(len(files) * SPLIT_SIZE)
testing_length = int(len(files) - training_length)
shuffled_set = random.sample(files, len(files))
training_set = shuffled_set[0:training_length]
testing_set = shuffled_set[-testing_length:]
for filename in training_set:
this_file = SOURCE + filename
destination = TRAINING + filename
copyfile(this_file, destination)
for filename in testing_set:
this_file = SOURCE + filename
destination = TESTING + filename
copyfile(this_file, destination)