【发布时间】:2021-12-26 13:00:45
【问题描述】:
我正在尝试使笔记本“Predict Artist from Artworks”适应我自己的数据集。 Keras 模型已生成并转换为 Tensorflow 模型(使用 tensorflowjs_converter --input_format keras us.keras tfjs_model/us),我现在尝试将其与 tensorflow.js 一起使用,但使用 tensorflow.js 时预测结果不同(且错误)。
这是给出正确结果的预测 Python 代码:
from keras.preprocessing import image
from tensorflow import keras
import numpy as np
artists = ['CB', 'AT', 'TS', 'FG', 'DR']
model = keras.models.load_model('us.keras')
image_file = 'datasets/full/thumbnails3/fr/gb/fr_gb_0004p_001.jpg'
test_image = image.load_img(image_file, target_size=(224, 224))
# Predict artist
test_image = image.img_to_array(test_image)
test_image /= 255.
test_image = np.expand_dims(test_image, axis=0)
prediction = model.predict(test_image)
prediction_probability = np.amax(prediction)
prediction_idx = np.argmax(prediction)
print("Predicted artist = {}, probability of {:.2f} %"
.format(artists[prediction_idx], prediction_probability * 100))
结果是:
预测艺术家 = CB,概率为 22.62 %
但是,当使用 tensorflow.js 时,结果完全不同:
const tf = require("@tensorflow/tfjs");
const tfn = require("@tensorflow/tfjs-node");
const sharp = require('sharp');
const modelFile = tfn.io.fileSystem("tfjs_model/us/model.json");
const artists = ['CB', 'AT', 'TS', 'FG', 'DR']
tf.loadLayersModel(modelFile).then(model => {
sharp('datasets/full/thumbnails3/fr/gb/fr_gb_0004p_001.jpg')
.rotate()
.resize(224, 224)
.toBuffer().then(
data => {
let image = tfn.node.decodeImage(data, 0)
image = tf.expandDims(image, 0);
image = tf.cast(image, 'float32').div(255)
const prediction = model.predict(image);
prediction.array().then(([predictionArray]) => {
const predictionProbability = Math.max(...predictionArray);
const predictionIndex = predictionArray.indexOf(predictionProbability);
console.log(`Predicted artist = ${artists[predictionIndex]}, probability of ${predictionProbability * 100}%`)
})
}
)
})
结果:
预测艺术家 = DR,概率为 37.461987137794495%
我的假设是我在 JS 代码中对尺寸或图像处理所做的事情是错误的,但我不知道是什么。
【问题讨论】:
-
这肯定与预测前图像的处理方式有关。在 js 中,您在预测之前旋转图像。你似乎没有在 python 中做同样的事情