簡體   English   中英

如何使用夾帶自編碼器模型計算新圖像的分數以在 tensorflow 中進行異常檢測?

[英]How can I calculate score of a new image using entrained autoencoder model for anomaly detection in tensorflow?

我是 tensorflow 的初學者,我正在嘗試為圖像創建一個簡單的自動編碼器來檢測異常。首先,我使用狗圖像創建了一個簡單的自動編碼器,現在我想使用這個模型來重建我的測試圖像並使用一些指標比較結果.那么我怎么能在 tensorflow 上做到這一點(因為我是 tensorflow 的初學者)(我發現在數值數據集和 MNIST 數據集上實現了相同的想法)。 這是我的代碼:

from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input, Dense, Conv2D, MaxPooling2D, UpSampling2D
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.callbacks import LearningRateScheduler

BATCH_SIZE = 256
EPOCHS = 2
train_datagen = ImageDataGenerator(rescale=1./255)
train_batches = train_datagen.flow_from_directory('C:/MyPath/PetImages1',
    target_size=(64,64), shuffle=True, class_mode='input', batch_size=BATCH_SIZE)




input_img = Input(shape=(64, 64, 3)) 

x = Conv2D(48, (3, 3), activation='relu', padding='same')(input_img)
x = MaxPooling2D((2, 2), padding='same')(x)
x = Conv2D(96, (3, 3), activation='relu', padding='same')(x)
x = MaxPooling2D((2, 2), padding='same')(x)
x = Conv2D(192, (3, 3), activation='relu', padding='same')(x)
x = MaxPooling2D((2, 2), padding='same')(x)
 encoded = Conv2D(32, (1, 1), activation='relu', padding='same')(x)


 latentSize = (8,8,32)


 # DECODER
 direct_input = Input(shape=latentSize)
 x = Conv2D(192, (1, 1), activation='relu', padding='same')(direct_input)
 x = UpSampling2D((2, 2))(x)
 x = Conv2D(192, (3, 3), activation='relu', padding='same')(x)
 x = UpSampling2D((2, 2))(x)
 x = Conv2D(96, (3, 3), activation='relu', padding='same')(x)
 x = UpSampling2D((2, 2))(x)
 x = Conv2D(48, (3, 3), activation='relu', padding='same')(x)
 decoded = Conv2D(3, (3, 3), activation='sigmoid', padding='same')(x)
# COMPILE

encoder = Model(input_img, encoded)
decoder = Model(direct_input, decoded)
autoencoder = Model(input_img, decoder(encoded))

autoencoder.compile(optimizer='Adam', loss='binary_crossentropy')
autoencoder.save_weights('autoencoder_DogsAuto.h5')
history=autoencoder.fit_generator(train_batches,steps_per_epoch=10,epochs = 
 EPOCHS)

#Images for tests
 testGene = train_datagen.flow_from_directory('C:/PetImages/',
    target_size=(64,64), shuffle=True, class_mode='input', 
  batch_size=BATCH_SIZE)

  restored = autoencoder.predict_generator(testGene, 
 steps=testGene.n/BATCH_SIZE)

 image_height=64
 image_width=64
 image_channels=3



 x_train = np.zeros((0, image_height, image_width, image_channels), dtype=float)
for x, _ in train_batches :
    if train_batches.total_batches_seen > train_batches.n/BATCH_SIZE:
        break
   else:
       x_train = np.r_[x_train,x]
pred=autoencoder.predict(train_batches, steps=train_batches.n/BATCH_SIZE)
from sklearn import metrics


score1=np.sqrt(metrics.mean_squared_error(pred,x_train ))
print(score1)

我收到了這個錯誤:

回溯(最近一次調用):文件“c:\\autoencoder_anomaly.py”,第 196 行,在 score1=np.sqrt(metrics.mean_squared_error(pred,x_train)) 文件“C:\\Users\\AppData\\Local\\Programs\\ Python\\Python36\\lib\\site-packages\\sklearn\\metrics_regression.py", line 252, in mean_squared_error y_true, y_pred, multioutput) 文件 "C:\\Users\\AppData\\Local\\Programs\\Python\\Python36\\lib\\site-packages \\sklearn\\metrics_regression.py",第 84 行,在 _check_reg_targets check_consistent_length(y_true, y_pred)

ValueError:發現樣本數量不一致的輸入變量:[6, 0]請注意,我只使用了 6 個圖像。 那么如何使用 tensorflow 上的度量和自動編碼器模型來計算重建圖像的誤差?

這僅僅是因為形狀不匹配。

當您計算均方誤差時,它會計算真實值和估計值的元素誤差。 所以pred.shapetrain_batches.shape應該相等。檢查輸入數據形狀並確保它們相等。

第 1 步:從生成器中獲取所有訓練圖像並添加到一個數組中

x_test = np.zeros((0, image_height, image_width, image_color), dtype=float)
for x, _ in testGene:
    if testGene.total_batches_seen > testGene.n/BATCH_SIZE:
        break
    else:
        x_test = np.r_[x_test , x]

第 2 步:預測

pred=autoencoder.predict(testGene, steps=testGene.n/BATCH_SIZE)

第 3 步:計算差異

score1=np.sqrt(metrics.mean_squared_error(pred,testGene))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM