Search code examples
pythonmachine-learningscikit-learnsvmcross-validation

'bad input shape' when using scikit-learn SVM and optunity


I'm trying to use optunity package to tuning my SVM model, I'm directly copy and past it's up-to-date example code , just import the feature array and data array

import optunity
import optunity.metrics
import sklearn.svm
import numpy as np

data_path = '/python/Feature'
files = ['A.npy', 'B.npy', 'C.npy']

array = []
labels = []

for i,name in enumerate(files):
    data = np.load('{}/{}'.format(data_path, name))
    for j in range(0,len(data)):
        labels.append(data[j])
        array.append(data)

print len(array)   #=> 1247
print len(labels)  #=> 1247

# score function: twice iterated 10-fold cross-validated accuracy
@optunity.cross_validated(x=data, y=labels, num_folds=10, num_iter=2)
def svm_auc(x_train, y_train, x_test, y_test, C, gamma):
    model = sklearn.svm.SVC(C=C, gamma=gamma).fit(x_train, y_train)
    decision_values = model.decision_function(x_test)
    return optunity.metrics.roc_auc(y_test, decision_values)

# perform tuning
optimal_pars, _, _ = optunity.maximize(svm_auc, num_evals=200, C=[0, 10], gamma=[0, 1])

# train model on the full training set with tuned hyperparameters
optimal_model = sklearn.svm.SVC(**optimal_pars).fit(data, labels)

However ,compiler looks very unhappy , I have looked at SVM class document to double check the input format ,however I don't understand optunity's coding syntax .. can anyone help me find out what's going wrong there? Really appreciated .. (I'm using 'rbf' kernel , I tried to add in but syntax goes wrong , it's strange in optunity's example there is no kernel selection.. )

Traceback (most recent call last):
  File "python/SVM_turning.py", line 26, in <module>
    optimal_pars, _, _ = optunity.maximize(svm_auc, num_evals=200, C=[0, 10], gamma=[0, 1])
  File "/lib/python2.7/site-packages/optunity/api.py", line 181, in maximize
    pmap=pmap)
  File "/lib/python2.7/site-packages/optunity/api.py", line 245, in optimize
    solution, report = solver.optimize(f, maximize, pmap=pmap)
  File "/lib/python2.7/site-packages/optunity/solvers/ParticleSwarm.py", line 257, in optimize
    fitnesses = pmap(evaluate, list(map(self.particle2dict, pop)))
  File "/lib/python2.7/site-packages/optunity/solvers/ParticleSwarm.py", line 246, in evaluate
    return f(**d)
  File "/lib/python2.7/site-packages/optunity/functions.py", line 286, in wrapped_f
    value = f(*args, **kwargs)
  File "/lib/python2.7/site-packages/optunity/functions.py", line 341, in wrapped_f
    return f(*args, **kwargs)
  File "/lib/python2.7/site-packages/optunity/constraints.py", line 150, in wrapped_f
    return f(*args, **kwargs)
  File "/lib/python2.7/site-packages/optunity/constraints.py", line 128, in wrapped_f
    return f(*args, **kwargs)
  File "/lib/python2.7/site-packages/optunity/constraints.py", line 265, in func
    return f(*args, **kwargs)
  File "/lib/python2.7/site-packages/optunity/cross_validation.py", line 386, in __call__
    scores.append(self.f(**kwargs))
  File "/python/SVM_turning.py", line 21, in svm_auc
    model = sklearn.svm.SVC(C=C, gamma=gamma).fit(x_train, y_train)
  File "/lib/python2.7/site-packages/sklearn/svm/base.py", line 138, in fit
    y = self._validate_targets(y)
  File "/lib/python2.7/site-packages/sklearn/svm/base.py", line 441, in _validate_targets
    y_ = column_or_1d(y, warn=True)
  File "/lib/python2.7/site-packages/sklearn/utils/validation.py", line 319, in column_or_1d
    raise ValueError("bad input shape {0}".format(shape))
ValueError: bad input shape (428, 600)

Solution

  • I think I found the problem. You are preparing the lists array and labels while reading files. array gets filled with data sequentially. However, later, you do this:

    @optunity.cross_validated(x=data, y=labels, num_folds=10, num_iter=2)
    

    and

    optimal_model = sklearn.svm.SVC(**optimal_pars).fit(data, labels)
    

    and hence use data as your data set, rather than array which you prepared. I don't know the format of what you're reading from files, so I can't say for sure what's going on. However, the dimensions of data and labels almost surely won't match.

    Here's a toy example with array and labels that does work properly:

    import optunity
    import optunity.metrics
    import sklearn.svm
    import numpy as np
    
    #print len(array)   #=> 1247
    #print len(labels)  #=> 1247
    
    # make dummy data
    array = np.array([[i] for i in range(1247)])
    labels = [True] * 100 + [False] * 1147
    
    # score function: twice iterated 10-fold cross-validated accuracy
    @optunity.cross_validated(x=array, y=labels, num_folds=10, num_iter=2)
    def svm_auc(x_train, y_train, x_test, y_test, C, gamma):
        model = sklearn.svm.SVC(C=C, gamma=gamma).fit(x_train, y_train)
        decision_values = model.decision_function(x_test)
        return optunity.metrics.roc_auc(y_test, decision_values)
    
    # perform tuning
    optimal_pars, _, _ = optunity.maximize(svm_auc, num_evals=200, C=[0, 10], gamma=[0, 1])
    
    # train model on the full training set with tuned hyperparameters
    optimal_model = sklearn.svm.SVC(**optimal_pars).fit(array, labels)
    print(optimal_pars)
    

    Which outputs (example):

    {'C': 8.0126953125, 'gamma': 0.35791015625}

    Sorry for taking so long to reply.