我有一個問題。我想在tensorflow中創建一個深度學習影像分類模型,用于忽略檢測。 比如說我有一張圖片,它的右邊是空的,左邊是空的,或者沒有空的。 我將給模型輸入一張圖片,模型將把圖片分類為左側有表情或左側空或無表情。
左邊空表示左邊沒有物體。 右側空表示右側沒有物體 無側空是指兩邊都有物體。
那個物體可以是任何東西,不管它是圓還是三角形或其他什么,只需要它是物體。 我怎樣才能在tensorflow中做到這一點? 我的意思是,如何計算影像左右兩邊的物體
謝謝
我的意思是,如何計算影像左右兩邊的物體?
謝謝你
uj5u.com熱心網友回復:
如果它是一個分類模型,你不需要擔心如何檢測或計算影像中的物體。這就是深度學習所做的事情(在你的案例中可能是神經網路)。閱讀這個來了解使用tensorflow的影像分類。
uj5u.com熱心網友回復:
你所要做的是影像分類。在這種情況下,你有3個類,讓我們稱它們為rempty、lempty和noempty。 現在創建一個如下所示形式的目錄結構
image_dir
--空的
----image 0 # 第一張右側為空的圖片 # 第一張右側為空的圖片
----image 1 # 第二個影像,右邊是空的。
----
---影像N # 第N個右側為空的影像[/span
---空的
----image 0 # 第一個左側為空的影像 ---空
----image 1 # 第二個影像,左邊是空的。
----
---影像K # 左側為空的第K幅影像 # 左側為空的第K幅影像
---不空
----image 0 # 第一個沒有邊是空的影像。
----image 1 # 第二幅影像,其中沒有一面是空的。
----
---影像J # 第J張影像,左邊是空的。
所以現在我們將創建一個訓練集、一個測驗集和一個驗證集。我們將使用資料框架來創建它們
def preprocess (sdir, trsplit, vsplit, random_seed)。
filepaths=[]
標簽=[]
classlist=os.listdir(sdir)
for klass in classlist:
classpath=os.path.join(sdir,klass)
flist=os.listdir(classpath)
for f in flist:
fpath=os.path.join(classpath,f)
filepaths.append(fpath)
labels.append(klass)
Fseries=pd.Series(filepaths, name='filepaths')
Lseries=pd.Series(labsels, name='labsels')
df=pd.concat([Fseries, Lseries], axis=1)
# split df into train_df and test_df
dsplit=vsplit/(1-trsplit)
strat=df['標簽']
train_df, dummy_df=train_test_split(df, train_size=trsplit, shuffle=True, random_state=random_seed, stratify=strat)
strat=dummy_df['label']
valid_df, test_df=train_test_split(dummy_df, train_size=dsplit, shuffle=True, random_state=random_seed, stratify=strat)
print('train_df length: ', len(train_df), ' test_df length: ',len(test_df), ' valid_df length: ', len(valid_df)
print(list(train_df['labsels'].value_counts())
return train_df, test_df, valid_df
上述函式創建了訓練、測驗和有效的資料框架。現在呼叫該函式并使用它們來創建訓練生成器、測驗生成器和驗證生成器
。sdir=img_dir
train_df, test_df, valid_df= preprocess(sdir, .8,.1, 123)
img_size=(224,224) # 設定為所需的影像大小。
channels=3 # 設定為3的RGB影像。
length=len(test_df)
test_batch_size=sorted([int(length/n) for n in range(1, length 1) if length % n ==0 and length/n< =80],reverse=True) [0]
test_steps=int(length/test_batch_size)
batch_size=30 # 將此設定為所需的批次大小。
def scalar(img)。
return img # EfficientNet期望的像素范圍是0到255,所以不需要縮放。
gen=ImageDataGenerator(preprocessing_function=scalar)
train_gen=gen.flow_from_dataframe( train_df, x_col='filepaths', y_col='label', target_size=img_size, class_mode='categorical',
color_mode='rgb', shuffle=True, batch_size=batch_size)
test_gen=gen.flow_from_dataframe( test_df, x_col='filepaths', y_col='label', target_size=img_size, class_mode='categorical',
color_mode='rgb', shuffle=False, batch_size=test_batch_size)
valid_gen=gen.flow_from_dataframe( valid_df, x_col='filepaths', y_col='label', target_size=img_size, class_mode='categorical',
color_mode='rgb', shuffle=True, batch_size=batch_size)
classes=list(train_gen.class_indices.keys() )
class_count=len(classes)
現在,train_gen和valid_gen可以在model.fit中使用。test_gen可以在model.evaluation或model.predict中使用。一個好的模型可以使用,如下圖所示
base_model=tf.keras.applications.EfficientNetB2(include_top)。 EfficientNetB2(include_top=False, weights="imagenet", input_shape=img_shape, pooling='max')
x=base_model.output
x=keras.layer.BatchNormalization(axis=-1, momentum=0.99, epsilon=0.001 )(x)
x = Dense(256, kernel_regularizer = regularizers.l2(l = 0.016), activity_regularizer=regularizers.l1(0.006) 。
bias_regularizer=regularizers.l1(0.006) ,activation='relu') (x)
x=Dropout(rate=.45, seed=123)(x)
output=Dense(class_count, activation='softmax')(x)
model=模型(inputs=base_model.input, outputs=output)
model.compile(Adamax(lr=.001), loss='categorical_crossentropy', metrics=['accuracy'] )
現在訓練模型并評估測驗集上的性能
epochs=10 # setting this to desired epochs
history=model.fit(x=train_gen, epochs=epochs, verbose=1, validation_data=valid_gen,
validation_steps=None, shuffle=False, initial_epoch=0)
acc=model.evaluation( test_gen, verbose=1, steps=test_steps, return_dict=False) [1] *100
msg=f'accuracy on the test set is {acc:5.2f} %'/span>
print(msg)
你需要匯入這些模塊
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import backend as K
from tensorflow.keras.layer import Dense, Activation, Dropout, BatchNormalization
from tensorflow.keras.optimizers import Adam, Adamax
from tensorflow.keras.metrics import categorical_crossentropy
from tensorflow.keras import regularizers
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.models import Model
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
import os
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/312766.html
標籤:
下一篇:[LeetCode]相交鏈表
