草庐IT

java - 如何在 LibSVM 中使用 'svm_toy' Applet 示例?

coder 2024-03-07 原文

我正在使用 LIBSVM。下载包中有一个svm_toy.java文件。我不知道它是如何工作的。这是源代码:

import libsvm.*;
import java.applet.*;
import java.awt.*;
import java.util.*;
import java.awt.event.*;
import java.io.*;

/**
 * SVM package 
 * @author unknown
 *
 */
public class svm_toy extends Applet {

    static final String DEFAULT_PARAM="-t 2 -c 100";
    int XLEN;
    int YLEN;

    // off-screen buffer

    Image buffer;
    Graphics buffer_gc;

    // pre-allocated colors

    final static Color colors[] =
    {
      new Color(0,0,0),
      new Color(0,120,120),
      new Color(120,120,0),
      new Color(120,0,120),
      new Color(0,200,200),
      new Color(200,200,0),
      new Color(200,0,200)
    };

    class point {
        point(double x, double y, byte value)
        {
            this.x = x;
            this.y = y;
            this.value = value;
        }
        double x, y;
        byte value;
    }

    Vector<point> point_list = new Vector<point>();
    byte current_value = 1;

    public void init()
    {
        setSize(getSize());

        final Button button_change = new Button("Change");
        Button button_run = new Button("Run");
        Button button_clear = new Button("Clear");
        Button button_save = new Button("Save");
        Button button_load = new Button("Load");
        final TextField input_line = new TextField(DEFAULT_PARAM);

        BorderLayout layout = new BorderLayout();
        this.setLayout(layout);

        Panel p = new Panel();
        GridBagLayout gridbag = new GridBagLayout();
        p.setLayout(gridbag);

        GridBagConstraints c = new GridBagConstraints();
        c.fill = GridBagConstraints.HORIZONTAL;
        c.weightx = 1;
        c.gridwidth = 1;
        gridbag.setConstraints(button_change,c);
        gridbag.setConstraints(button_run,c);
        gridbag.setConstraints(button_clear,c);
        gridbag.setConstraints(button_save,c);
        gridbag.setConstraints(button_load,c);
        c.weightx = 5;
        c.gridwidth = 5;
        gridbag.setConstraints(input_line,c);

        button_change.setBackground(colors[current_value]);

        p.add(button_change);
        p.add(button_run);
        p.add(button_clear);
        p.add(button_save);
        p.add(button_load);
        p.add(input_line);
        this.add(p,BorderLayout.SOUTH);

        button_change.addActionListener(new ActionListener()
        { public void actionPerformed (ActionEvent e)
          { button_change_clicked(); button_change.setBackground(colors[current_value]); }});

        button_run.addActionListener(new ActionListener()
        { public void actionPerformed (ActionEvent e)
          { button_run_clicked(input_line.getText()); }});

        button_clear.addActionListener(new ActionListener()
        { public void actionPerformed (ActionEvent e)
          { button_clear_clicked(); }});

        button_save.addActionListener(new ActionListener()
        { public void actionPerformed (ActionEvent e)
          { button_save_clicked(input_line.getText()); }});

        button_load.addActionListener(new ActionListener()
        { public void actionPerformed (ActionEvent e)
          { button_load_clicked(); }});

        input_line.addActionListener(new ActionListener()
        { public void actionPerformed (ActionEvent e)
          { button_run_clicked(input_line.getText()); }});

        this.enableEvents(AWTEvent.MOUSE_EVENT_MASK);
    }

    void draw_point(point p)
    {
        Color c = colors[p.value+3];

        Graphics window_gc = getGraphics();
        buffer_gc.setColor(c);
        buffer_gc.fillRect((int)(p.x*XLEN),(int)(p.y*YLEN),4,4);
        window_gc.setColor(c);
        window_gc.fillRect((int)(p.x*XLEN),(int)(p.y*YLEN),4,4);
    }

    void clear_all()
    {
        point_list.removeAllElements();
        if(buffer != null)
        {
            buffer_gc.setColor(colors[0]);
            buffer_gc.fillRect(0,0,XLEN,YLEN);
        }
        repaint();
    }

    void draw_all_points()
    {
        int n = point_list.size();
        for(int i=0;i<n;i++)
            draw_point(point_list.elementAt(i));
    }

    void button_change_clicked()
    {
        ++current_value;
        if(current_value > 3) current_value = 1;
    }

    private static double atof(String s)
    {
        return Double.valueOf(s).doubleValue();
    }

    private static int atoi(String s)
    {
        return Integer.parseInt(s);
    }

    void button_run_clicked(String args)
    {
        // guard
        if(point_list.isEmpty()) return;

        svm_parameter param = new svm_parameter();

        // default values
        param.svm_type = svm_parameter.C_SVC;
        param.kernel_type = svm_parameter.RBF;
        param.degree = 3;
        param.gamma = 0;
        param.coef0 = 0;
        param.nu = 0.5;
        param.cache_size = 40;
        param.C = 1;
        param.eps = 1e-3;
        param.p = 0.1;
        param.shrinking = 1;
        param.probability = 0;
        param.nr_weight = 0;
        param.weight_label = new int[0];
        param.weight = new double[0];

        // parse options
        StringTokenizer st = new StringTokenizer(args);
        String[] argv = new String[st.countTokens()];
        for(int i=0;i<argv.length;i++)
            argv[i] = st.nextToken();

        for(int i=0;i<argv.length;i++)
        {
            if(argv[i].charAt(0) != '-') break;
            if(++i>=argv.length)
            {
                System.err.print("unknown option\n");
                break;
            }
            switch(argv[i-1].charAt(1))
            {
                case 's':
                    param.svm_type = atoi(argv[i]);
                    break;
                case 't':
                    param.kernel_type = atoi(argv[i]);
                    break;
                case 'd':
                    param.degree = atoi(argv[i]);
                    break;
                case 'g':
                    param.gamma = atof(argv[i]);
                    break;
                case 'r':
                    param.coef0 = atof(argv[i]);
                    break;
                case 'n':
                    param.nu = atof(argv[i]);
                    break;
                case 'm':
                    param.cache_size = atof(argv[i]);
                    break;
                case 'c':
                    param.C = atof(argv[i]);
                    break;
                case 'e':
                    param.eps = atof(argv[i]);
                    break;
                case 'p':
                    param.p = atof(argv[i]);
                    break;
                case 'h':
                    param.shrinking = atoi(argv[i]);
                    break;
                case 'b':
                    param.probability = atoi(argv[i]);
                    break;
                case 'w':
                    ++param.nr_weight;
                    {
                        int[] old = param.weight_label;
                        param.weight_label = new int[param.nr_weight];
                        System.arraycopy(old,0,param.weight_label,0,param.nr_weight-1);
                    }

                    {
                        double[] old = param.weight;
                        param.weight = new double[param.nr_weight];
                        System.arraycopy(old,0,param.weight,0,param.nr_weight-1);
                    }

                    param.weight_label[param.nr_weight-1] = atoi(argv[i-1].substring(2));
                    param.weight[param.nr_weight-1] = atof(argv[i]);
                    break;
                default:
                    System.err.print("unknown option\n");
            }
        }

        // build problem
        svm_problem prob = new svm_problem();
        prob.l = point_list.size();
        prob.y = new double[prob.l];

        if(param.kernel_type == svm_parameter.PRECOMPUTED)
        {
        }
        else if(param.svm_type == svm_parameter.EPSILON_SVR ||
            param.svm_type == svm_parameter.NU_SVR)
        {
            if(param.gamma == 0) param.gamma = 1;
            prob.x = new svm_node[prob.l][1];
            for(int i=0;i<prob.l;i++)
            {
                point p = point_list.elementAt(i);
                prob.x[i][0] = new svm_node();
                prob.x[i][0].index = 1;
                prob.x[i][0].value = p.x;
                prob.y[i] = p.y;
            }

            // build model & classify
            svm_model model = svm.svm_train(prob, param);
            svm_node[] x = new svm_node[1];
            x[0] = new svm_node();
            x[0].index = 1;
            int[] j = new int[XLEN];

            Graphics window_gc = getGraphics();
            for (int i = 0; i < XLEN; i++)
            {
                x[0].value = (double) i / XLEN;
                j[i] = (int)(YLEN*svm.svm_predict(model, x));
            }

            buffer_gc.setColor(colors[0]);
            buffer_gc.drawLine(0,0,0,YLEN-1);
            window_gc.setColor(colors[0]);
            window_gc.drawLine(0,0,0,YLEN-1);

            int p = (int)(param.p * YLEN);
            for(int i=1;i<XLEN;i++)
            {
                buffer_gc.setColor(colors[0]);
                buffer_gc.drawLine(i,0,i,YLEN-1);
                window_gc.setColor(colors[0]);
                window_gc.drawLine(i,0,i,YLEN-1);

                buffer_gc.setColor(colors[5]);
                window_gc.setColor(colors[5]);
                buffer_gc.drawLine(i-1,j[i-1],i,j[i]);
                window_gc.drawLine(i-1,j[i-1],i,j[i]);

                if(param.svm_type == svm_parameter.EPSILON_SVR)
                {
                    buffer_gc.setColor(colors[2]);
                    window_gc.setColor(colors[2]);
                    buffer_gc.drawLine(i-1,j[i-1]+p,i,j[i]+p);
                    window_gc.drawLine(i-1,j[i-1]+p,i,j[i]+p);

                    buffer_gc.setColor(colors[2]);
                    window_gc.setColor(colors[2]);
                    buffer_gc.drawLine(i-1,j[i-1]-p,i,j[i]-p);
                    window_gc.drawLine(i-1,j[i-1]-p,i,j[i]-p);
                }
            }
        }
        else
        {
            if(param.gamma == 0) param.gamma = 0.5;
            prob.x = new svm_node [prob.l][2];
            for(int i=0;i<prob.l;i++)
            {
                point p = point_list.elementAt(i);
                prob.x[i][0] = new svm_node();
                prob.x[i][0].index = 1;
                prob.x[i][0].value = p.x;
                prob.x[i][1] = new svm_node();
                prob.x[i][1].index = 2;
                prob.x[i][1].value = p.y;
                prob.y[i] = p.value;
            }

            // build model & classify
            svm_model model = svm.svm_train(prob, param);
            svm_node[] x = new svm_node[2];
            x[0] = new svm_node();
            x[1] = new svm_node();
            x[0].index = 1;
            x[1].index = 2;

            Graphics window_gc = getGraphics();
            for (int i = 0; i < XLEN; i++)
                for (int j = 0; j < YLEN ; j++) {
                    x[0].value = (double) i / XLEN;
                    x[1].value = (double) j / YLEN;
                    double d = svm.svm_predict(model, x);
                    if (param.svm_type == svm_parameter.ONE_CLASS && d<0) d=2;
                    buffer_gc.setColor(colors[(int)d]);
                    window_gc.setColor(colors[(int)d]);
                    buffer_gc.drawLine(i,j,i,j);
                    window_gc.drawLine(i,j,i,j);
            }
        }

        draw_all_points();
    }

    void button_clear_clicked()
    {
        clear_all();
    }

    void button_save_clicked(String args)
    {
        FileDialog dialog = new FileDialog(new Frame(),"Save",FileDialog.SAVE);
        dialog.setVisible(true);
        String filename = dialog.getDirectory() + dialog.getFile();
        if (filename == null) return;
        try {
            DataOutputStream fp = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(filename)));

            int svm_type = svm_parameter.C_SVC;
            int svm_type_idx = args.indexOf("-s ");
            if(svm_type_idx != -1)
            {
                StringTokenizer svm_str_st = new StringTokenizer(args.substring(svm_type_idx+2).trim());
                svm_type = atoi(svm_str_st.nextToken());
            }

            int n = point_list.size();
            if(svm_type == svm_parameter.EPSILON_SVR || svm_type == svm_parameter.NU_SVR)
            {
                for(int i=0;i<n;i++)
                {
                    point p = point_list.elementAt(i);
                    fp.writeBytes(p.y+" 1:"+p.x+"\n");
                }
            }
            else
            {
                for(int i=0;i<n;i++)
                {
                    point p = point_list.elementAt(i);
                    fp.writeBytes(p.value+" 1:"+p.x+" 2:"+p.y+"\n");
                }
            }
            fp.close();
        } catch (IOException e) { System.err.print(e); }
    }

    void button_load_clicked()
    {
        FileDialog dialog = new FileDialog(new Frame(),"Load",FileDialog.LOAD);
        dialog.setVisible(true);
        String filename = dialog.getDirectory() + dialog.getFile();
        if (filename == null) return;
        clear_all();
        try {
            BufferedReader fp = new BufferedReader(new FileReader(filename));
            String line;
            while((line = fp.readLine()) != null)
            {
                StringTokenizer st = new StringTokenizer(line," \t\n\r\f:");
                if(st.countTokens() == 5)
                {
                    byte value = (byte)atoi(st.nextToken());
                    st.nextToken();
                    double x = atof(st.nextToken());
                    st.nextToken();
                    double y = atof(st.nextToken());
                    point_list.addElement(new point(x,y,value));
                }
                else if(st.countTokens() == 3)
                {
                    double y = atof(st.nextToken());
                    st.nextToken();
                    double x = atof(st.nextToken());
                    point_list.addElement(new point(x,y,current_value));
                }else
                    break;
            }
            fp.close();
        } catch (IOException e) { System.err.print(e); }
        draw_all_points();
    }

    protected void processMouseEvent(MouseEvent e)
    {
        if(e.getID() == MouseEvent.MOUSE_PRESSED)
        {
            if(e.getX() >= XLEN || e.getY() >= YLEN) return;
            point p = new point((double)e.getX()/XLEN,
                        (double)e.getY()/YLEN,
                        current_value);
            point_list.addElement(p);
            draw_point(p);
        }
    }

    public void paint(Graphics g)
    {
        // create buffer first time
        if(buffer == null) {
            buffer = this.createImage(XLEN,YLEN);
            buffer_gc = buffer.getGraphics();
            buffer_gc.setColor(colors[0]);
            buffer_gc.fillRect(0,0,XLEN,YLEN);
        }
        g.drawImage(buffer,0,0,this);
    }

    public Dimension getPreferredSize() { return new Dimension(XLEN,YLEN+50); }

    public void setSize(Dimension d) { setSize(d.width,d.height); }
    public void setSize(int w,int h) {
        super.setSize(w,h);
        XLEN = w;
        YLEN = h-50;
        clear_all();
    }

    public static void main(String[] argv)
    {
        new AppletFrame("svm_toy",new svm_toy(),500,500+50);
    }
}

class AppletFrame extends Frame {
    AppletFrame(String title, Applet applet, int width, int height)
    {
        super(title);
        this.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
        applet.init();
        applet.setSize(width,height);
        applet.start();
        this.add(applet);
        this.pack();
        this.setVisible(true);
    }

}

有人可以给我一个例子或解释吗?我还想扩展我的训练数据。哪里是扩展的正确位置?

谢谢

最佳答案

SVM 玩具

顾名思义,SVM Toy 是一个简单的玩具,由 LIBSVM 开发团队构建,不推荐用于“高效”可视化 SVM 的决策边界。

此外,查看 svm_toy 的源代码可以清楚地看出,该工具仅支持 2D vector 。

相关代码片段取自button_load_clicked()方法:

while ((line = fp.readLine()) != null) {
    StringTokenizer st = new StringTokenizer(line, " \t\n\r\f:");
        if (st.countTokens() == 5) {
            byte value = (byte) atoi(st.nextToken());
            st.nextToken();
            double x = atof(st.nextToken());
            st.nextToken();
            double y = atof(st.nextToken());
            point_list.addElement(new point(x, y, value));
        } else if (st.countTokens() == 3) {
            double y = atof(st.nextToken());
            st.nextToken();
            double x = atof(st.nextToken());
            point_list.addElement(new point(x, y, current_value));
        } else {
            break;
        }
    }

如您所见,svm_toy 实现只能处理二维 vector ,这意味着它只支持由两个特征构成的 vector 。

这意味着,您只能读取和显示仅由两个功能构建的文件,例如 fourclass LIBSVM 作者提供的数据集。然而,这个实现似乎不支持这个特性。

我认为,该工具是为交互式可视化而设计的。您可以更改颜色并单击黑色应用程序屏幕。设置一些点(每种颜色代表自己的类别)后,您可以单击“运行”并显示决策边界。

在高维 vector 空间中显示决策边界甚至几乎是不可能的。我建议不要将此工具实现用于任何生产/科学目的。

缩放

训练数据的缩放应在将其转换为数字表示之后以及继续使用此数据训练 SVM 之前完成。

简而言之,您必须在使用 svm_train 之前执行以下步骤

  1. 为每个数据点构建数字表示(借助特征选择,...)
  2. 分析每个数据点的结果数字表示
  3. 将数据缩放到 [-1,1] 等范围
  4. 继续训练您的 SVM 模型。请注意,您必须重复 1-3 来预测未知数据点。唯一的区别是,您已经知道必要的特征,因此无需进行特征选择。

关于java - 如何在 LibSVM 中使用 'svm_toy' Applet 示例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33993362/

有关java - 如何在 LibSVM 中使用 'svm_toy' Applet 示例?的更多相关文章

  1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

    我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

  2. ruby - 使用 RubyZip 生成 ZIP 文件时设置压缩级别 - 2

    我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看ruby​​zip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d

  3. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  4. ruby-on-rails - 使用 Ruby on Rails 进行自动化测试 - 最佳实践 - 2

    很好奇,就使用ruby​​onrails自动化单元测试而言,你们正在做什么?您是否创建了一个脚本来在cron中运行rake作业并将结果邮寄给您?git中的预提交Hook?只是手动调用?我完全理解测试,但想知道在错误发生之前捕获错误的最佳实践是什么。让我们理所当然地认为测试本身是完美无缺的,并且可以正常工作。下一步是什么以确保他们在正确的时间将可能有害的结果传达给您? 最佳答案 不确定您到底想听什么,但是有几个级别的自动代码库控制:在处理某项功能时,您可以使用类似autotest的内容获得关于哪些有效,哪些无效的即时反馈。要确保您的提

  5. ruby - 在 Ruby 中使用匿名模块 - 2

    假设我做了一个模块如下:m=Module.newdoclassCendend三个问题:除了对m的引用之外,还有什么方法可以访问C和m中的其他内容?我可以在创建匿名模块后为其命名吗(就像我输入“module...”一样)?如何在使用完匿名模块后将其删除,使其定义的常量不再存在? 最佳答案 三个答案:是的,使用ObjectSpace.此代码使c引用你的类(class)C不引用m:c=nilObjectSpace.each_object{|obj|c=objif(Class===objandobj.name=~/::C$/)}当然这取决于

  6. ruby - 如何在 Ruby 中顺序创建 PI - 2

    出于纯粹的兴趣,我很好奇如何按顺序创建PI,而不是在过程结果之后生成数字,而是让数字在过程本身生成时显示。如果是这种情况,那么数字可以自行产生,我可以对以前看到的数字实现垃圾收集,从而创建一个无限系列。结果只是在Pi系列之后每秒生成一个数字。这是我通过互联网筛选的结果:这是流行的计算机友好算法,类机器算法:defarccot(x,unity)xpow=unity/xn=1sign=1sum=0loopdoterm=xpow/nbreakifterm==0sum+=sign*(xpow/n)xpow/=x*xn+=2sign=-signendsumenddefcalc_pi(digits

  7. ruby - 使用 ruby​​ 和 savon 的 SOAP 服务 - 2

    我正在尝试使用ruby​​和Savon来使用网络服务。测试服务为http://www.webservicex.net/WS/WSDetails.aspx?WSID=9&CATID=2require'rubygems'require'savon'client=Savon::Client.new"http://www.webservicex.net/stockquote.asmx?WSDL"client.get_quotedo|soap|soap.body={:symbol=>"AAPL"}end返回SOAP异常。检查soap信封,在我看来soap请求没有正确的命名空间。任何人都可以建议我

  8. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  9. ruby-on-rails - rails : "missing partial" when calling 'render' in RSpec test - 2

    我正在尝试测试是否存在表单。我是Rails新手。我的new.html.erb_spec.rb文件的内容是:require'spec_helper'describe"messages/new.html.erb"doit"shouldrendertheform"dorender'/messages/new.html.erb'reponse.shouldhave_form_putting_to(@message)with_submit_buttonendendView本身,new.html.erb,有代码:当我运行rspec时,它失败了:1)messages/new.html.erbshou

  10. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

    我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

随机推荐