id
stringlengths
36
36
text
stringlengths
1
1.25M
30b8786d-fb1a-4dff-b53d-3b462b4d46dc
public abstract FitnessFunction getFitnessFunction();
f0184a73-0bac-47e3-8529-8117e32cbe28
public abstract Selector getSelector();
0942d4bf-5322-407e-bf90-55f950993463
public abstract GeneticOperator getRecombinationOperator();
9f513933-8358-4092-984a-97f8195edf9e
public abstract List<Mutation> getMutations();
a298d311-b237-484f-af05-c7158f6869d6
public abstract Factory getFactory();
165db94e-a1d9-462e-9d62-656d32404574
public abstract Comparator<Individual> getFitnessComparator();
2439eab8-80fb-4fd2-95d7-5c18f4959df5
public abstract boolean terminationCriteriaMet(Population population);
1522b77a-36f1-4dc8-bd0c-2edd33a1750e
public Random getRandom() { return this.random; }
0e5f96a7-2f47-48b7-aa30-32ad7abc4715
public Population() { individuals = new ArrayList<Individual>(); }
cba7a6a9-5c4a-427a-85a9-e68215ba6d3d
public Population(List<Individual> individuals, int age) { this.individuals = individuals; this.age = age; }
2fd2880f-0e5e-4ea8-aebf-5ace60acaad0
@Override public Iterator<Individual> iterator() { return individuals.listIterator(); }
f4d1d637-3717-4795-a82b-f87a6ae2cfc2
public void addIndividual(Individual individual) { individuals.add(individual); }
5c9b61df-d6cf-483d-97fb-e01cb51abb16
public int size() { return individuals.size(); }
8cb10de4-d0f1-499e-848a-2047ebe98666
public int getAge() { return age; }
86d9cfa6-d5cb-4a97-aba4-f63f81895da7
public List<Individual> getIndividuals() { return Collections.unmodifiableList(individuals); }
bbbf1f21-729f-474d-857d-d15d051afc4b
@Override public String toString() { StringBuilder result = new StringBuilder(); result.append("Population ["); result.append(size()); result.append(", "); for (Individual individual : individuals) { result.append(individual.toString()); result.append(","); } result.append("]"); return result.toString(); }
6009ed34-43cc-4aa2-aaca-6c5eaf6fe432
void add(List<Individual> children) { for (Individual child : children) { addIndividual(child); } }
f2a70f91-f1e6-4e4c-a3f7-13dc33a194a3
public void validate(Population population);
4f601202-6005-4654-9bde-88948f722f74
@Override public void mutate(Individual individual) { individual.getGenom().increaseRandomChromosom(); }
c88e6ee0-5a35-481a-acb6-5dce02b7c0bf
public void mutate(Individual individual);
1dc18a1a-0ec8-402a-90ff-0a2c6a27950c
@Override public void mutate(Individual individual) { individual.getGenom().reduceRandomChromosom(); }
9117f68f-180d-4e01-99c1-dd709fe73e4e
@Override public void mutate(Individual individual) { individual.getGenom().switchRandomChromosomes(); }
c173efce-d7c0-47ba-b374-9b32bb324c02
public Pattern(double[] input, double[] output) { this.input = input.clone(); this.output = output.clone(); }
235bdcfe-7a4b-444e-a965-1f7fe166a10d
public Pattern(BufferedImage img, double[] output) { this.imgInput = img; this.output = output.clone(); }
46b2cca2-91a1-4291-bd91-fa51cbab63cc
public double[] getInput() { return(input); }
68f037ab-7111-4712-b41e-a992073d7dcb
public void setInput(double[] input) { this.input = input; }
28c40272-ff91-4036-8417-558d5b82f99e
public double[] getOutput() { return(output); }
1d996e36-a5fd-4cbd-8aff-15212eaf4193
public BufferedImage getImgInput() { return imgInput; }
266fe6f4-7906-40bc-bc99-48b8238aab3d
public double[] getResult() { return result; }
51cf8dd1-f5d8-407e-bc57-aa35c15201ab
public void setResult(double[] result) { this.result = result; }
1515bb0f-21d9-43b7-ac1c-fb7e3e847519
public SlidingWindow(NeuralNetwork network) { this.network = network; }
e96e510b-d726-45fd-bd37-d115e06c4132
public int process(BufferedImage img) { int width = (img.getWidth() % size != 0) ? img.getWidth() + (size-(img.getWidth() % size)) : img.getWidth(); int height = (img.getHeight() % size != 0) ? img.getHeight() + (size-(img.getHeight() % size)) : img.getHeight(); BufferedImage resized = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_BINARY); Graphics2D g2d = resized.createGraphics(); g2d.drawImage(img, 0, 0, null); int wt = width / 100; int ht = height / 100; BufferedImage sub = null; int counter = 0; for (int i = 0; i < wt; i++) { for (int j = 0; j < ht; j++) { System.out.println(i + " " + j + "/" + wt + " " + ht); sub = resized.getSubimage(i*size, j*size, size, size); network.setInput(PatternSupplier.getFeatures(sub)); network.activateNetwork(); if (PatternSupplier.decodeOutput(network.getOutput())) { counter++; } } } return counter; }
2de9a542-7b5d-4a2a-b411-0d830d3178e8
public static double[] getFeatures(BufferedImage img) { double[] features = new double[3]; double[] firstAndSec = getFirstAndSecondFeature(img); features[0] = firstAndSec[0]; features[1] = firstAndSec[1]; features[2] = getThirdFeature(img); return features; }
f980bb96-d5f2-4eb4-9814-19149cdfdc90
private static double[] getFirstAndSecondFeature(BufferedImage img) { double[] result = new double[2]; int cntr = 1; ArrayList<Color> rgbs = new ArrayList<Color>(); //img = Scalr.resize(img, 80); int areaCnt = 0; BufferedImageOp op = new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_sRGB), null); BufferedImage color = op.filter(img, null); for (int i = 0; i < color.getHeight(); i++) { for (int j = 0; j < color.getWidth(); j++) { if (color.getRGB(j, i) == Color.BLACK.getRGB()) { rgbs.add(new Color(1000*(cntr++) + cntr*473)); floodFill(j, i, Color.BLACK, rgbs.get(rgbs.size()-1), color); areaCnt++; } } } result[0] = scaleFirstFeature(areaCnt); Map<Color, Integer> map = new HashMap<Color, Integer>(); int old = 0; for (Color c: rgbs) { map.put(c, 0); } for (int i = 0; i < color.getHeight(); i++) { for (int j = 0; j < color.getWidth(); j++) { for (Color c: rgbs) { if (color.getRGB(j, i) == c.getRGB()) { old = map.get(c); map.put(c, old + 1); break; } } } } int maxVal = 0; for (Map.Entry<Color, Integer> entry : map.entrySet()) { if (entry.getValue() > maxVal) { maxVal = entry.getValue(); } } result[1] = scaleSecondFeature(maxVal, color.getWidth()*color.getHeight()); return result; }
7e745d9d-b9b4-47c9-9437-13187528912c
private static double scaleFirstFeature(double val) { return (20 - val) / 19.0; }
f7bf5038-aa27-4539-bc1a-233b8cd29ba9
private static double scaleSecondFeature(int val, int size) { return (double)val/(double)size; }
12fdf794-f031-4f70-882e-6998453261c2
private static double getThirdFeature(BufferedImage img) { int whiteCnt = 0; for (int i = 0; i < img.getHeight(); i++) for (int j = 0; j < img.getWidth(); j++) if (img.getRGB(j, i) == -1) whiteCnt++; return (double)whiteCnt / ((img.getWidth() * img.getHeight()) - whiteCnt); }
05b85f77-8223-47a9-91cf-5eea342acdfe
private static void floodFill(int x, int y, Color targetColor, Color replacementColor, BufferedImage image) { List<Point> queue = new LinkedList<Point>(); Point w, e; queue.add(new Point(x, y)); do { Point p = queue.remove(queue.size() - 1); if (image.getRGB((int)p.getX(), (int)p.getY()) == targetColor.getRGB()) { w = (Point)p.clone(); e = (Point)p.clone(); while (w.getX() - 1 >= 0) if (image.getRGB((int)w.getX() - 1, (int)w.getY()) == targetColor.getRGB()) { w = new Point((int)w.getX() - 1, (int)w.getY()); } else { break; } while (e.getX() + 1 < image.getWidth()) if (image.getRGB((int)e.getX() + 1, (int)e.getY()) == targetColor.getRGB()) { e = new Point((int)e.getX() + 1, (int)e.getY()); } else { break; } for (int i = (int)w.getX(); i <= e.getX(); i++) image.setRGB(i, (int)w.getY(), replacementColor.getRGB()); for (int i = (int)w.getX(); i <= e.getX(); i++) { if (w.getY() - 1 >= 0) if (image.getRGB(i, (int)w.getY()-1) == targetColor.getRGB()) queue.add(new Point(i, (int)w.getY()-1)); if (w.getY() + 1 < image.getHeight()) if (image.getRGB(i, (int)w.getY()+1) == targetColor.getRGB()) queue.add(new Point(i, (int)w.getY()+1)); } } } while (!queue.isEmpty()); }
806d0ead-24e9-4eba-a020-54d6a156bb60
public static List<Pattern> processLearningSet(List<Pattern> learningSet) { int cnt = 0; for (Pattern patt: learningSet) { System.out.println(cnt++); patt.setInput(getFeatures(patt.getImgInput())); } return learningSet; }
c4ad5df8-6c2a-4aae-9d39-05bfe4f6fdf0
public static boolean decodeOutput(double[] out) { return Math.round(out[0]) == 1; }
eb29f613-c95a-47ab-a0c3-1db224366a97
private static Vector<Color> getKeyColors(Vector<Color> src, int cnt, int threshold) { Vector<Color> groups = new Vector<Color>(); groups.add(src.get(0)); boolean add; for (int i = 0; i < src.size(); i++) { Color c = src.get(i); add = true; for (Color col: groups) { if (getDist(c, col) < threshold) { add = false; break; } } if (add) { groups.add(c); } } while (groups.size() > cnt) { groups = getKeyColors(src, cnt, threshold + (int)(200 * ((groups.size()-cnt) * (groups.size()-cnt) * 0.04))); } while (groups.size() < cnt) { groups = getKeyColors(src, cnt, threshold - (int)(200 * ((groups.size()-cnt) * (groups.size()-cnt) * 0.04))); } return groups; }
cba3e721-1070-4750-853d-db1d95ef6ecc
public static Vector<SOMVector> getKeyColorInputVector(BufferedImage src, int cnt) { Vector<Color> input = getColorsFromImage(src); Vector<Color> resultKeyColors = getKeyColors(input, cnt, KeyColorFinder.startColorThreshold); Vector<SOMVector> inputs = new Vector<SOMVector>(); for (Color c: resultKeyColors) { inputs.addElement(new SOMVector(scale(c.getRed()), scale(c.getGreen()), scale(c.getBlue()))); } return inputs; }
72ca86fd-5541-49ed-8029-968b2d16459a
private static int getDist(Color c1, Color c2) { int summation = 0, temp; temp = c1.getRed() - c2.getRed(); temp *= temp; summation += temp; temp = c1.getGreen() - c2.getGreen(); temp *= temp; summation += temp; temp = c1.getBlue() - c2.getBlue(); temp *= temp; summation += temp; return summation; }
e37aba80-3aee-4d83-9d7d-e5c41e24b66b
private static float scale(int val) { return 1 - ((float)(255-val)/(float)255); }
f4db1c71-794e-4341-82f8-176aed0f4240
public static Vector<Color> getColorsFromImage(BufferedImage img) { Vector<Color> result = new Vector<Color>(); for (int i = 0; i < img.getWidth(); i++) { for (int j = 0; j < img.getHeight(); j++) { result.add(new Color(img.getRGB(i, j))); } } return result; }
fad332b5-2065-4ad2-945d-92a2829361d2
private static BufferedImage useBorderFilter(BufferedImage img) { BufferedImageOp op = new ConvolveOp(new Kernel(3, 3, borderMatrix), ConvolveOp.EDGE_NO_OP, null); return op.filter(img, null); }
2ed9f24b-af42-49a9-a236-d7f0b45e7daf
private static BufferedImage setBlackAndWhite(BufferedImage img) { BufferedImage result = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_BYTE_BINARY); Graphics2D graph = result.createGraphics(); graph.drawImage(img, 0, 0, null); return result; }
91d1237e-3331-4f88-8a9c-bc49df7d243d
private static BufferedImage mergeNearestWhitePoints(BufferedImage img) { Graphics2D g = img.createGraphics(); g.setColor(Color.WHITE); for (int k = 0; k < 20; k++) { for (int i = 0; i < img.getWidth() - 1; i++) { for (int j = 0; j < img.getHeight() - 1; j++) { if (img.getRGB(i, j) == -1) { Vector<Integer> vec = checkNeighbourhood(img, i, j, 2); if (vec.size() == 2) { g.drawLine(i, j, vec.get(0), vec.get(1)); } } } } } return img; }
25813e03-d9e5-4fcf-853c-cc86f42b3ee8
private static Vector<Integer> checkNeighbourhood(BufferedImage img, int x, int y, int r) { Vector<Integer> vect = new Vector<>(); for (int i = x - r; i <= x + r; i++) { for (int j = y - r; j <= y + r; j++) { if (i >= 0 && j >= 0 && i < img.getWidth() && j < img.getHeight()) { if (img.getRGB(i, j) == -1 && !(i == x && j == y)) { vect.addElement(i); vect.addElement(j); return vect; } } } } return vect; }
650d0ab0-04c3-448a-b350-7a5ead53ee5b
public static BufferedImage setBlackAndWhiteNonStrict(BufferedImage img) { for (int i = 0; i < img.getWidth() - 1; i++) { for (int j = 0; j < img.getHeight() - 1; j++) { if (img.getRGB(i, j) != -1 && img.getRGB(i, j) != -16777216) { img.setRGB(i, j, -1); } } } return img; }
0033bb69-daf1-4cc1-85dd-32a268e2cb9c
public static BufferedImage processImage(BufferedImage img, Vector<SOMVector> inputs) { return mergeNearestWhitePoints(setBlackAndWhite(setBlackAndWhiteNonStrict(useBorderFilter(removeBackground( medianFilter(img), inputs))))); }
f6868aca-50a7-4c4d-b1f0-1d5c830e43f1
public static BufferedImage removeBackground(BufferedImage img, Vector<SOMVector> inputs) { Map<SOMVector, Integer> map = new HashMap<SOMVector, Integer>(); Vector<SOMVector> bckCols = new Vector<SOMVector>(); int old = 0; for (SOMVector s : inputs) { map.put(s, 0); } for (int i = 0; i < img.getWidth() - 1; i++) { for (int j = 0; j < img.getHeight() - 1; j++) { SOMVector v = new SOMVector(new Color(img.getRGB(i, j))); for (SOMVector vec : inputs) { if (v.euclideanDist(vec) < 0.02) { old = map.get(vec); map.put(vec, old + 1); break; } } } } int prc10 = (int) (0.1 * img.getWidth() * img.getHeight()); for (Map.Entry<SOMVector, Integer> entry : map.entrySet()) { if (entry.getValue() >= prc10) { bckCols.addElement(entry.getKey()); } } for (int i = 0; i < img.getWidth() - 1; i++) { for (int j = 0; j < img.getHeight() - 1; j++) { for (SOMVector vec : bckCols) { SOMVector v = new SOMVector(new Color(img.getRGB(i, j))); if (v.euclideanDist(vec) < 0.02) { img.setRGB(i, j, -16777216); } } } } return img; }
87a1d2b1-71e6-4672-b428-235c19d91b48
public static BufferedImage medianFilter(BufferedImage img) { MedianFilter fil = new MedianFilter(3); return fil.filter(img); }
b19ca625-6c71-4673-a04e-70cb67f9d1d4
public static BufferedImage sharpen(BufferedImage img) { float data[] = { -1.0f, -1.0f, -1.0f, -1.0f, 9.0f, -1.0f, -1.0f, -1.0f, -1.0f }; Kernel kernel = new Kernel(3, 3, data); ConvolveOp convolve = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null); return convolve.filter(img, null); }
60360b13-0a14-495b-abf1-990ba153ac6e
public static List<Pattern> createLearningSet(int cnt, Vector<SOMVector> inputs) { List<Pattern> result = new ArrayList<Pattern>(); Pattern temp = null; BufferedImage[] images = null; try { images = loadImages(); } catch (IOException e) {} for (int i = 0; i < cnt; i++) { System.out.println(i); temp = new Pattern(processImage(images[i], inputs), new double[] {outputs[i]}); result.add(temp); } Collections.shuffle(result); return result; }
22a7a74a-ac65-4357-a47b-2b82e02e2bda
private static BufferedImage[] loadImages() throws IOException { BufferedImage[] result = new BufferedImage[22]; for (int i = 0; i < result.length; i++) { result[i] = ImageIO.read(new File("tmp/segmented/" + (i+1) + ".png")); } System.out.println("loaded " + result.length); return result; }
cf6690c2-3564-43d5-8745-6c4fbdd7a9ca
public MedianFilter(int s) { if ((s % 2 == 0) || (s < 3)) { // check if the filter size is an odd number > = 3 s = 3; } size = s; }
4b8eabe9-4d93-4715-bb21-4ea12f106f95
public int getFilterSize() { return size; }
e3556fb0-2057-47fc-a367-51f03ca95062
public int median(int[] a) { int temp; int asize = a.length; // sort the array in increasing order for (int i = 0; i < asize; i++) for (int j = i + 1; j < asize; j++) if (a[i] > a[j]) { temp = a[i]; a[i] = a[j]; a[j] = temp; } // if it's odd if (asize % 2 == 1) return a[asize / 2]; else return ((a[asize / 2] + a[asize / 2 - 1]) / 2); }
ec0631b1-710c-4c4a-b0df-b0929567479d
public int[] getArray(BufferedImage image, int x, int y) { int[] n; // store the pixel values of position(x, y) and its neighbors int h = image.getHeight(); int w = image.getWidth(); int xmin, xmax, ymin, ymax; // the limits of the part of the image on // which the filter operate on xmin = x - size / 2; xmax = x + size / 2; ymin = y - size / 2; ymax = y + size / 2; // special edge cases if (xmin < 0) xmin = 0; if (xmax > (w - 1)) xmax = w - 1; if (ymin < 0) ymin = 0; if (ymax > (h - 1)) ymax = h - 1; // the actual number of pixels to be considered int nsize = (xmax - xmin + 1) * (ymax - ymin + 1); n = new int[nsize]; int k = 0; for (int i = xmin; i <= xmax; i++) for (int j = ymin; j <= ymax; j++) { n[k] = image.getRGB(i, j); // get pixel value k++; } return n; }
f515c699-53a0-4ad3-9a46-b493c2c0ffb9
public BufferedImage filter(BufferedImage srcImage) { BufferedImage dstImage = new BufferedImage(srcImage.getWidth(), srcImage.getHeight(), BufferedImage.TYPE_INT_RGB); int height = srcImage.getHeight(); int width = srcImage.getWidth(); int[] a; // the array that gets the pixel value at (x, y) and its // neightbors for (int k = 0; k < height; k++) { for (int j = 0; j < width; j++) { a = getArray(srcImage, j, k); int[] red, green, blue; red = new int[a.length]; green = new int[a.length]; blue = new int[a.length]; // get the red,green,blue value from the pixel for (int i = 0; i < a.length; i++) { Color c = new Color(a[i]); red[i] = c.getRed(); green[i] = c.getGreen(); blue[i] = c.getBlue(); } // find the median for each color int R = median(red); int G = median(green); int B = median(blue); // set the new pixel value using the median just found Color c = new Color(R, G, B); int spixel = c.getRGB(); dstImage.setRGB(j, k, spixel); } } return dstImage; }
fb863630-598d-4b42-ac48-f37f670c0cf8
public ViewManager() { super("Neural Network Car Recognizer"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(x-90, y); setLocationRelativeTo(null); setResizable(false); menu = new JMenuBar(); m1 = new JMenu("File"); p1 = new JMenuItem("Load Image", KeyEvent.VK_L); p2 = new JMenuItem("Load NN Settings", KeyEvent.VK_K); p3 = new JMenuItem("Save NN Settings", KeyEvent.VK_S); m1.add(p1); m1.add(p2); m1.add(p3); menu.add(m1); m2 = new JMenu("Train"); p4 = new JMenuItem("Train BP"); m2.add(p4); menu.add(m2); setJMenuBar(menu); fc = new JFileChooser(); FileFilter fil = new FileFilter() { @Override public String getDescription() { return "Image files .jpg .png"; } @Override public boolean accept(File file) { if (file.isDirectory()) { return true; } else { String path = file.getAbsolutePath().toLowerCase(); if (path.endsWith(".jpg") || path.endsWith(".png")) { return true; } } return false; } }; fc.setFileFilter(fil); showPanel = new ShowPanel(); maxCols = new JTextField(8); maxCols.setText("Max Cols"); keyColors = new JButton("Key Colors"); somTrain = new JButton("Train Som"); processSom = new JButton("Process Som"); restProcess = new JButton("Rest Of Processes"); confirm = new JButton("Run BP"); JPanel bottom = new JPanel(); bottom.setLayout(new FlowLayout(FlowLayout.LEFT, 15, 5)); bottom.setBackground(Color.WHITE); bottom.add(maxCols); bottom.add(keyColors); bottom.add(somTrain); bottom.add(processSom); bottom.add(restProcess); bottom.add(confirm); mPanel = new MainPanel(); mPanel.setBorder(bord); getContentPane().add(BorderLayout.CENTER, mPanel); getContentPane().add(BorderLayout.SOUTH, bottom); setVisible(true); }
827858c6-4f41-4a93-9903-8bbde286822d
@Override public String getDescription() { return "Image files .jpg .png"; }
c23a7d9f-c637-491a-ac37-dd2f18715d83
@Override public boolean accept(File file) { if (file.isDirectory()) { return true; } else { String path = file.getAbsolutePath().toLowerCase(); if (path.endsWith(".jpg") || path.endsWith(".png")) { return true; } } return false; }
f5967bcd-4f9e-4dfa-a12c-ac9321641fa8
public void addListener(ActionListener aListener) { keyColors.setActionCommand("keyColors"); keyColors.addActionListener(aListener); somTrain.setActionCommand("trainSom"); somTrain.addActionListener(aListener); processSom.setActionCommand("processSom"); processSom.addActionListener(aListener); restProcess.setActionCommand("restProcess"); restProcess.addActionListener(aListener); confirm.setActionCommand("runBP"); confirm.addActionListener(aListener); p1.setActionCommand("load"); p1.addActionListener(aListener); p2.setActionCommand("ldSettings"); p2.addActionListener(aListener); p3.setActionCommand("saveSett"); p3.addActionListener(aListener); p4.setActionCommand("trainBP"); p4.addActionListener(aListener); }
4bdbe48b-8ca9-419a-be3d-647b0e88690d
public int getKeyColorsSize() { return Integer.parseInt(maxCols.getText()); }
86a7331a-b899-4cec-9084-56df8e1e1673
public void loadImage(BufferedImage img) { mPanel.changeScene(img); }
57e6c4fb-e868-4696-9173-939a725f8c66
public int showFileChooser(Component parent) { return fc.showOpenDialog(parent); }
7436e58c-ca50-4594-9b1c-5e7af3686c37
public String getLoadPath() { return fc.getSelectedFile().getPath(); }
9be133fa-e5e8-4f4c-be81-f75903ca30e2
public void cleanFileChooser() { fc.setSelectedFile(new File("")); }
b4f7c30e-046e-4b62-bb05-45c97a2fd328
public void showColorsInPanel(Vector<SOMVector> vec) { showPanel.render(vec); showPanel.setVisible(true); }
8cf92541-7236-47cf-9a3a-c137f6139fef
public void changeScene(BufferedImage scene) { this.scene = scene; //this.graph = this.scene.createGraphics(); repaint(); }
a4930bc4-07d7-47b6-9c48-43c8b084558c
@Override public void paintComponent(Graphics g) { super.paintComponent(g); g.drawImage(scene, 0, 0, null); }
736896e4-41cb-42df-8546-0d386b9705cb
@Override public void actionPerformed(ActionEvent event) { if (event.getActionCommand().equals("keyColors")) { somInput = KeyColorFinder.getKeyColorInputVector(processedImg, win.getKeyColorsSize()); win.showColorsInPanel(somInput); } else if (event.getActionCommand().equals("trainSom")) { lattice = new SOMLattice(SomLatticeSize, SomLatticeSize); trainer.setTraining(lattice, somInput); trainer.start(); } else if (event.getActionCommand().equals("processSom")) { processedImg = lattice.use(processedImg, somInput); win.loadImage(processedImg); } else if (event.getActionCommand().equals("restProcess")) { processedImg = ImagePreparer.processImage(processedImg, somInput); win.loadImage(processedImg); } else if (event.getActionCommand().equals("runBP")) { int lb = slWindow.process(processedImg); JOptionPane.showMessageDialog(win, "Success", "Recognized " + lb + " cars" , JOptionPane.INFORMATION_MESSAGE); } else if (event.getActionCommand().equals("load")) { returnVal = win.showFileChooser(win); switch (returnVal) { case JFileChooser.APPROVE_OPTION: try { processedImg = ImageIO.read(new File(win.getLoadPath())); win.loadImage(processedImg); } catch (IOException e) { e.printStackTrace(); } break; } win.cleanFileChooser(); } else if (event.getActionCommand().equals("ldSettings")) { ObjectInputStream in; try { in = new ObjectInputStream(new FileInputStream("baza0.dat")); network = (NeuralNetwork) in.readObject(); in.close(); } catch (IOException e) { } catch (ClassNotFoundException e) {} JOptionPane.showMessageDialog(win, "Success loading", "Load", JOptionPane.INFORMATION_MESSAGE); } else if (event.getActionCommand().equals("saveSett")) { ObjectOutputStream stream; try { stream = new ObjectOutputStream(new FileOutputStream("baza" + (ctn++) + ".dat")); stream.writeObject(network); stream.flush(); stream.close(); } catch (IOException e) {} JOptionPane.showMessageDialog(win, "Success saveing", "Save", JOptionPane.INFORMATION_MESSAGE); } else if (event.getActionCommand().equals("trainBP")) { bp.setPatterns(PatternSupplier.processLearningSet(ImagePreparer.createLearningSet(22, somInput))); //bp.setPatterns(null); // int maxRuns = 50000; // double minErrorCondition = 1.0; // Long time = System.currentTimeMillis(); // bp.run(maxRuns, minErrorCondition); // System.out.println("Time: " + (System.currentTimeMillis() - time)); double res = bp.tenFoldCrossValidation(); System.out.println("RESULT: " + res); } }
c23fc065-8e97-42a3-bd4e-94c7c55e4042
public Controller(ViewManager win) { this.win = win; this.win.addListener(this); this.trainer = new SOMTrainer(); this.network = new NeuralNetwork(3, 2, 1); this.bp = new BackPropagation(network); this.slWindow = new SlidingWindow(network); }
2ae06628-f749-4bd4-abb1-360206718ad5
public static void main(String[] args) { new Controller(new ViewManager()); }
2178d6dd-9a9b-4f6c-911e-50de39c1e02e
public NeuralNetwork(int input, int hidden, int output) { this.neuronCnt = input + hidden + output; for (int i = 0; i < input; i++) { // input layer Neuron neuron = new Neuron(); inputLayer.add(neuron); } Neuron bias = new Neuron(); for (int i = 0; i < hidden; i++) { // hidden layer Neuron neuron = new Neuron(); neuron.addInConnectionsS(inputLayer); neuron.addBiasConnection(bias); hiddenLayer.add(neuron); } for (int i = 0; i < output; i++) { // output layer Neuron neuron = new Neuron(); neuron.addInConnectionsS(hiddenLayer); neuron.addBiasConnection(bias); outputLayer.add(neuron); } for (Neuron neuron : hiddenLayer) { // initialize random weights ArrayList<Connection> connections = neuron.getAllInConnections(); for (Connection conn : connections) { double newWeight = getRandom(); conn.setWeight(newWeight); } } for (Neuron neuron : outputLayer) { ArrayList<Connection> connections = neuron.getAllInConnections(); for (Connection conn : connections) { double newWeight = getRandom(); conn.setWeight(newWeight); } } Neuron.counter = 0; // reset id counters }
1f15e9cd-0c6c-45a4-b171-7c039eb0ae82
private double getRandom() { // rand agile double range = 4/Math.sqrt(neuronCnt); return (Math.random() * range - (2/Math.sqrt(neuronCnt))); }
87ada625-c237-4ae6-a8a5-b5b2554e0f13
public void setInput(double inputs[]) { for (int i = 0; i < inputLayer.size(); i++) { inputLayer.get(i).setOutput(inputs[i]); } }
2825cfd0-e4ed-4b61-879f-909e8c7ce156
public double[] getOutput() { double[] outputs = new double[outputLayer.size()]; for (int i = 0; i < outputLayer.size(); i++) outputs[i] = outputLayer.get(i).getOutput(); return outputs; }
f9600295-4e17-4cd5-8690-8238431cd528
public void activateNetwork() { for (Neuron n : hiddenLayer) n.calculateOutput(); for (Neuron n : outputLayer) n.calculateOutput(); }
3f600654-1479-4a53-9375-c4c8663605a5
public void applyBackpropagation(double expectedOutput[]) { int i = 0; for (Neuron n : outputLayer) { // update weights for output layer ArrayList<Connection> connections = n.getAllInConnections(); for (Connection con : connections) { double ak = n.getOutput(); double ai = con.getFromNeuron().getOutput(); double desiredOutput = expectedOutput[i]; double partialDerivative = -ak * (1 - ak) * ai * (desiredOutput - ak); double deltaWeight = -learningRate * partialDerivative; double newWeight = con.getWeight() + deltaWeight; con.setDeltaWeight(deltaWeight); con.setWeight(newWeight + momentum * con.getPrevDeltaWeight()); } i++; } for (Neuron n : hiddenLayer) { // update weights for hidden layer ArrayList<Connection> connections = n.getAllInConnections(); for (Connection con : connections) { double aj = n.getOutput(); double ai = con.getFromNeuron().getOutput(); double sumKoutputs = 0; int j = 0; for (Neuron out_neu : outputLayer) { double wjk = out_neu.getConnection(n.id).getWeight(); double desiredOutput = expectedOutput[j]; double ak = out_neu.getOutput(); j++; sumKoutputs = sumKoutputs + (-(desiredOutput - ak) * ak * (1 - ak) * wjk); } double partialDerivative = aj * (1 - aj) * ai * sumKoutputs; double deltaWeight = -learningRate * partialDerivative; double newWeight = con.getWeight() + deltaWeight; con.setDeltaWeight(deltaWeight); con.setWeight(newWeight + momentum * con.getPrevDeltaWeight()); } } }
0a2bcc38-0fde-4593-8066-7d706fe30cb1
public void changeLearningRate(double learningRate) { this.learningRate = learningRate; }
faee9f61-47f3-4c2f-854e-abf9802de25c
public void changeMomentum(double momentum) { this.momentum = momentum; }
f219505a-ab5b-44bf-8af6-daaf5c9f9980
public Neuron(){ id = counter; counter++; }
20117792-8839-4b47-b552-4163d082534d
public void calculateOutput(){ double s = 0; for(Connection con : Inconnections){ Neuron leftNeuron = con.getFromNeuron(); double weight = con.getWeight(); double a = leftNeuron.getOutput(); //output from previous layer s = s + (weight*a); } s = s + (biasConnection.getWeight()*bias); output = sigmoid(s); }
310497c7-40a8-4761-a83d-74c57df4ccec
private double sigmoid(double x) { return 1.0 / (1.0 + (Math.exp(-x))); }
c1c745c3-5271-4f89-80d9-541af0fb6d44
public void addInConnectionsS(ArrayList<Neuron> inNeurons){ for(Neuron n: inNeurons){ Connection con = new Connection(n,this); Inconnections.add(con); connectionLookup.put(n.id, con); } }
d0c92899-8648-43ad-85d4-c14112eb07c0
public Connection getConnection(int neuronIndex){ return connectionLookup.get(neuronIndex); }
f7815716-c033-4bd9-93d3-0cdcaf1a2a30
public void addInConnection(Connection con){ Inconnections.add(con); }
c5251ddb-0ab5-4577-977b-b27eb7faaa7c
public void addBiasConnection(Neuron n){ Connection con = new Connection(n,this); biasConnection = con; Inconnections.add(con); }
6b3358ea-d586-4a30-ab00-de98707dd596
public ArrayList<Connection> getAllInConnections(){ return Inconnections; }
b429f300-5a2a-4286-a52a-fc1783deb2d5
public double getBias() { return bias; }
e1d38060-d83a-4479-a0cd-b3d0cbb29fbf
public double getOutput() { return output; }
fc41956f-f529-4986-b2f9-aeb9f5f90900
public void setOutput(double o){ output = o; }
dbc5ec33-c60e-4d7a-836c-d90c3f252754
public BackPropagation(NeuralNetwork network) { this.network = network; this.patterns = new ArrayList<Pattern>(); }
c9069b50-dd6e-4c07-8e63-31deba576b1e
public void addPattern(double[] in, double[] out) { this.patterns.add(new Pattern(in, out)); }
b403ba0c-93b8-40c3-aeec-d76d8da4f385
public void addPattern(Pattern pattern) { this.patterns.add(pattern); }
d39e70dd-79dd-4d2b-91e9-6454e41a5229
public void setPatterns(List<Pattern> patterns) { this.patterns = patterns; // have to clone /*try { ObjectInputStream in = new ObjectInputStream(new FileInputStream(new File("patterny.bin"))); this.patterns = (List<Pattern>)in.readObject(); in.close(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException ex) { ex.printStackTrace(); }*/ /*try { ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(new File("patterny.bin"))); os.writeObject(patterns); os.close(); } catch (IOException e) { e.printStackTrace(); }*/ }
851c3b94-a256-4296-aa3e-9c7306154299
public void run(int maxSteps, double minError) { double[] output; int i; double error = 1; //for (i = 0; i < maxSteps && error > minError; i++) { // Train neural network until minError reached or maxSteps exceeded for (i = 0; error > minError; i++) { error = 0; for (int j = 0; j < patterns.size(); j++) { network.setInput(patterns.get(j).getInput()); network.activateNetwork(); output = network.getOutput(); patterns.get(j).setResult(output); // double oError = 0; for (int k = 0; k < patterns.get(j).getOutput().length; k++) { double err = Math.pow(output[k] - patterns.get(j).getOutput()[k], 2); error += err; } network.applyBackpropagation(patterns.get(j).getOutput()); } error = 1.0/2.0 * error; Collections.shuffle(patterns); // added recently } System.out.println("Sum of squared errors = " + error + " %"); System.out.println("##### EPOCH " + i+"\n"); if (i == maxSteps) { System.out.println("!Error training try again"); } }