如何将原始代码转换为函数示例 [英] How to convert raw code into function(s) example

查看:113
本文介绍了如何将原始代码转换为函数示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始学习如何使用Python进行编码,如果有人可以向我简要说明如何将原始代码转换为函数,我将不胜感激。

I have just started learning how to code in Python and would appreciate if anyone could give me a brief explanation/hint on how to convert raw code into function(s).

示例机器学习代码:

# create model
model = Sequential()
model.add(Dense(neurons, input_dim=8, kernel_initializer='uniform', activation='linear', kernel_constraint=maxnorm(4)))
model.add(Dropout(0.2))
model.add(Dense(1, kernel_initializer='uniform', activation='sigmoid'))
# Compile model
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) 
# split into input (X) and output (Y) variables
X = dataset[:,0:8]
Y = dataset[:,8]
# create model
model = KerasClassifier(build_fn=model, epochs=100, batch_size=10, verbose=0)
# define the grid search parameters
neurons = [1, 5]
param_grid = dict(neurons=neurons)
grid = GridSearchCV(estimator=model, param_grid=param_grid, n_jobs=-1, cv=3)
grid_result = grid.fit(X, Y)
# summarize results
print("Best: %f using %s" % (grid_result.best_score_, grid_result.best_params_))
means = grid_result.cv_results_['mean_test_score']
stds = grid_result.cv_results_['std_test_score']
params = grid_result.cv_results_['params']
for mean, stdev, param in zip(means, stds, params):
    print("%f (%f) with: %r" % (mean, stdev, param))

如果要在1个或2个函数中使用该示例,应该如何开始?

How should I start with this example if I want to make it in 1 or 2 functions?

编辑:

在上面的代码中,我为<创建了一个函数。 #创建模型> :

In the code above, I have created a function for < # create model > :

def create_model(neurons=1):
    # create model
    model = Sequential()
    model.add(Dense(neurons, input_dim=8, kernel_initializer='uniform', activation='linear', kernel_constraint=maxnorm(4)))
    model.add(Dropout(0.2))
    model.add(Dense(1, kernel_initializer='uniform', activation='sigmoid'))
    # Compile model
    model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
return model

然后,我将必须通过 create_model()进入< KerasClassifier(build_fn = create_model 等...)>

Then, I will have to pass create_model() into < KerasClassifier(build_fn=create_model etc...) >

如果我创建下面的另一个函数,是否正确:

Is it right if I create another function like this below:

def keras_classifier(model):
    # split into input (X) and output (Y) variables
    X = dataset[:,0:8]
    Y = dataset[:,8]
    model = KerasClassifier(build_fn=model, epochs=100, batch_size=10, verbose=0)
    # define the grid search parameters
    neurons = [1, 5]
    param_grid = dict(neurons=neurons)
    grid = GridSearchCV(estimator=model, param_grid=param_grid, n_jobs=-1, cv=3)
    grid_result = grid.fit(X, Y)
    # summarize results
    print("Best: %f using %s" % (grid_result.best_score_, grid_result.best_params_))
    means = grid_result.cv_results_['mean_test_score']
    stds = grid_result.cv_results_['std_test_score']
    params = grid_result.cv_results_['params']
    for mean, stdev, param in zip(means, stds, params):
         print("%f (%f) with: %r" % (mean, stdev, param))

是否正确/可以在另一个函数中调用?

Is it correct/can be a function called in another function?

因为我调用了两个函数:

Because if I call the two functions:

create_model(neurons)
keras_classifier(model)

我收到错误 NameError:未定义名称'model'

有人可以帮忙吗?

推荐答案

我的函数def有问题,我相信:

There is an issue with your function def I believe:

def create_model(neurons):
    ....
return model

需要

def create_model(neurons):
    ....
    return model

缩进在python中非常重要,它们构成了语法的一部分。别写难看的代码,谢谢:)

indentations are very important in python, they form part of the syntax. don't write ugly code thanks :)

是的,您可以将模型传递到一个函数中,然后将其传递给keras分类器的build_fn =命名变量。放入分类器调用中的东西本身必须是模型对象,所以可以这样做:

And yes you can pass in the model into a function that then passes it to the build_fn= named variable of the keras classifier. the thing that you put in to the classifier call must itself be a model object, so do this:

model = KerasClassifier(build_fn=create_model(), epochs=100, batch_size=10, verbose=0)

对函数创建或传递给模型的模型使用不同的名称函数可以帮助跟踪它们。

using different names for models created by your functions or passing to functions can help keep track of them.

这篇关于如何将原始代码转换为函数示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆