六、項目實戰---識別貓和狗

一、準備數據集

kagglecatsanddogs網上一搜一大堆,這里我就不上傳了,需要的話可以私信
在這里插入圖片描述
導包

import os
import zipfile
import random
import shutil
import tensorflow as tf
from tensorflow.keras.optimizers import RMSprop
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from shutil import copyfile

貓和狗的照片各12500張

print(len(os.listdir('./temp/cats/')))
print(len(os.listdir('./temp/dogs/')))
"""
12500
12500
"""

生成訓練數據文件夾和測試數據文件夾

import os
import zipfile
import random
import shutil
import tensorflow as tf
from tensorflow.keras.optimizers import RMSprop
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from shutil import copyfiledef create_dir(file_dir):if os.path.exists(file_dir):print("True")shutil.rmtree(file_dir)#刪除再創建os.makedirs(file_dir)else:os.makedirs(file_dir)cat_source_dir = "./temp/cats/"
train_cats_dir = "./temp/train/cats/"
test_cats_dir = "./temp/test/cats/"dot_source_dir = "./temp/dogs/"
train_dogs_dir = "./temp/train/dogs/"
test_dogs_dir = "./temp/test/dogs/"create_dir(train_cats_dir)#創建貓的訓練集文件夾
create_dir(test_cats_dir)#創建貓的測試集文件夾
create_dir(train_dogs_dir)#創建狗的訓練集文件夾
create_dir(test_dogs_dir)#創建狗的測試集文件夾"""
True
True
True
True
"""

在這里插入圖片描述
將總的貓狗圖像按9:1分成訓練集和測試集,貓和狗各12500張
最終temp/train/catstemp/train/dogs兩個文件夾下各12500 * 0.9=11250張
temp/test/catstemp/test/dogs這兩個文件夾下各12500 * 0.1=1250張
cats和dogs為總共的貓狗圖像
test和train為準備的數據集文件

import os
import zipfile
import random
import shutil
import tensorflow as tf
from tensorflow.keras.optimizers import RMSprop
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from shutil import copyfiledef split_data(source,train,test,split_size):files = []for filename in os.listdir(source):file = source + filenameif os.path.getsize(file)>0:files.append(filename)else:print(filename + "is zero file,please ignoring")train_length = int(len(files)*split_size)test_length = int(len(files)-train_length)shuffled_set = random.sample(files,len(files))train_set = shuffled_set[0:train_length]test_set = shuffled_set[-test_length:]for filename in train_set:this_file = source + filenamedestination = train + filenamecopyfile(this_file,destination)for filename in test_set:this_file = source + filenamedestination = test + filenamecopyfile(this_file,destination)cat_source_dir = "./temp/cats/"
train_cats_dir = "./temp/train/cats/"
test_cats_dir = "./temp/test/cats/"dot_source_dir = "./temp/dogs/"
train_dogs_dir = "./temp/train/dogs/"
test_dogs_dir = "./temp/test/dogs/"split_size = 0.9
split_data(cat_source_dir,train_cats_dir,test_cats_dir,split_size)
split_data(dog_source_dir,train_dogs_dir,test_dogs_dir,split_size)

二、模型的搭建和訓練

先對數據進行歸一化操作,預處理進行優化一下

import os
import zipfile
import random
import shutil
import tensorflow as tf
from tensorflow.keras.optimizers import RMSprop
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from shutil import copyfiletrain_dir = "./temp/train/"
train_datagen = ImageDataGenerator(rescale=1.0/255.0)#優化網絡,先進行歸一化操作
train_generator = train_datagen.flow_from_directory(train_dir,batch_size=100,class_mode='binary',target_size=(150,150))#二分類,訓練樣本的輸入的要一致validation_dir = "./temp/test/"
validation_datagen = ImageDataGenerator(rescale=1.0/255.0)
validation_generator = validation_datagen.flow_from_directory(validation_dir,batch_size=100,class_mode='binary',target_size=(150,150))
"""
Found 22500 images belonging to 2 classes.
Found 2500 images belonging to 2 classes.
"""

搭建模型架構

model = tf.keras.models.Sequential([tf.keras.layers.Conv2D(16,(3,3),activation='relu',input_shape=(150,150,3)),tf.keras.layers.MaxPooling2D(2,2),tf.keras.layers.Conv2D(32,(3,3),activation='relu'),tf.keras.layers.MaxPooling2D(2,2),tf.keras.layers.Conv2D(64,(3,3),activation='relu'),tf.keras.layers.MaxPooling2D(2,2),tf.keras.layers.Flatten(),tf.keras.layers.Dense(512,activation='relu'),tf.keras.layers.Dense(1,activation='sigmoid')
])
model.compile(optimizer=RMSprop(lr=0.001),loss='binary_crossentropy',metrics=['acc'])

訓練模型
225:因為數據一共22500張,貓和狗各12500張,其對于訓練集個11250張,故訓練集共22500張,在預處理第一段代碼中,batch_size=100設置了一批100個,故總共應該有225批
epochs=2:兩輪,也就是所有的樣本全部訓練一次
每輪包含225批,每一批有100張樣本

history = model.fit_generator(train_generator,epochs=2,#進行2輪訓練,每輪255批verbose=1,#要不記錄每次訓練的日志,1表示記錄validation_data=validation_generator)"""
Instructions for updating:
Use tf.cast instead.
Epoch 1/2
131/225 [================>.............] - ETA: 2:03 - loss: 0.7204 - acc: 0.6093
"""

history是模型運行過程的結果

三、分析訓練結果

import matplotlib.image as mpimg
import matplotlib.pyplot as pltacc = history.history['acc']
val_acc = history.history['val_acc']
loss = history.history['loss']
val_loss = history.history['val_loss']epochs = range(len(acc))

epoch太少了,導致是直線,多訓練幾輪實際應該是折線圖
準確率

plt.plot(epochs,acc,'r',"training accuracy")
plt.plot(epochs,val_acc,'b',"validation accuracy")
plt.title("training and validation accuracy")
plt.figure()

在這里插入圖片描述
損失值

plt.plot(epochs,loss,'r',"training loss")
plt.plot(epochs,val_loss,'b',"validation loss")
plt.figure()

在這里插入圖片描述

四、模型的使用驗證

import numpy as np
from google.colab import files
from tensorflow.keras.preprocessing import imageuploaded = files.upload()
for fn in uploaded.keys():path = 'G:/Juptyer_workspace/Tensorflow_mooc/sjj/test/' + fn#該路徑為要用模型測試的路徑img = image.load_img(path,target_size=(150,150))x = image.img_to_array(img)#多維數組x = np.expand_dims(x,axis=0)#拉伸images = np.vstack([x])#水平方向拉直classes = model.predict(images,batch_size=10)print(classes[0])if classes[0]>0.5:print(fn + "it is a dog")else:print(fn + "it is a cat")

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/377632.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/377632.shtml
英文地址,請注明出處:http://en.pswp.cn/news/377632.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

修改shell終端提示信息

PS1:就是用戶平時的提示符。PS2:第一行沒輸完,等待第二行輸入的提示符。公共設置位置:/etc/profile echo $PS1可以看到當前提示符設置例如:顯示綠色,并添加時間和shell版本export PS1"\[\e[32m\][\uyou are right…

java 字謎_計算字謎的出現次數

java 字謎Problem statement: 問題陳述: Given a string S and a word C, return the count of the occurrences of anagrams of the word in the text. Both string and word are in lowercase letter. 給定一個字符串S和一個單詞C ,返回該單詞在文本…

Origin繪制熱重TG和微分熱重DTG曲線

一、導入數據 二、傳到Origin中 三、熱重TG曲線 temp為橫坐標、mass為縱坐標 繪制折線圖 再稍微更改下格式 字體加粗,Times New Roman 曲線寬度設置為2 橫縱坐標數值格式為Times New Roman 根據實際情況改下橫縱坐標起始結束位置 四、微分熱重DTG曲線 點擊曲線…

【嵌入式系統復習】嵌入式網絡與協議棧

目錄開放式系統互連模型總線通信的報文組形式以及傳遞方式報文組形式報文傳遞方式網絡分配與調度嵌入式TCP/IP藍牙技術藍牙的節能狀態糾錯方案藍牙協議棧開放式系統互連模型 ISO/OSI七層模型展示了網絡結構與各層的功能。 應用層: 提供了終端用戶程序和網絡之間的應…

代碼兼容、技巧

代碼兼容、技巧 前端開發中,一個頭疼的事,就是代碼的不兼容,這里貼出自己在前端開發中的一些解決經驗。除了其瀏覽器本身的BUG外,不建議使用CSS hack來解決兼容性問題的。 IE和FF下對”li“的的高度解析不同 可以不定義高度&#…

Windows Phone 7 自定義事件

在Windows Phone的應用開發里面,對于事件這種東西我們可以隨處可見,系統本來就已經封裝好了各種各樣的事件機制,如按鈕的單擊事件等等的。在實際的開發中,我們需要自己去給相關的類自定義一些事件來滿足業務的要求,特別…

getcwd函數_PHP getcwd()函數與示例

getcwd函數PHP getcwd()函數 (PHP getcwd() function) The full form of getcwd is "Get Current Working Directory", the function getcwd() is used to get the name of the current working directory, it does not accept any parameter and returns the curren…

十四、數據庫的導出和導入的兩種方法

一、以SQL腳本格式導出(推薦) 導出 右擊需要導出的數據庫,任務—>生成腳本 下一步 選擇要導出的數據庫,下一步 內容根據需求修改,沒啥需求直接下一步 勾選 表 勾選需要導出的數據庫中的表 選擇腳本保存的路…

Apache中 RewriteCond 規則參數介紹

RewriteCond就像我們程序中的if語句一樣,表示如果符合某個或某幾個條件則執行RewriteCond下面緊鄰的RewriteRule語句,這就是RewriteCond最原始、基礎的功能,為了方便理解,下面來看看幾個例子。RewriteEngine onRewriteCond %{HTT…

【C++grammar】文件I/O流的基本用法

目錄1、輸入輸出類介紹1.C/C文件操作對比2.什么是流?3.C I/O流類層次4.帶緩沖的輸入輸出5.gcc編譯器cin.in_avail()2、向文件寫入數據1.寫文件小練習2.如何將信息同時輸出到文件和屏幕?3、從文件讀數據1.檢測文件是否成功打開2.檢測是否已到文件末尾3.讀…

作業2 分支循環結構

書本第39頁 習題2 1.輸入2個整數num1和num2.計算并輸出它們的和&#xff0c;差&#xff0c;積&#xff0c;商&#xff0c;余數。 //輸入2個整數num1和num2.計算并輸出它們的和&#xff0c;差&#xff0c;積&#xff0c;商&#xff0c;余數。//#include<stdio.h> int main…

求一個序列中最大的子序列_最大的斐波那契子序列

求一個序列中最大的子序列Problem statement: 問題陳述&#xff1a; Given an array with positive number the task to find the largest subsequence from array that contain elements which are Fibonacci numbers. 給定一個具有正數的數組&#xff0c;任務是從包含菲波納…

十三、系統優化

系統整體框架圖 程序運行進入紡織面料庫存管理系統主頁面 用戶子系統功能演示&#xff1a; 1&#xff0c;點擊用戶登錄進入用戶登錄頁面&#xff0c;可以注冊和找回密碼 2&#xff0c;注冊新用戶&#xff0c;賬號、密碼、性別、手機號均有限制&#xff0c;用戶注冊需要按指定…

時間工具類[DateUtil]

View Code 1 package com.ly.util;2 3 import java.text.DateFormat;4 import java.text.ParseException;5 import java.text.SimpleDateFormat;6 import java.util.Calendar;7 import java.util.Date;8 9 /**10 * 11 * 功能描述12 * 13 * authorAdministrator14 * Date Jul 19…

JQuery delegate多次綁定的解決辦法

我用delegate來控制分頁&#xff0c;查詢的時候會造成多次綁定 //前一頁、后一頁觸發 1 $("body").delegate("#tableFoot a:not(a.btn)", "click", function () { 2 _options.page $(this).attr("page"); 3 loadTmpl(_option…

leetcode 45. 跳躍游戲 II 思考分析

題目 給定一個非負整數數組&#xff0c;你最初位于數組的第一個位置。 數組中的每個元素代表你在該位置可以跳躍的最大長度。 你的目標是使用最少的跳躍次數到達數組的最后一個位置。 示例: 輸入: [2,3,1,1,4] 輸出: 2 解釋: 跳到最后一個位置的最小跳躍數是 2。 從下標為 …

C程序實現冒泡排序

Bubble Sort is a simple, stable, and in-place sorting algorithm. 氣泡排序是一種簡單&#xff0c;穩定且就地的排序算法。 A stable sorting algorithm is the one where two keys having equal values appear in the same order in the sorted output array as it is pre…

一、爬蟲基本概念

一、爬蟲根據使用場景分類 爬蟲&#xff1a; 通過編寫程序&#xff0c;模擬瀏覽器上網&#xff0c;讓其去互聯網上抓取數據的過程。 ① 通用爬蟲&#xff1a;抓取系統重要的組成部分&#xff0c;抓取的是一整張頁面的數據 ② 聚焦爬蟲&#xff1a;建立在通用爬蟲的基礎之上&am…

經營你的iOS應用日志(二):異常日志

如果你去4S店修車&#xff0c;給小工說你的車哪天怎么樣怎么樣了&#xff0c;小工有可能會立即搬出一臺電腦&#xff0c;插上行車電腦把日志打出來&#xff0c;然后告訴你你的車發生過什么故障。汽車尚且如此&#xff0c;何況移動互聯網應用呢。 本文第一篇&#xff1a;經營你的…

Discuz 升級X3問題匯總整理

最近一段時間公司的社區垃圾帖數量陡然上漲&#xff0c;以至于社區首頁的推薦版塊滿滿都是垃圾帖的身影&#xff0c;為了進一步解決垃圾帖問題我們整整花了1天時間刪垃圾貼&#xff0c;清除不良用戶&#xff0c;刪的手都酸了&#xff0c;可見垃圾帖的數量之多&#xff01;可恥的…