使用keras的sk-learn API时出错

xia*_*iao 8 python machine-learning scikit-learn keras

  我这些天正在学习keras,在使用scikit-learn API时我遇到了一个错误.这里有些东西可能有用:

环境:

python:3.5.2  
keras:1.0.5  
scikit-learn:0.17.1
Run Code Online (Sandbox Code Playgroud)

import pandas as pd
from keras.layers import Input, Dense
from keras.models import Model
from keras.models import Sequential
from keras.wrappers.scikit_learn import KerasRegressor
from sklearn.cross_validation import train_test_split
from sklearn.cross_validation import cross_val_score
from sqlalchemy import create_engine
from sklearn.cross_validation import KFold


def read_db():
    "get prepared data from mysql."
    con_str = "mysql+mysqldb://root:0000@localhost/nbse?charset=utf8"
    engine = create_engine(con_str)
    data = pd.read_sql_table('data_ml', engine)
    return data

def nn_model():
    "create a model."
    model = Sequential()
    model.add(Dense(output_dim=100, input_dim=105, activation='softplus'))
    model.add(Dense(output_dim=1, input_dim=100, activation='softplus'))
    model.compile(loss='mean_squared_error', optimizer='adam')
    return model

data = read_db()
y = data.pop('PRICE').as_matrix()
x = data.as_matrix()
model = nn_model()
model = KerasRegressor(build_fn=model, nb_epoch=2)
model.fit(x,y)  #something wrong here!
Run Code Online (Sandbox Code Playgroud)

错误

Traceback (most recent call last):
  File "C:/Users/Administrator/PycharmProjects/forecast/gridsearch.py", line 43, in <module>
    model.fit(x,y)
  File "D:\Program Files\Python35\lib\site-packages\keras\wrappers\scikit_learn.py", line 135, in fit
    **self.filter_sk_params(self.build_fn.__call__))
TypeError: __call__() missing 1 required positional argument: 'x'

Process finished with exit code 1
Run Code Online (Sandbox Code Playgroud)

  该模型运行良好,没有使用kerasRegressor打包,但我想在此之后使用sk_learn的gridSearch,所以我在这里寻求帮助.我试过但仍然不知道.

可能有用的东西:

keras.warappers.scikit_learn.py  

class BaseWrapper(object):  


    def __init__(self, build_fn=None, **sk_params):
        self.build_fn = build_fn
        self.sk_params = sk_params
        self.check_params(sk_params)  


    def fit(self, X, y, **kwargs):
        '''Construct a new model with build_fn and fit the model according
        to the given training data.
    # Arguments
        X : array-like, shape `(n_samples, n_features)`
            Training samples where n_samples in the number of samples
            and n_features is the number of features.
        y : array-like, shape `(n_samples,)` or `(n_samples, n_outputs)`
            True labels for X.
        kwargs: dictionary arguments
            Legal arguments are the arguments of `Sequential.fit`

    # Returns
        history : object
            details about the training history at each epoch.
    '''

    if self.build_fn is None:
        self.model = self.__call__(**self.filter_sk_params(self.__call__))
    elif not isinstance(self.build_fn, types.FunctionType):
        self.model = self.build_fn(
            **self.filter_sk_params(self.build_fn.__call__))
    else:
        self.model = self.build_fn(**self.filter_sk_params(self.build_fn))

    loss_name = self.model.loss
    if hasattr(loss_name, '__name__'):
        loss_name = loss_name.__name__
    if loss_name == 'categorical_crossentropy' and len(y.shape) != 2:
        y = to_categorical(y)

    fit_args = copy.deepcopy(self.filter_sk_params(Sequential.fit))
    fit_args.update(kwargs)

    history = self.model.fit(X, y, **fit_args)

    return history
Run Code Online (Sandbox Code Playgroud)

  此行中出现错误:

    self.model = self.build_fn(
        **self.filter_sk_params(self.build_fn.__call__))
Run Code Online (Sandbox Code Playgroud)

self.build_fn这里是keras.models.Sequential

models.py  

class Sequential(Model):

    def call(self, x, mask=None):
        if not self.built:
            self.build()
        return self.model.call(x, mask)
Run Code Online (Sandbox Code Playgroud)

那么,x是什么意思以及如何解决这个错误?
谢谢!

mat*_*nja 12

,我遇到了同样的问题!希望这有助于:

背景和问题

Keras文档指出,在为scikit-learn实现Wrappers时,有两个参数.第一个是构建函数,它是"可调用函数或类实例".具体而言,它指出:

build_fn应该构造,编译并返回一个Keras模型,然后将其用于拟合/预测.可以将以下三个值之一传递给build_fn:

  1. 一个功能
  2. 实现调用方法的类的实例
  3. 没有.这意味着您实现了一个继承自KerasClassifier或的类KerasRegressor.然后将本类的调用方法视为默认的build_fn.

在代码中,创建模型,然后build_fn在创建KerasRegressor包装器时将模型作为参数的值传递:

model = nn_model()
model = KerasRegressor(build_fn=model, nb_epoch=2)
Run Code Online (Sandbox Code Playgroud)

这就是问题所在.您不是传递nn_model 函数,而是传递build_fnKeras Sequential模型的实际实例.因此,在fit()调用时,它无法找到该call方法,因为它未在您返回的类中实现.

提出的解决方案

我所做的工作是将函数传递给build_fn,而不是实际的模型:

data = read_db()
y = data.pop('PRICE').as_matrix()
x = data.as_matrix()
# model = nn_model() # Don't do this!
# set build_fn equal to the nn_model function
model = KerasRegressor(build_fn=nn_model, nb_epoch=2) # note that you do not call the function!
model.fit(x,y)  # fixed!
Run Code Online (Sandbox Code Playgroud)

这不是唯一的解决方案(您可以设置build_fncall适当地实现该方法的类),但是对我有用的那个.我希望它对你有所帮助!

  • @matsuninja 你知道如何将参数传递给函数吗?我想制作一个更通用的`nn_model` 函数,具有不同的层大小和这样的参数...... (2认同)