【问题标题】:tensorflow prediction output changes each time I train每次训练时,张量流预测输出都会发生变化
【发布时间】:2021-01-02 09:20:32
【问题描述】:

我使用以下代码来训练我应该检测猫和狗的模型。当我训练它时,每次它给出不同的预测分数并且输出大多是错误的。这是我的代码

    #Imports
import os
from PIL import Image
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Flatten, Conv2D, MaxPooling2D, Dropout
from tensorflow.keras import layers
from tensorflow.keras.utils import to_categorical
import numpy as np
import matplotlib.pyplot as plt
import csv
import pathlib
from IPython.display import display
import random
plt.style.use('fivethirtyeight')


batchsize = 64
imagewidth = 32
imageheight = 32

def define_model():
    model = Sequential()
    model.add(layers.experimental.preprocessing.Rescaling(1./255, input_shape=(imageheight, imageheight, 3)))
    model.add(Conv2D(32, (3, 3), activation='relu'))
    model.add(MaxPooling2D((2, 2)))
    model.add(Flatten())
    model.add(Dense(128, activation='relu'))
    model.add(Dense(2, activation='softmax'))
    # compile model
    model.compile(optimizer='adam', loss = 'binary_crossentropy', metrics=['accuracy'])
    return model


dataseturl = 'E:\AI\\'

data_dir = pathlib.Path("")
print(data_dir)
print("0101")



train_ds = tf.keras.preprocessing.image_dataset_from_directory(
  data_dir,
  validation_split=0.2,
  subset="training",
  seed=123,
  image_size=(imageheight, imagewidth),
  batch_size=batchsize)
#random.shuffle(train_ds)

val_ds = tf.keras.preprocessing.image_dataset_from_directory(
  data_dir,
  validation_split=0.2,
  subset="validation",
  seed=123,
  image_size=(imageheight, imagewidth),
  batch_size=batchsize)
class_names = train_ds.class_names
model = define_model()
#model.load_weights("trained.ckpt")
#model.compile(loss = 'binary_crossentropy', optimizer= 'adam', metrics = ['accuracy'])
epochs=10
history = model.fit(
  train_ds,
  validation_data=val_ds,
  epochs=epochs,
  batch_size = 32
)
img = keras.preprocessing.image.load_img(
    "Test3.jpg", target_size=(imageheight, imagewidth)
)
img_array = keras.preprocessing.image.img_to_array(img)
img_array = img_array / 255.0
print(img_array.shape)
img_array = tf.expand_dims(img_array, 0) # Create a batch

predictions = model.predict(img_array)
score = predictions[0]
print(class_names)
print(score)
print(
    "This image most likely belongs to {} with a {:.2f} percent confidence."
    .format(class_names[np.argmax(predictions[0])], 100 * np.max(predictions[0]))
)
model.save_weights("trained.ckpt")

此代码要么坚持一个输出,例如所有图片的猫预测,要么预测图片错误,例如猫预测为狗,反之亦然

【问题讨论】:

  • 训练集中有多少样例?如果训练集太小,这很可能是旧模型过拟合。您的模型可能“记住”了训练集中的每张图片,并且不知道狗或猫实际上长什么样。

标签: python tensorflow deep-learning neural-network


【解决方案1】:

我还不能发布 cmets,所以写一个答案。

我看到您的模型只有一个带有 32 个过滤器的卷积层。您的模型仅使用一层就不会学习到好的特征。可以尝试增加卷积层数。

您的训练集有多少张图片? 您是否检查过您的 class_names 变量值是否与您的图像相对应?我的意思是尝试使用标签绘制数据集的几张图像,以确保您正确地为图像设置标签。

监控您的训练和验证准确度得分。如果您的验证分数较低并且您的训练准确度很高,那么您的模型很可能是过度拟合的。使用正则化方法来避免过拟合。 (例如,添加一个 dropout 层或使用 kernel_regularizer)。

看看这个帖子,看看能不能得到结果

https://machinelearningmastery.com/how-to-develop-a-convolutional-neural-network-to-classify-photos-of-dogs-and-cats/

【讨论】:

  • 好的,但是我怎样才能添加更多的卷积层。我在教程上看到了该代码,所以我确实喜欢他,但由于您所说的原因,它不起作用。 + 抱歉迟到了
猜你喜欢
  • 2017-11-21
  • 1970-01-01
  • 2020-02-29
  • 2021-12-24
  • 2012-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多