How to use dlib's LDA

拟墨画扇 提交于 2019-12-24 19:41:46

问题


I want to fit dlib's LDA on my training set and apply the transformation to both the training and testing set. I wrote following minimal example to reproduce the problem. If you delete the sections that uses LDA, it should output a meaningful prediction.

#include <iostream>
#include <vector>
#include <dlib/svm.h>

int main() {

    typedef dlib::matrix<float, 2, 1> sample_type;
    typedef dlib::radial_basis_kernel<sample_type> kernel_type;
    dlib::svm_c_trainer<kernel_type> trainer;
    trainer.set_kernel(kernel_type(0.5f));
    trainer.set_c(1.0f);

    std::vector<sample_type> samples_train;
    std::vector<float> labels_train;
    std::vector<sample_type> samples_test;
    std::vector<float> labels_test;

    sample_type sample;
    float label;

    label = -1;
    sample(0) = -1;
    sample(1) = -1;
    samples_train.push_back(sample);
    labels_train.push_back(label);

    label = 1;
    sample(0) = 1;
    sample(1) = 1;
    samples_train.push_back(sample);
    labels_train.push_back(label);

    label = 1;
    sample(0) = 0.5;
    sample(1) = 0.5;
    samples_test.push_back(sample);
    labels_test.push_back(label);

    // Fit LDA on training data
    dlib::matrix<sample_type> X;
    dlib::matrix<sample_type,0,1> mean;
    dlib::compute_lda_transform(X, mean, labels_train);

    // Apply LDA on train data
    for (auto &sample_train : samples_train){
        sample_train = X * sample_train;
    }

    // Apply LDA on test data
    for (auto &sample_test : samples_test){
        sample_test = X * sample_test;
    }

    auto predictor = trainer.train(samples_train, labels_train);

    std::cout << "Train Sample 1: " << predictor(samples_train[0]) << ", label: " << labels_train[0] << std::endl;
    std::cout << "Train Sample 2: " << predictor(samples_train[1]) << ", label: " << labels_train[1] << std::endl;
    std::cout << "Test Sample: " << predictor(samples_test[0]) << ", label: " << labels_test[0] << std::endl;

}

Error:

cannot convert 'labels_train' (type 'std::__debug::vector<float>') to type 'const std::__debug::vector<long unsigned int>&'

But if the labels are not of the same type as the samples, the SVM throws an error. I could not find any example on dlib's github repository.


回答1:


You should use two set of labels, one being of type long unsigned for the lda and another of type float for your SVM



来源:https://stackoverflow.com/questions/46910328/how-to-use-dlibs-lda

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!