Skip to main content
 首页 » 编程设计

python之Keras 2.0.8 仅使用 Python 3.x 执行 1 个 epoch,使用 2.x 执行 10 个

2024年09月07日7jyk

如果我将它切换到 Python 2.x,它执行 10。这是为什么?

训练逻辑回归模型

                                 import keras.backend as K 
    from keras.models            import Sequential 
    from keras.layers            import Dense, Activation 
    from keras.optimizers        import SGD 
    from sklearn.model_selection import train_test_split, cross_val_score 
 
    X_train, X_test, y_train, y_test = train_test_split(X, y, 
                                                    test_size    = 0.3, 
                                                    random_state = 42) 
 
# NOTE: If I run this in Python 3.x, it only performs 1 Epoch 
K.clear_session() 
 
model = Sequential() 
model.add(Dense(1, input_shape=(4,), activation='sigmoid')) 
 
model.compile(loss     = 'binary_crossentropy', 
              optimizer= 'sgd', 
              metrics  = ['accuracy']) 
 
# Saved the result of the fitting, to display the history as a data frame & see how the model does 
history = model.fit     (X_train, y_train) 
result  = model.evaluate(X_test,  y_test) 

输出:

Epoch 1/10 
960/960 [==============================] - 0s - loss: 0.7943 - acc: 0.5219      
Epoch 2/10 
960/960 [==============================] - 0s - loss: 0.7338 - acc: 0.5469      
Epoch 3/10 
960/960 [==============================] - 0s - loss: 0.6847 - acc: 0.5688      
Epoch 4/10 
960/960 [==============================] - 0s - loss: 0.6446 - acc: 0.6177      
Epoch 5/10 
960/960 [==============================] - 0s - loss: 0.6113 - acc: 0.6719      
Epoch 6/10 
960/960 [==============================] - 0s - loss: 0.5832 - acc: 0.7000      
Epoch 7/10 
960/960 [==============================] - 0s - loss: 0.5591 - acc: 0.7177      
Epoch 8/10 
960/960 [==============================] - 0s - loss: 0.5381 - acc: 0.7365      
Epoch 9/10 
960/960 [==============================] - 0s - loss: 0.5196 - acc: 0.7542      
Epoch 10/10 
960/960 [==============================] - 0s - loss: 0.5031 - acc: 0.7688      
 32/412 [=>............................] - ETA: 0s 

请您参考如下方法:

fit函数具有参数 epochs,默认值为 1。

fit(self, x=None, y=None, batch_size=None, epochs=1, verbose=1, callbacks=None,  
    validation_split=0.0, validation_data=None, shuffle=True, class_weight=None,  
    sample_weight=None, initial_epoch=0, steps_per_epoch=None,  
    validation_steps=None) 

但是,默认值过去是 10。查看 this commit 中 models.py 中 fit 的更改例如。您很可能使用旧版本的 Keras 和 Python 2。