二元分類 Cat and Dog

二元分類 Cat and Dog

數(shù)據(jù)來源

Kaggle-Cat and Dog https://www.kaggle.com/tongpython/cat-and-dog

講解

Coursera-Convolutional Neural Networks in TensorFlow-Exploring a Larger Dataset-Training with the cats vs. dogs dataset

目的

數(shù)據(jù)集為貓和狗的圖片寸五,使用TensorFlow將兩者分類旁蔼。
作者向?qū)嵺`一下講解中的過程锨苏,因此分類的準(zhǔn)確率不高。

待測(cè)試

  • 對(duì)訓(xùn)練和測(cè)試集使用數(shù)據(jù)增強(qiáng)

代碼

  • 定義圖片目錄
import os
# let's define each of these directories
# Directory with our training cat pictures
train_cat_dir = os.path.join('/kaggle/input/training_set/training_set/cats')
# Directory with our training dog pictures
train_dog_dir = os.path.join('/kaggle/input/training_set/training_set/dogs') 
  • 看看圖片名稱和圖片總數(shù)
# let's see what the filenames look like in the training directories
train_cat_names = os.listdir(train_cat_dir)
print(train_cat_names[:10])

train_dog_names = os.listdir(train_dog_dir)
print(train_dog_names[:10])

# The total number of images in the directories
print('total training cat images:', len(os.listdir(train_cat_dir)))
print('total training dog images:', len(os.listdir(train_dog_dir)))
  • 看看圖片示例
# let's take a look at a few pictures to get a better sense of what they look like
import matplotlib.pyplot as plt
import matplotlib.image as mpimg

# Parameters for our graph; we'll output images in a 4x4 configuration
nrows = 4
ncols = 4

# Index for iterating over images
pic_index = 0

# Set up matplotlib fig, and size it to fit 4x4 pics
fig = plt.gcf()
fig.set_size_inches(ncols * 4, nrows * 4)

pic_index += 8
next_cat_pix = [os.path.join(train_cat_dir, fname) 
                for fname in train_cat_names[pic_index-8:pic_index]]
next_dog_pix = [os.path.join(train_dog_dir, fname) 
                for fname in train_dog_names[pic_index-8:pic_index]]

for i, img_path in enumerate(next_cat_pix+next_dog_pix):
  # Set up subplot; subplot indices start at 1
  sp = plt.subplot(nrows, ncols, i + 1)
  sp.axis('Off') # Don't show axes (or gridlines)

  img = mpimg.imread(img_path)
  plt.imshow(img)

plt.show()
  • 設(shè)計(jì)NN
# import tensorflow
import tensorflow as tf
# add the densely connected layers
model = tf.keras.models.Sequential([
    # Note the input shape is the desired size of the image 300x300 with 3 bytes color
    # This is the first convolution
    tf.keras.layers.Conv2D(16, (3,3), activation='relu', input_shape=(300, 300, 3)),
    tf.keras.layers.MaxPooling2D(2, 2),
    # The second convolution
    tf.keras.layers.Conv2D(32, (3,3), activation='relu'),
    tf.keras.layers.MaxPooling2D(2,2),
    # The third convolution
    tf.keras.layers.Conv2D(64, (3,3), activation='relu'),
    tf.keras.layers.MaxPooling2D(2,2),
    # The fourth convolution
    tf.keras.layers.Conv2D(64, (3,3), activation='relu'),
    tf.keras.layers.MaxPooling2D(2,2),
    # The fifth convolution
    tf.keras.layers.Conv2D(64, (3,3), activation='relu'),
    tf.keras.layers.MaxPooling2D(2,2),
    # Flatten the results to feed into a DNN
    tf.keras.layers.Flatten(),
    # 512 neuron hidden layer
    tf.keras.layers.Dense(512, activation='relu'),
    # Only 1 output neuron. 
    tf.keras.layers.Dense(1, activation='sigmoid')
])

# prints a summary of the NN
model.summary()
  • 使用二元交叉熵?fù)p失函數(shù)
# train our model with the binary_crossentropy loss
from tensorflow.keras.optimizers import RMSprop

model.compile(loss='binary_crossentropy',
              optimizer=RMSprop(lr=0.001),
              metrics=['acc'])
  • 準(zhǔn)備訓(xùn)練和測(cè)試數(shù)據(jù)
#  set up data generators
from tensorflow.keras.preprocessing.image import ImageDataGenerator

# All images will be rescaled by 1./255
train_datagen = ImageDataGenerator(rescale=1/255)
test_datagen = ImageDataGenerator(rescale=1/255)

# Flow training images in batches of 128 using train_datagen generator
train_generator = train_datagen.flow_from_directory(
        '/kaggle/input/training_set/training_set/',  # This is the source directory for training images
        target_size=(300, 300),  # All images will be resized 
        batch_size=128,
        # Since we use binary_crossentropy loss, we need binary labels
        class_mode='binary')
# Flow test images in batches of 128 using train_datagen generator
test_generator = test_datagen.flow_from_directory(
        '/kaggle/input/test_set/test_set/',  # This is the source directory for training images
        target_size=(300, 300),  # All images will be resized 
        batch_size=128,
        # Since we use binary_crossentropy loss, we need binary labels
        class_mode='binary')
  • 訓(xùn)練
#  train for 25 epochs
history = model.fit_generator(
      train_generator,
      steps_per_epoch=8,  
      epochs=25,
      validation_data = test_generator,
      validation_steps = 8,
      verbose=1)
  • 打印一下訓(xùn)練和測(cè)試的acc和loss
# plot
import matplotlib.pyplot as plt
acc= history.history['acc']
val_acc= history.history['val_acc']
loss= history.history['loss']
val_loss= history.history['val_loss']
epochs=range(len(acc))
plt.plot(epochs,acc,'bo',label='Training accuracy')
plt.plot(epochs,val_acc,'b',label='Validation accuracy')
plt.title('Training and validation accuracy')
plt.legend()
plt.figure()

plt.plot(epochs,loss,'bo',label='Training loss')
plt.plot(epochs,val_loss,'b',label='Training loss')
plt.title('Training and validation loss')
plt.legend()
plt.show()
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末棺聊,一起剝皮案震驚了整個(gè)濱河市蚓炬,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌躺屁,老刑警劉巖肯夏,帶你破解...
    沈念sama閱讀 211,042評(píng)論 6 490
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡驯击,警方通過查閱死者的電腦和手機(jī)烁兰,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 89,996評(píng)論 2 384
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來徊都,“玉大人沪斟,你說我怎么就攤上這事∠窘茫” “怎么了主之?”我有些...
    開封第一講書人閱讀 156,674評(píng)論 0 345
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)李根。 經(jīng)常有香客問我槽奕,道長(zhǎng),這世上最難降的妖魔是什么房轿? 我笑而不...
    開封第一講書人閱讀 56,340評(píng)論 1 283
  • 正文 為了忘掉前任粤攒,我火速辦了婚禮,結(jié)果婚禮上囱持,老公的妹妹穿的比我還像新娘夯接。我一直安慰自己,他們只是感情好纷妆,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,404評(píng)論 5 384
  • 文/花漫 我一把揭開白布盔几。 她就那樣靜靜地躺著,像睡著了一般掩幢。 火紅的嫁衣襯著肌膚如雪问欠。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 49,749評(píng)論 1 289
  • 那天粒蜈,我揣著相機(jī)與錄音顺献,去河邊找鬼。 笑死注整,一個(gè)胖子當(dāng)著我的面吹牛度硝,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播蕊程,決...
    沈念sama閱讀 38,902評(píng)論 3 405
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼藻茂!你這毒婦竟也來了玫恳?” 一聲冷哼從身側(cè)響起优俘,我...
    開封第一講書人閱讀 37,662評(píng)論 0 266
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎惭婿,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體财饥,經(jīng)...
    沈念sama閱讀 44,110評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡折晦,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,451評(píng)論 2 325
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片暴拄。...
    茶點(diǎn)故事閱讀 38,577評(píng)論 1 340
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖响驴,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情豁鲤,我是刑警寧澤,帶...
    沈念sama閱讀 34,258評(píng)論 4 328
  • 正文 年R本政府宣布琳骡,位于F島的核電站讼溺,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏怒坯。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,848評(píng)論 3 312
  • 文/蒙蒙 一视译、第九天 我趴在偏房一處隱蔽的房頂上張望归敬。 院中可真熱鬧酷含,春花似錦、人聲如沸第美。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,726評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至躯舔,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間粥庄,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 31,952評(píng)論 1 264
  • 我被黑心中介騙來泰國(guó)打工惜互, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留琳拭,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 46,271評(píng)論 2 360
  • 正文 我出身青樓坑鱼,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親鲁沥。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,452評(píng)論 2 348