[英]I want to get the specific prediction of my Deep-Learning- CNN-model to a probability
我训练了一个 model 来将图片分类为 7 种不同类型。 我的 Model 只能做一个特定的预测(在我的例子中是 numpy.ndarray),但我有兴趣做一个更像是概率的预测(例如 90% class1 和 80% class2 ...等)。 我现在应该更改的代码部分在哪里? 我如何使用火车 model 为每个 class 获得正确的概率值
import tensorflow as tf
from tensorflow.keras.layers import Input, Lambda, Dense,Flatten
from tensorflow.keras.models import Model
from tensorflow.keras.applications.inception_v3 import InceptionV3
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.applications.inception_v3 import preprocess_input
from tensorflow.keras.preprocessing import image
from tensorflow.keras.preprocessing.image import ImageDataGenerator,load_img
from tensorflow.keras.models import Sequential
import numpy as np
from glob import glob
from google.colab import drive
from google.colab import drive
drive.mount('/content/drive')
IMAGE_SIZE = [244,244]
train_path = '/content/drive/MyDrive/Programs/Datasets/Train'
test_path = '/content/drive/MyDrive/Programs/Datasets/Test'
folders = glob('/content/drive/MyDrive/Programs/Datasets/Train/*')
7类
['/content/drive/MyDrive/Programs/Datasets/Train/Circle', '/content/drive/MyDrive/Programs/Datasets/Train/Grapes', '/content/drive/MyDrive/Programs/Datasets/Train/Sun ', '/content/drive/MyDrive/Programs/Datasets/Train/Tree', '/content/drive/MyDrive/Programs/Datasets/Train/Square', '/content/drive/MyDrive/Programs/Datasets/Train/ Triangle', '/content/drive/MyDrive/Programs/Datasets/Train/Leaf', '/content/drive/MyDrive/Programs/Datasets/Train/Pencil']
model = tf.keras.models.Sequential([
tf.keras.layers.Conv2D(30, (4, 4), activation='relu', input_shape=(224, 224, 3)),
tf.keras.layers.MaxPooling2D(pool_size=(2, 2)),
tf.keras.layers.Conv2D(60, (2, 2), activation='relu'),
tf.keras.layers.MaxPooling2D(pool_size=(2, 2)),
tf.keras.layers.Dropout(0.25),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dense(20, activation='relu'),
tf.keras.layers.Dense(len(folders), activation='softmax')])
model.summary()
train_datagen = ImageDataGenerator(rescale = 1./255,
shear_range = 0.2,
zoom_range = 0.2,
horizontal_flip = True)
test_datagen = ImageDataGenerator(rescale = 1./255)
training_set = train_datagen.flow_from_directory(train_path,
target_size = (224,224),
batch_size = 16,
class_mode = 'categorical')
test_set = test_datagen.flow_from_directory(test_path,
target_size = (224, 224),
batch_size = 16,
class_mode = 'categorical')
model.compile(
loss='categorical_crossentropy',
optimizer='adam',
metrics=['accuracy']
)
#Traning
r = model.fit_generator(
training_set,
validation_data=test_set,
epochs=5,
steps_per_epoch=len(training_set),
validation_steps=len(test_set)
)
from tensorflow.keras.models import load_model
model.save('my_model.h5')
```
Model prediction Part
```
y_pred = model.predict(test_set)
import numpy as np
y_pred = np.argmax(y_pred, axis=1)
from tensorflow.keras.models import load_model
from tensorflow.keras.preprocessing import image
model=load_model('my_model.h5')
img=image.load_img('/content/drive/MyDrive/Programs/Datasets/circle604.jpg',target_size=
(224,224))
x=image.img_to_array(img)
x=x/255
import numpy as np
x=np.expand_dims(x,axis=0)
img_data=preprocess_input(x)
img_data.shape
model.predict(img_data)
```
out put of model.predict(img_data)
array([[6.1735226e-09, 5.3491673e-11, 1.6549424e-09, 9.9484622e-01,
5.1531033e-03, 7.3390618e-07, 2.1824545e-16, 4.2561878e-11]],
dtype=float32)
```
# Predict with test data
predictions = model.predict(img_data)
# getting the highet probable digit
predicted_value = np.argmax(model.predict(img_data))
print("The set of predicted values")
print(model.predict(img_data))
print("\nPredicted Class : ", predicted_value)
print("Probability of the Class being ", predicted_value, " is : ",
max(model.predict(img_data)), "\n")
print(type(model.predict(img_data)))
```
#I want get class name and Probability vale for prediction
#But output results is
The set of predicted values
[[6.1735226e-09 5.3491673e-11 1.6549424e-09 9.9484622e-01 5.1531033e-03
7.3390618e-07 2.1824545e-16 4.2561878e-11]]
Predicted Class : 3
Probability of the Class being 3 is : [6.1735226e-09 5.3491673e-11 1.6549424e-09
9.9484622e-01 5.1531033e-03
7.3390618e-07 2.1824545e-16 4.2561878e-11]
<class 'numpy.ndarray'>
predictions
保存每个 class 的“概率” argmax
位选择具有最大“概率”的 class
首先有8个类别。 其次,预测的 output 具有形状 (1,8),从技术上讲,它是单个列表(一行列数据)的列表,因此通过传入model.predict(img_data)
您将取回该行。 您需要做的是max(model.predict(img_data)[0])
以获得最高值。
要获得 class 名称,这与标签上使用的编码方法有关。
另外,如果你想,正如你所说,你的每个 class 的概率都是这种形式,90% class1 和 80% class2...等,你应该使用sigmoid
而不是softmax
作为 output 层中的激活 function。 softmax
强制每个样本的所有类概率之和为 1(当类是排他性时使用 - 例如:60% 的概率下雨,40% 的概率不下雨),这不是你想要的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.