【问题标题】:Tensorflow CNN only 1 output predict valueTensorFlow CNN 只有 1 个输出预测值
【发布时间】:2021-05-20 12:33:04
【问题描述】:

我已经研究过类似的主题,但没有一个提示对我有帮助。我的模型只预测和输出 1 个类,即使在控制台中我也只看到 1 个数组值。我必须检查帐号中的字体是假的还是真的。它打印的精度为 0.99 甚至 1.00,但在使用 model.predicts 手动检查后,它只输出 0。我在每个班级的 1000 张照片上训练它。有什么解决办法吗?我的代码:

train = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1/255)
    validation = train_set = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1/255)
    validation_set = validation.flow_from_directory('Samples', class_mode='binary', batch_size=30, target_size=(500, 50), shuffle=True, seed=42, color_mode='rgb')
    train_set = train.flow_from_directory(directory='Train', class_mode='binary', batch_size=30, target_size=(500, 50), shuffle=True, seed=42, color_mode='rgb')
    print(train_set.classes)
    model = tf.keras.models.Sequential([
        tf.keras.layers.Conv2D(16, kernel_size = (3, 3), activation='relu', input_shape=(500, 50, 3)),
        tf.keras.layers.MaxPool2D(pool_size = (2, 2)),
        tf.keras.layers.Conv2D(32, kernel_size = (3, 3), activation='relu'),
        tf.keras.layers.MaxPool2D(pool_size = (2, 2)),
        tf.keras.layers.Conv2D(64, kernel_size = (3, 3), activation='relu'),
        tf.keras.layers.MaxPool2D(pool_size = (2, 2)),
        tf.keras.layers.Flatten(),
        tf.keras.layers.Dense(512, activation='relu'),
        tf.keras.layers.Dense(1, activation='sigmoid')
    ])
    print(train_set.class_indices)
    model.compile(loss='binary_crossentropy', optimizer='adam', metrics= ['accuracy'])
    model.fit(train_set, epochs=2, validation_data=validation_set)

    path = 'Samples/'
    DIRECTORIES = ['Fake', 'Real']
    for dir in DIRECTORIES:
        for file in os.listdir(path+dir):
            img = tf.keras.preprocessing.image.load_img(path+dir+'/'+file)
            img = tf.keras.preprocessing.image.img_to_array(img)
            img = np.expand_dims(img, axis=0)
            images = np.vstack([img])
            val = np.argmax(model.predict(images))
            print(val)

要比较的照片: Real Fake

Output

【问题讨论】:

  • argmax 错误,应该是-> (model.predict(images) > 0.5)

标签: python tensorflow conv-neural-network artificial-intelligence


【解决方案1】:

您在使用模型时就像在输出层中有两个输出神经元一样。 np.argmax(model.predict(images)) 将返回具有最大值的神经元的索引,但由于您只有 1,因此它将始终返回 0。只需检查 predict 返回的值是否超过阈值或交替使用两个神经元。

【讨论】:

  • 你能帮我如何使用 2 个预测神经元吗?我希望 0.4 代表 1 类 0.6 代表 2 类
猜你喜欢
  • 2020-07-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-14
  • 2020-03-13
  • 1970-01-01
相关资源
最近更新 更多