作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我创建了一个单层神经网络,具有两个输出(每个类别一个,0 或 1),并使用 sigmoid 方法和 SGD 优化器进行训练。我还训练了没有任何隐藏层的神经网络。此外,我还使用 StratifiedKFold 进行 4 次分割验证了模型的性能。训练的模型设计为 lr=0.1 和 epochs=150,但是,我不知道这些值是否正在优化模型。出于这个原因,我想运行 20 种学习率参数和历元的组合,以查看最准确的结果以及我获得这些参数的哪些组合。以下限制:
请参阅下面的代码:
from sklearn.model_selection import StratifiedKFold
from keras.models import Sequential
from keras.layers.core import Dense
from keras import layers
from keras.optimizers import SGD
from keras.wrappers.scikit_learn import KerasClassifier
from sklearn.model_selection import cross_val_score
#Function to create the NN model
def create_model():
#Neural Network model
ann = Sequential()
#Number of columns of training dataset
n_cols = x_train.shape[1]
#Output
ann.add(Dense(units=1,activation='sigmoid',input_shape=(n_cols,)))
#SGD Optimizer
sgd = SGD(lr=0.1)
#Compile with SGD optimizer and binary_crossentropy
ann.compile(optimizer=sgd,
loss='binary_crossentropy',
metrics=['accuracy'])
return ann
#Creating the model
model=KerasClassifier(build_fn=create_model,epochs=150,batch_size=10,verbose=0)
#Evaluating the model using StratifiedKFold
kfold = StratifiedKFold(n_splits=4, shuffle=True, random_state=2)
results=cross_val_score(model,x_train,y_train,cv=kfold)
#Accuracies
print(results)
为了创建由学习率和历元形成的 20 种组合,首先,我创建了 lr 和历元的随机值:
#Epochs
epo = np.random.randint(10,150)
#Learning Rate
learn = np.random.randint(0.01,1)
我的问题是,我不知道如何将其放入神经网络的代码中,以便找到能够提供最佳模型准确度的组合。
最佳答案
无需优化您可以轻松使用提前停止的纪元数量,当您的损失或准确性没有改善时,提前停止就会停止所以只需将您的纪元设置为一个大数字(例如 300 )并添加:
keras.callbacks.callbacks.EarlyStopping(monitor='val_loss', min_delta=0.1)
您还可以通过以下方式调用最佳权重(在模型开始过度拟合之前):
restore_best_weights=True
关于python - 在神经网络中找到最佳学习率和时期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59038030/
我是一名优秀的程序员,十分优秀!