我正在研究 scikit-learn 中的神经网络的多分类问题,我试图弄清楚如何优化我的超参数(层的数量、感知器的数量,最终其他东西)。
我发现这GridSearchCV
是这样做的方法,但我使用的代码返回了平均准确度,而我实际上想测试 F1 分数。有没有人知道如何编辑此代码以使其适用于 F1 分数?
一开始,当我不得不评估精确度/准确度时,我认为只取混淆矩阵并从中得出结论就“足够了”,同时通过反复试验来改变我的神经网络中的层和感知器的数量网络一遍又一遍。
今天我发现还有更多:GridSearchCV
. 我只需要弄清楚如何评估 F1 分数,因为我需要研究确定神经网络在层、节点以及最终其他替代方案方面的准确性......
mlp = MLPClassifier(max_iter=600)
clf = GridSearchCV(mlp, parameter_space, n_jobs= -1, cv = 3)
clf.fit(X_train, y_train.values.ravel())
parameter_space = {
'hidden_layer_sizes': [(1), (2), (3)],
}
print('Best parameters found:\n', clf.best_params_)
means = clf.cv_results_['mean_test_score']
stds = clf.cv_results_['std_test_score']
for mean, std, params in zip(means, stds, clf.cv_results_['params']):
print("%0.3f (+/-%0.03f) for %r" % (mean, std * 2, params))
Run Code Online (Sandbox Code Playgroud)
输出:
Best parameters found:
{'hidden_layer_sizes': 3}
0.842 (+/-0.089) for {'hidden_layer_sizes': 1}
0.882 (+/-0.031) …
Run Code Online (Sandbox Code Playgroud) python machine-learning neural-network multilabel-classification hyperparameters
我尝试将贝叶斯优化应用于 MNIST 手写数字数据集的简单 CNN,但几乎没有迹象表明它有效。我已经尝试进行 k 折验证以消除噪声,但似乎优化仍然没有在收敛到最佳参数方面取得任何进展。一般来说,贝叶斯优化可能失败的一些主要原因是什么?在我的特殊情况下?
其余的只是上下文和代码片段。
型号定义:
def define_model(learning_rate, momentum):
model = Sequential()
model.add(Conv2D(32, (3,3), activation = 'relu', kernel_initializer = 'he_uniform', input_shape=(28,28,1)))
model.add(MaxPooling2D((2,2)))
model.add(Flatten())
model.add(Dense(100, activation='relu', kernel_initializer='he_uniform'))
model.add(Dense(10, activation='softmax'))
opt = SGD(lr=learning_rate, momentum=momentum)
model.compile(optimizer=opt, loss='categorical_crossentropy', metrics=['accuracy'])
return model
Run Code Online (Sandbox Code Playgroud)
使用超参数运行一次训练:batch_size = 32,学习率 = 1e-2,Momentum = 0.9,10 个 epoch。(蓝色 = 训练,黄色 = 验证)。
盒须图用于 5 折交叉验证的准确性,具有与上述相同的超参数(以了解传播)
网格搜索将 batch_size 保持在 32,并保持 10 个纪元。我是在单次评估而不是 5 倍上这样做的,因为差价不足以破坏结果。
贝叶斯优化。如上,batch_size=32 和 10 epoch。在相同的范围内搜索。但这一次使用 5 折交叉验证来消除噪音。它应该进行 100 次迭代,但这还需要 20 个小时。
space = …
Run Code Online (Sandbox Code Playgroud) 我目前正在做一个项目,很遗憾无法与您分享。该项目是关于神经网络的超参数优化,它要求我并行训练多个神经网络模型(比我在 GPU 上存储的多)。网络架构保持不变,但网络参数和超参数在每个训练间隔之间会发生变化。我目前正在 Linux 环境中使用 PyTorch 来实现这一点,以允许我的 NVIDIA GTX 1660(6GB RAM)使用 PyTorch 提供的多处理功能。
代码(简化):
def training_function(checkpoint):
load(checkpoint)
train(checkpoint)
unload(checkpoint)
for step in range(training_steps):
trained_checkpoints = list()
for trained_checkpoint in pool.imap_unordered(training_function, checkpoints):
trained_checkpoints.append(trained_checkpoint)
for optimized_checkpoint in optimize(trained_checkpoints):
checkpoints.update(optimized_checkpoint)
Run Code Online (Sandbox Code Playgroud)
我目前使用 MNIST 和 FashionMNIST 数据集对 30 个神经网络(即 30 个检查点)进行测试,该数据集由 70 000 个(50k 训练、10k 验证、10k 测试)28x28 图像组成,每个图像分别具有 1 个通道。我训练的网络是一个简单的 Lenet5 实现。
我使用了一个 torch.multiprocessing 池并允许产生 7 个进程。每个进程使用一些可用的 GPU 内存来初始化每个进程中的 CUDA 环境。训练结束后,检查点将使用我的超参数优化技术进行调整。
中的load
函数training_function
将模型和优化器状态(保存网络参数张量)从本地文件加载到使用torch.load
. 使用unload
将新训练的状态保存回文件torch.save
并从内存中删除它们。我这样做是因为 PyTorch …
我用一个步骤编写了一个简单的 AWS 步骤函数工作流程:
from stepfunctions.inputs import ExecutionInput
from stepfunctions.steps import Chain, TuningStep
from stepfunctions.workflow import Workflow
import train_utils
def main():
workflow_execution_role = 'arn:aws:iam::MY ARN'
execution_input = ExecutionInput(schema={
'app_id': str
})
estimator = train_utils.get_estimator()
tuner = train_utils.get_tuner(estimator)
tuning_step = TuningStep(state_id="HP Tuning", tuner=tuner, data={
'train': f's3://my-bucket/{execution_input["app_id"]}/data/'},
wait_for_completion=True,
job_name='HP-Tuning')
workflow_definition = Chain([
tuning_step
])
workflow = Workflow(
name='HP-Tuning',
definition=workflow_definition,
role=workflow_execution_role,
execution_input=execution_input
)
workflow.create()
if __name__ == '__main__':
main()
Run Code Online (Sandbox Code Playgroud)
我的目标是从运行时提供的执行 JSON 中提取训练输入。当我执行工作流(从步骤函数控制台)时,提供 JSON{"app_id": "My App ID"}
调整步骤不会获得正确的数据,而是获得stepfunctions.inputs.placeholders.ExecutionInput
. 此外,在查看生成的 ASL 时,我可以看到执行输入被呈现为字符串:
... …
Run Code Online (Sandbox Code Playgroud) python machine-learning state-machine hyperparameters aws-step-functions
我有 scikit-learn 0.24.1 和 scikit-optimize 0.8.1,当我尝试使用 BayesSearchCV 函数时,它给了我这个错误:
TypeError: __init__() got an unexpected keyword argument 'iid'
Run Code Online (Sandbox Code Playgroud)
当我搜索时发现新的 scikit-learn 中不推荐使用“iid”,有什么建议可以解决这个问题?
GridsearchCV()有一个参数cv,默认值为3,表示是3倍。有没有办法将 Gridsearch() 与保留验证方案一起使用。例如80-20%分割???
好吧,我试图了解如何以及在算法中的哪个点应用 Kfold CV 和 GridSearchCV。另外,如果我理解正确的话,GridSearchCV 用于超参数调整,即参数的哪些值将给出最佳结果,而 Kfold CV 用于更好的泛化,以便我们在不同的折叠上进行训练,从而在数据有序的情况下减少偏差以某种特定的方式,从而增加普遍性。现在的问题是,GridSearchCV 是否也使用 CV 参数进行交叉验证。那么为什么我们需要 Kfold CV,如果需要的话我们是否在 GridSearchCV 之前进行呢?对该过程的一些概述将非常有帮助。
machine-learning scikit-learn cross-validation hyperparameters
我正在尝试使用 tensorflow.plugins.hparams 调整神经网络的超参数。
在此链接中,它提供了有关如何使用该函数调整超参数的建议代码。
如提供的链接所示,可以使用以下内容:
HP_NUM_UNITS = hp.HParam('num_units', hp.Discrete([16, 32]))
HP_DROPOUT = hp.HParam('dropout', hp.RealInterval(0.1, 0.2))
HP_OPTIMIZER = hp.HParam('optimizer', hp.Discrete(['adam', 'sgd']))
METRIC_ACCURACY = 'accuracy'
with tf.summary.create_file_writer('logs/hparam_tuning').as_default():
hp.hparams_config(
hparams=[HP_NUM_UNITS, HP_DROPOUT, HP_OPTIMIZER],
metrics=[hp.Metric(METRIC_ACCURACY, display_name='Accuracy')],
)
def train_test_model(hparams):
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(hparams[HP_NUM_UNITS], activation=tf.nn.relu),
tf.keras.layers.Dropout(hparams[HP_DROPOUT]),
tf.keras.layers.Dense(10, activation=tf.nn.softmax),
])
model.compile(
optimizer=hparams[HP_OPTIMIZER],
loss='sparse_categorical_crossentropy',
metrics=['accuracy'],
)
model.fit(x_train, y_train, epochs=1) # Run with 1 epoch to speed things up for demo purposes
_, accuracy = model.evaluate(x_test, y_test)
return accuracy
Run Code Online (Sandbox Code Playgroud)
我将重点放在下一行,因为我将它作为我想做的事情的参考。线路:
tf.keras.layers.Dense(hparams[HP_NUM_UNITS], activation=tf.nn.relu),
Run Code Online (Sandbox Code Playgroud)
我最终想要做的是创建一堆不同类型的优化器,它们具有不同的学习率、衰减率、beta_1 和 beta_2 值等。这就是我试图做的: …
hyperparameters ×10
python ×7
scikit-learn ×4
grid-search ×2
keras ×2
tensorflow ×2
gpu ×1
hyperopt ×1
python-3.x ×1
pytorch ×1
ray ×1
skopt ×1