⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 kaverage.java~152~

📁 java 实现K均值算法 编成工具:JBuilder
💻 JAVA~152~
字号:
package kaverage;

import java.awt.Frame;
import java.awt.Button;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.util.*;
public class KAverage extends Frame {
    public KAverage() {
        try {
            jbInit();
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }

    private void jbInit() throws Exception {
        this.setLayout(null);
        button1.setFont(new java.awt.Font("华文行楷", Font.BOLD, 20));
        button1.setForeground(Color.red);
        button1.setLabel("分类");
        button1.setBounds(new Rectangle(70, 509, 119, 41));
        button1.addActionListener(new KAverage_button1_actionAdapter(this));
        label1.setAlignment(Label.CENTER);
        label1.setFont(new java.awt.Font("华文新魏", Font.BOLD, 20));
        label1.setForeground(new Color(255, 138, 0));
        label1.setText("请输入K值");
        label1.setBounds(new Rectangle(111, 130, 116, 28));
        button2.setBackground(new Color(236, 233, 216));
        button2.setFont(new java.awt.Font("方正舒体", Font.BOLD, 20));
        button2.setForeground(new Color(111, 228, 76));
        button2.setLabel("导入数据");
        button2.setBounds(new Rectangle(172, 70, 119, 42));
        button2.addActionListener(new KAverage_button2_actionAdapter(this));
        textInputK.setBounds(new Rectangle(243, 133, 104, 22));
        this.setBackground(Color.lightGray);
        this.setForeground(Color.black);
        this.setTitle("KAverage");
        textInput.setEditable(false);
        textInput.setText("");
        textInput.setBounds(new Rectangle(41, 193, 188, 301));
        textOutput.setBackground(Color.white);
        textOutput.setEditable(false);
        textOutput.setText("");
        textOutput.setBounds(new Rectangle(235, 193, 186, 301));
        button3.setFont(new java.awt.Font("华文彩云", Font.BOLD, 20));
        button3.setForeground(Color.blue);
        button3.setLabel("保存结果");
        button3.setBounds(new Rectangle(268, 510, 123, 41));
        button3.addActionListener(new KAverage_button3_actionAdapter(this));
        jLabelInput.setFont(new java.awt.Font("黑体", Font.BOLD, 15));
        jLabelInput.setForeground(new Color(255, 28, 175));
        jLabelInput.setDisplayedMnemonic('0');
        jLabelInput.setText("数据导入窗口:");
        jLabelInput.setBounds(new Rectangle(45, 167, 127, 21));
        jLabelOutput.setFont(new java.awt.Font("华文彩云", Font.BOLD, 15));
        jLabelOutput.setForeground(new Color(166, 180, 0));
        jLabelOutput.setText("分类结果:");
        jLabelOutput.setBounds(new Rectangle(237, 167, 98, 27));
        this.add(button3);
        this.add(button1);
        this.add(textInput);
        this.add(button2);
        this.add(label1);
        this.add(textInputK);
        this.add(textOutput);
        this.add(jLabelInput);
        this.add(jLabelOutput);
    }

    public static void main(String[] args) {
        KAverage kaverage = new KAverage();
        kaverage.setBounds(100,100,500,600);
        kaverage.show();
        kaverage.addWindowListener(new WindowAdapter(){
        public void windowClosing(WindowEvent e)
        {System.exit(0);}});
}

    Button button1 = new Button();
    Label label1 = new Label();
    Button button2 = new Button();
    TextField textInputK = new TextField();
    TextArea textInput = new TextArea();
    TextArea textOutput = new TextArea();
    Button button3 = new Button();
    JFileChooser fileChooser = new JFileChooser("e:/java");
    JLabel jLabelInput = new JLabel();
    JLabel jLabelOutput = new JLabel();
    File file;
    String currentFileName = null;
//    int [][]data;
//    boolean check=true;
    PointF data[],z[],z0[];
    int count = 0,k,test=0;
    int type[];
    PointF sum;
    int l = 0;          //迭代次数
    boolean check = true;
    public void button2_actionPerformed(ActionEvent e) {
        inputData();
        saveData(file);
    }

    public void inputData()
    {
        int n = fileChooser.showOpenDialog(this);
        if(n == JFileChooser.APPROVE_OPTION)
        {
                file = fileChooser.getSelectedFile();

                try
                {
                        FileReader readfile = new FileReader(file);
                        BufferedReader in = new BufferedReader(readfile);
                        textInput.setText(null);
                        String s = null;
                        while((s = in.readLine()) != null)
                        {
                        textInput.append(s+"\n");
                        }
                        in.close();
                }
                catch(IOException ee)
                {
                textInput.setText("你没有选择文件");
                }
         }
    }

    public void saveData(File file)
    {
        String s;
        try
        {
            DataInputStream in = new DataInputStream(new FileInputStream(
                    file));
            while ((s = in.readLine()) != null) {
                count++;
            }
            in.close();
            in = new DataInputStream(new FileInputStream(file));
            data = new PointF[count];
            type = new int[count];
            count = 0;
            while ((s = in.readLine()) != null) {
                data[count] = new PointF();
                data[count].x = Integer.parseInt(s.substring(0,s.indexOf(",")));
                data[count].y = Integer.parseInt(s.substring(s.indexOf(",")+1,s.length()));
                count++;
            }
        }

        catch(IOException e)
        {

        }
    }

    public void button1_actionPerformed(ActionEvent e) {
        if(textInput.getText().equals(""))
        {
            JOptionPane.showMessageDialog(this,"您还没有导入数据,请导入","警告对话筐",
                                                                JOptionPane.WARNING_MESSAGE);
            return;
        }
        else
        {
            try {
                k = Integer.parseInt(textInputK.getText());
            } catch (Exception e1) {
                JOptionPane.showMessageDialog(this,"您输入的k值不是整数,请重新输入","警告对话筐",
                                                                JOptionPane.WARNING_MESSAGE);
                return;
            }


        if(k <= count)
        {
            z = new PointF[k];
            z0 = new PointF[k];
            textOutput.setText("");
            for(int i=0;i<k;i++)
            {
                z[i] = data[i];
                z0[i] = data[i];
            }
            for(int i=0;i<k;i++)
                textOutput.append("初始时,第"+(i+1)+"类聚类中心:"+(int)z[i].x+","+(int)z[i].y+"\n");

            while(check)
            {
                int temp = 0; //记录data[i]暂时在哪个类中
                for (int i = 0; i < count; i++) {
                    for (int j = 0; j < k; j++) {
                        if (distance(data[i], z[temp]) > distance(data[i], z[j]))
                            temp = j;
                    }
                    type[i] = temp;
                }
  ///////////////////////////////
                 for(int j=0;j<k;j++)
                 {
                      textOutput.append("第"+(j+1)+"类有:\n");
                      for(int i=0;i<count;i++)
                      {
                          if(type[i] == j)
                              textOutput.append((int)data[i].x+","+(int)data[i].y+"\n");
                      }
                 }
                 for(int i=0;i<k;i++)
                 {
                     z[i] = newCenter(i);
                     textOutput.append("第"+(i+1)+"类新聚类中心:"+z[i].x+","+z[i].y+"\n");
                 }
                 for(int i=0;i<k;i++)
                 {
                      if(compare(z0[i],z[i]))
                          test = test+1;
                 }
                 if(test == k)
                     check = false;
                 else
                      {
                          for(int i=0;i<k;i++)
                                    z0[i] = z[i];
                          test = 0;
                      }
////////////////////////////////////////
                 l = l+1;
                 textOutput.append("******已完成第"+l+"次迭代*******"+"\n");
              }
              check = true;
              test = 0;
              l = 0;
              textOutput.append("\n"+"最后的分类结果为:"+"\n");
              for(int j=0;j<k;j++)
              {
                   textOutput.append("第"+(j+1)+"类有:\n");
                   for(int i=0;i<count;i++)
                   {
                       if(type[i] == j)
                           textOutput.append((int)data[i].x+","+(int)data[i].y+"\n");
                   }
                 }
              textOutput.setForeground(Color.red);
              textOutput.append("\n"+"注意:"+"\n");
              textOutput.append("结果保存在.txt文件中时,回车符用记事本打开是黑块,但是用其他文本编辑,如UltraEdit,是没有问题的"+"\n");
              textOutput.setForeground(Color.BLACK);
        }
        else
        {
            JOptionPane.showMessageDialog(this,"所分类数已超限,请重新输入","警告对话筐",
                                                                JOptionPane.WARNING_MESSAGE);
            return;
        }
    }
}
    //计算两个点的欧式距离
    public double distance(PointF p1,PointF p2)
    {
         return((p1.x-p2.x)*(p1.x-p2.x)+ (p1.y-p2.y)*(p1.y-p2.y));
    }
    //计算新的聚类中心
    public PointF newCenter(int m)
    {
         int N = 0;
         sum = new PointF();
         for(int i=0;i<count;i++)
         {
              if(type[i] == m)
              {
                  sum.x = data[i].x+sum.x;
                  sum.y = data[i].y+sum.y;
                  N += 1;
              }
         }
         sum.x=sum.x/N;
         sum.y=sum.y/N;
         return sum;
    }
    //比较两个聚类中心的是否相等
    private boolean compare(PointF a,PointF b)
    {
         if(((int)(a.x*10) == (int)(b.x*10)) && ((int)(a.y*10) == (int)(b.y*10)))
              return true;
         else
              return false;
    }
    //进行迭代,对total个样本根据聚类中心进行分类
    private void order()
    {
         int temp = 0;//记录data[i]暂时在哪个类中
         for(int i=0;i<count;i++)
         {
              for(int j=0;j<k;j++)
              {
                  if(distance(data[i],z[temp]) > distance(data[i],z[j]))
                       temp = j;
              }
              type[i] = temp;
         }
    }

    public void button3_actionPerformed(ActionEvent e) {
        int n = fileChooser.showSaveDialog(this);
        if(n == JFileChooser.APPROVE_OPTION)
        {
                currentFileName = fileChooser.getSelectedFile().getPath();
                 file = new File(currentFileName);
                try
                {
                      /*  FileReader readfile = new FileReader(file);
                        BufferedReader in = new BufferedReader(readfile);
                        textInput.setText(null);
                        String s = null;
                        while((s = in.readLine()) != null)
                        {
                        textInput.append(s+"\n");
                        }*/
                      FileOutputStream out = new FileOutputStream(file);
                      String s = textOutput.getText();
                      out.write(s.getBytes());
                      out.close();
                }
                catch(IOException ee)
                {
                textInput.setText("你没有选择文件");
                }
         }
    }
}


class KAverage_button3_actionAdapter implements ActionListener {
    private KAverage adaptee;
    KAverage_button3_actionAdapter(KAverage adaptee) {
        this.adaptee = adaptee;
    }

    public void actionPerformed(ActionEvent e) {
        adaptee.button3_actionPerformed(e);
    }
}


class KAverage_button1_actionAdapter implements ActionListener {
    private KAverage adaptee;
    KAverage_button1_actionAdapter(KAverage adaptee) {
        this.adaptee = adaptee;
    }

    public void actionPerformed(ActionEvent e) {
        adaptee.button1_actionPerformed(e);
    }
}


class KAverage_button2_actionAdapter implements ActionListener {
    private KAverage adaptee;
    KAverage_button2_actionAdapter(KAverage adaptee) {
        this.adaptee = adaptee;
    }

    public void actionPerformed(ActionEvent e) {

        adaptee.button2_actionPerformed(e);
    }
}

class PointF
{
    double x;
    double y;
    public PointF()
    {
        x = 0;
        y = 0;
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -