在mat2py中如何修复错误AttributeError:'numpy.ndarray'对象没有属性'get_svm_type'

时间:2019-05-08 09:00:13

标签: python matlab

我正在尝试将Matlab代码转换为Python代码。我已经使用libsvm下载了sudo apt-get install python-libsvm库,但出现错误。

import scipy.io
from svmutil import svm_predict
def SVM_LIBSVM(VECTOR_TRAINING_LABELS , VECTOR_TRAINING_POINTS ,VECTOR_TESTING_LABELS , VECTOR_TESTING_POINTS):
    mat = scipy.io.loadmat('model.mat')
    model = mat['model']
    predicted_label = list()
    predicted_label = svm_predict(VECTOR_TESTING_LABELS , VECTOR_TESTING_POINTS , model)
    return predicted_label

我遇到以下错误:

File "/home/optimum/mat2py/svmutil.py", line 193, in svm_predict
    svm_type = m.get_svm_type()
AttributeError: 'numpy.ndarray' object has no attribute 'get_svm_type'

1 个答案:

答案 0 :(得分:0)

我假设model对象来自MATLAB libsvm接口,这将使其成为MATLAB结构而不是svm_model对象。 AFAIK没有直接转换,但是您应该能够从struct中读取字段,您可以将其用于python svm_model对象(对此不是100%;我没有使用过python API)。

model_parameters = model['Parameters']
model_nr_class = model['nr_class']
model_total_sv = model['totalSV']
model_rho = model['rho']
model_label = model['Label']
model_sv_indices = model['sv_indices']
model_prob_a = model['ProbA']
model_prob_b = model['ProbB']
model_n_sv = model['nSV']
model_sv_coef = model['sv_coef']
model_svs = model['SVs']

如果您无法在python中找到方法,则最痛苦的生成方法是将MATLAB结构值移动到ctypes结构,然后使用toPyModel(python API)将其转换为python svm_model

struct svm_model
{
    struct svm_parameter param; /* parameter */
    int nr_class;       /* number of classes, = 2 in regression/one class svm */
    int l;          /* total #SV */
    struct svm_node **SV;       /* SVs (SV[l]) */
    double **sv_coef;   /* coefficients for SVs in decision functions (sv_coef[k-1][l]) */
    double *rho;        /* constants in decision functions (rho[k*(k-1)/2]) */
    double *probA;      /* pairwise probability information */
    double *probB;
    int *sv_indices;        /* sv_indices[0,...,nSV-1] are values in [1,...,num_traning_data] to indicate SVs in the training set */

    /* for classification only */

    int *label;     /* label of each class (label[k]) */
    int *nSV;       /* number of SVs for each class (nSV[k]) */
                /* nSV[0] + nSV[1] + ... + nSV[k-1] = l */
    /* XXX */
    int free_sv;        /* 1 if svm_model is created by svm_load_model*/
                /* 0 if svm_model is created by svm_train */
};