ผลลัพธ์ที่แตกต่างโดยใช้การเรียนรู้เชิงลึกใน Keras

ฉันกำลังจัดหมวดหมู่ข้อความโดยใช้โครงข่ายประสาทเทียมเชิงลึกใน keras ตาม บทช่วยสอน แต่เมื่อฉันรันโค้ดต่อไปนี้หลายครั้ง ฉันได้ผลลัพธ์ที่ต่างกันออกไป

ตัวอย่างเช่น การสูญเสียจากการทดสอบในการวิ่งครั้งแรกคือ 0.88815 และอยู่ที่ 0.89030 ในการวิ่งครั้งที่สอง ซึ่งสูงกว่าเล็กน้อย ฉันสงสัยว่าความบังเอิญมาจากไหน?

import keras
from keras.datasets import reuters


(x_train, y_train), (x_test, y_test) = reuters.load_data(num_words=None, test_split=0.2)
word_index = reuters.get_word_index(path="reuters_word_index.json")



print('# of Training Samples: {}'.format(len(x_train)))
print('# of Test Samples: {}'.format(len(x_test)))

num_classes = max(y_train) + 1
print('# of Classes: {}'.format(num_classes))

index_to_word = {}
for key, value in word_index.items():
    index_to_word[value] = key

print(' '.join([index_to_word[x] for x in x_train[0]]))
print(y_train[0])


from keras.preprocessing.text import Tokenizer

max_words = 10000

tokenizer = Tokenizer(num_words=max_words)
x_train = tokenizer.sequences_to_matrix(x_train, mode='binary')
x_test = tokenizer.sequences_to_matrix(x_test, mode='binary')

y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)


print(x_train[0])
print(len(x_train[0]))

print(y_train[0])
print(len(y_train[0]))


from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation

model = Sequential()
model.add(Dense(512, input_shape=(max_words,)))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(num_classes))
model.add(Activation('softmax'))



model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
print(model.metrics_names)

batch_size = 32
epochs = 3

history = model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, verbose=1, validation_split=0.1)
score = model.evaluate(x_test, y_test, batch_size=batch_size, verbose=1)
print('Test loss:', score[0])
print('Test accuracy:', score[1])

person jinreal2014    schedule 30.08.2018    source แหล่งที่มา


คำตอบ (4)


หากคุณต้องการได้รับผลลัพธ์เดียวกันในแต่ละครั้ง คุณต้องเพิ่มเมล็ดแบบสุ่ม ดูเพิ่มเติมที่ https://machinelearningmastery.com/reproducible-results-neural-networks-keras/.

สามารถทำได้โดยเพียงเพิ่ม:

from numpy.random import seed
seed(42)

และในกรณีที่คุณใช้แบ็กเอนด์ Tensorflow คุณต้องเพิ่ม:

from tensorflow import set_random_seed
set_random_seed(42)

42 เป็นเพียงตัวเลขที่คุณเลือกได้ตามใจชอบ นี่เป็นเพียงค่าคงที่สำหรับเมล็ดสุ่ม เพื่อที่คุณจะได้รับการกำหนดค่าเริ่มต้นแบบสุ่มเหมือนกันเสมอสำหรับน้ำหนักของคุณ สิ่งนี้จะทำให้คุณได้รับผลลัพธ์เช่นเดียวกัน

person WurzelseppQX    schedule 30.08.2018

นี่เป็นพฤติกรรมปกติของเครา ดูการสนทนานี้ที่รายการปัญหาพื้นที่เก็บข้อมูล keras ของ github

ตัวอย่างเช่น ใน ฟังก์ชัน fit อาร์กิวเมนต์ที่ 9 อยู่ในโหมดสับเปลี่ยน โดยค่าเริ่มต้นจะตั้งค่าเป็นจริง ดังนั้นในแต่ละยุค ข้อมูลจะถูกสับเปลี่ยนก่อนที่จะรัน ซึ่งจะทำให้ค่าเปลี่ยนแปลงในแต่ละครั้ง

การสุ่มเมล็ดพืชจะช่วยได้ แต่ก็ยังไม่แน่ชัด

person Gimhani    schedule 30.08.2018

ตามที่กล่าวไว้ใน Keras FAQ เพิ่มรหัสต่อไปนี้:

import numpy as np
import tensorflow as tf
import random as rn

# The below is necessary in Python 3.2.3 onwards to
# have reproducible behavior for certain hash-based operations.
# See these references for further details:
# https://docs.python.org/3.4/using/cmdline.html#envvar-PYTHONHASHSEED
# https://github.com/keras-team/keras/issues/2280#issuecomment-306959926

import os
os.environ['PYTHONHASHSEED'] = '0'

# The below is necessary for starting Numpy generated random numbers
# in a well-defined initial state.

np.random.seed(42)

# The below is necessary for starting core Python generated random numbers
# in a well-defined state.

rn.seed(12345)

# Force TensorFlow to use single thread.
# Multiple threads are a potential source of
# non-reproducible results.
# For further details, see: https://stackoverflow.com/questions/42022950/which-seeds have-to-be-set-where-to-realize-100-reproducibility-of-training-res

session_conf = tf.ConfigProto(intra_op_parallelism_threads=1, 
inter_op_parallelism_threads=1)

from keras import backend as K

# The below tf.set_random_seed() will make random number generation
# in the TensorFlow backend have a well-defined initial state.
# For further details, see: https://www.tensorflow.org/api_docs/python/tf/set_random_seed

tf.set_random_seed(1234)

sess = tf.Session(graph=tf.get_default_graph(), config=session_conf)
K.set_session(sess)

# Rest of code follows ...
person Vikranth    schedule 30.08.2018

ฉันไม่ได้ตรวจสอบกับ GPU แต่สำหรับ CPU ดูเหมือนว่าจะใช้งานไม่ได้กับการแก้ไข seed ข้างต้นด้วย Tensorflow 1 เป็น Keras back end ดังนั้นเราจึงจำเป็นต้องเปลี่ยน Tensorflow 1 เป็น Tensorflow 2 จากนั้นเมล็ดยึดจะทำงาน ตัวอย่างเช่นสิ่งนี้ใช้ได้กับฉัน

import os
import numpy as np
import random as rn
import tensorflow as tf

os.environ['PYTHONHASHSEED']= '0'
np.random.seed(1)
rn.seed(1)
tf.set_random_seed(1)
person Nguyen Trung Ky    schedule 05.04.2021