簡體   English   中英

CNN 給出隨機答案,而完全連接的神經網絡工作正常

[英]CNN giving random answers while fully-connected neural network works fine

我正在研究一個應該分析圖像並識別 5 個可能對象的 AI。 我在 python 中使用 tf.keras,它在以前的項目中運行良好,但對於這個項目,無論我訓練多長時間,它都會給出隨機結果(20% 的准確度和 5 個可能的輸出)。

5 種可能的對象是: - 四足動物 - 人類模型 - 飛機 - 卡車 - 汽車

我之前嘗試過使用完全連接的神經網絡,使用完全相同的數據集,經過 10 分鍾的訓練,它的准確率約為 50%。 我的目標是達到 90% 的准確率,這就是我嘗試使用 CNN 的原因。 我還使用了 mnist 數據集並制作了一個使用 tf.keras 識別手寫數字的 cnn。 我嘗試使用相同的 keras 模型,但失敗了。 我嘗試了不同的模型,但都沒有給出非隨機預測。

這是我的 keras 模型:

import tensorflow as tf

layers = tf.keras.layers

model = tf.keras.models.Sequential([
    layers.Conv2D(16, (3, 3), input_shape=(80, 80, 1), activation='relu'),
    layers.MaxPooling2D(pool_size=(2, 2)),
    layers.Conv2D(32, (3, 3), activation='relu'),
    layers.MaxPooling2D(pool_size=(2, 2)),
    layers.Conv2D(64, (3, 3), activation='relu'),
    layers.MaxPooling2D(pool_size=(2, 2)),
    layers.Dropout(0.2),
    layers.Flatten(),
    layers.Dense(512, activation=tf.nn.relu),
    layers.Dense(5, activation=tf.nn.softmax)
])
model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy']
)

我正在用這段代碼訓練它:

x, y = self.load_data(input("File containg train files: "), input("File containg labels files: ")) # function that takes a .mat file and return an array of shape (29160, 1, 80, 80)

x = x.reshape(total_data_number, 80, 80, 1)
x = x.astype('float32')
x /= 255.0

epoch = 15

model.fit(x, y, batch_size=50, epochs=epoch, verbose=1)

全連接模型是這樣的:

model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(input_shape=(80, 80, 1)),
tf.keras.layers.Dense(512, activation=tf.nn.relu),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(5, activation=tf.nn.softmax)
])
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])

准確率應該高於 20%,並且在我訓練模型時應該會提高。

您的一些問題可能來自這樣一個事實,即您使用的是sparse_categorical_crossentropy而您的輸出是 one_hot_encoded 向量。 所以你應該使用categorical_crossentropy代替。 (基本解釋在這里

每個班級有多少數據? 此外,您的模型對於對象分類任務來說似乎太簡單了。 您應該嘗試更深層次的模型。 Keras 在imagenet上提供了一些預訓練模型。 您可以在自己的數據集上微調這些模型。 例如,在Keras 應用程序上,它提供了一種微調預訓練的 InceptionV3 模型的方法:

from keras.applications.inception_v3 import InceptionV3
from keras.preprocessing import image
from keras.models import Model
from keras.layers import Dense, GlobalAveragePooling2D
from keras import backend as K

# create the base pre-trained model
base_model = InceptionV3(weights='imagenet', include_top=False)

# add a global spatial average pooling layer
x = base_model.output
x = GlobalAveragePooling2D()(x)
# let's add a fully-connected layer
x = Dense(1024, activation='relu')(x)
# and a logistic layer -- 4 classes in your case
predictions = Dense(4, activation='softmax')(x)

# this is the model we will train
model = Model(inputs=base_model.input, outputs=predictions)

# first: train only the top layers (which were randomly initialized)
# i.e. freeze all convolutional InceptionV3 layers
for layer in base_model.layers:
    layer.trainable = False

# compile the model (should be done *after* setting layers to non-trainable)
model.compile(optimizer='rmsprop', loss='categorical_crossentropy')

# train the model on the new data for a few epochs
model.fit_generator(...)

# at this point, the top layers are well trained and we can start fine-tuning
# convolutional layers from inception V3. We will freeze the bottom N layers
# and train the remaining top layers.

# let's visualize layer names and layer indices to see how many layers
# we should freeze:
for i, layer in enumerate(base_model.layers):
   print(i, layer.name)

# we chose to train the top 2 inception blocks, i.e. we will freeze
# the first 249 layers and unfreeze the rest:
for layer in model.layers[:249]:
   layer.trainable = False
for layer in model.layers[249:]:
   layer.trainable = True

# we need to recompile the model for these modifications to take effect
# we use SGD with a low learning rate
from keras.optimizers import SGD
model.compile(optimizer=SGD(lr=0.0001, momentum=0.9), loss='categorical_crossentropy')

# we train our model again (this time fine-tuning the top 2 inception blocks
# alongside the top Dense layers
model.fit_generator(...)

暫無
暫無

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

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