|
| 1 | +package com.example.androidDl4jClassifier; |
| 2 | + |
| 3 | +import android.content.Context; |
| 4 | +import android.graphics.Canvas; |
| 5 | +import android.graphics.Color; |
| 6 | +import android.graphics.Paint; |
| 7 | +import android.os.AsyncTask; |
| 8 | +import android.util.AttributeSet; |
| 9 | +import android.view.View; |
| 10 | + |
| 11 | +import androidx.annotation.Nullable; |
| 12 | + |
| 13 | +import org.deeplearning4j.nn.conf.MultiLayerConfiguration; |
| 14 | +import org.deeplearning4j.nn.conf.NeuralNetConfiguration; |
| 15 | +import org.deeplearning4j.nn.conf.layers.DenseLayer; |
| 16 | +import org.deeplearning4j.nn.conf.layers.OutputLayer; |
| 17 | +import org.deeplearning4j.nn.multilayer.MultiLayerNetwork; |
| 18 | +import org.deeplearning4j.nn.weights.WeightInit; |
| 19 | +import org.deeplearning4j.optimize.listeners.ScoreIterationListener; |
| 20 | +import org.nd4j.evaluation.classification.Evaluation; |
| 21 | +import org.nd4j.linalg.activations.Activation; |
| 22 | +import org.nd4j.linalg.api.buffer.DataType; |
| 23 | +import org.nd4j.linalg.api.ndarray.INDArray; |
| 24 | +import org.nd4j.linalg.dataset.DataSet; |
| 25 | +import org.nd4j.linalg.factory.Nd4j; |
| 26 | +import org.nd4j.linalg.learning.config.Nesterovs; |
| 27 | +import org.nd4j.linalg.lossfunctions.LossFunctions; |
| 28 | + |
| 29 | +import java.io.BufferedReader; |
| 30 | +import java.io.IOException; |
| 31 | +import java.io.InputStreamReader; |
| 32 | +import java.util.ArrayList; |
| 33 | + |
| 34 | +public class ScatterView extends View { |
| 35 | + |
| 36 | + private final Paint redPaint; |
| 37 | + private final Paint greenPaint; |
| 38 | + private final Paint lightGreenPaint; |
| 39 | + private final Paint lightRedPaint; |
| 40 | + private float[][] data; |
| 41 | + private DataSet ds; |
| 42 | + |
| 43 | + private final int nPointsPerAxis = 100; |
| 44 | + private INDArray xyGrid; //x,y grid to calculate the output image. Needs to be calculated once, then re-used. |
| 45 | + private MultiLayerNetwork model; |
| 46 | + |
| 47 | + public ScatterView(Context context, @Nullable AttributeSet attrs) { |
| 48 | + super(context, attrs); |
| 49 | + data = null; |
| 50 | + redPaint = new Paint(); |
| 51 | + redPaint.setColor(Color.RED); |
| 52 | + greenPaint = new Paint(); |
| 53 | + greenPaint.setColor(Color.GREEN); |
| 54 | + |
| 55 | + lightGreenPaint = new Paint(); |
| 56 | + lightGreenPaint.setColor(Color.rgb(225, 255, 225)); |
| 57 | + lightRedPaint = new Paint(); |
| 58 | + lightRedPaint.setColor(Color.rgb(255, 153, 152)); |
| 59 | + |
| 60 | + AsyncTask.execute(() -> { |
| 61 | + try { |
| 62 | + calcGrid(); |
| 63 | + ReadCSV(); |
| 64 | + BuildNN(); |
| 65 | + |
| 66 | + } catch (IOException e) { |
| 67 | + e.printStackTrace(); |
| 68 | + } |
| 69 | + }); |
| 70 | + } |
| 71 | + |
| 72 | + @Override |
| 73 | + public void onDraw(Canvas canvas) { |
| 74 | + int h = this.getHeight(); |
| 75 | + int w = this.getWidth(); |
| 76 | + |
| 77 | + if (null == data) { |
| 78 | + canvas.drawColor(Color.rgb(32, 32, 32)); |
| 79 | + canvas.drawCircle(800, 500, 200, redPaint); |
| 80 | + canvas.drawCircle(325, 900, 300, greenPaint); |
| 81 | + } else { |
| 82 | + |
| 83 | + //draw the nn predictions: |
| 84 | + int halfRectHeight = h / nPointsPerAxis; |
| 85 | + int halfRectWidth = w / nPointsPerAxis; |
| 86 | + INDArray modelOut = model.output(xyGrid); |
| 87 | + |
| 88 | + int nRows = xyGrid.rows(); |
| 89 | + |
| 90 | + for (int i = 0; i< nRows; i++){ |
| 91 | + int x = (int)(xyGrid.getFloat(i, 0) * w); |
| 92 | + int y = (int) (xyGrid.getFloat(i, 1) * h); |
| 93 | + float z = modelOut.getFloat(i, 0); |
| 94 | + Paint p = (z >= 0.5f) ? lightGreenPaint : lightRedPaint; |
| 95 | + canvas.drawRect(x-halfRectWidth, y-halfRectHeight, x+halfRectWidth, y+halfRectHeight, p); |
| 96 | + // } |
| 97 | + } |
| 98 | + |
| 99 | + |
| 100 | + //draw the data set |
| 101 | + for (float[] datum : data) { |
| 102 | + int x = (int) (datum[1] * w); |
| 103 | + int y = (int) (datum[2] * h); |
| 104 | + Paint p = (datum[0] == 0.0f) ? redPaint : greenPaint; |
| 105 | + canvas.drawCircle(x, y, 10, p); |
| 106 | + } |
| 107 | + } |
| 108 | + } |
| 109 | + |
| 110 | + /** |
| 111 | + * this is not the regular way to read a csv file into a data set with DL4j. |
| 112 | + * In this example we have put the data in the assets folder so that the demo works offline. |
| 113 | + */ |
| 114 | + private void ReadCSV() throws IOException { |
| 115 | + InputStreamReader is = new InputStreamReader(MainActivity.getInstance().getApplicationContext().getAssets() |
| 116 | + .open("linear_data_train.csv")); |
| 117 | + |
| 118 | + BufferedReader reader = new BufferedReader(is); |
| 119 | + ArrayList<String> rawSVC = new ArrayList<>(); |
| 120 | + String line; |
| 121 | + while ((line = reader.readLine()) != null) { |
| 122 | + rawSVC.add(line); |
| 123 | + } |
| 124 | + |
| 125 | + float[][] tmpData = new float[rawSVC.size()][3]; |
| 126 | + |
| 127 | + int index = 0; |
| 128 | + for(String l : rawSVC){ |
| 129 | + String[] values = l.split(","); |
| 130 | + for(int col = 0; col< 3L; col++){ |
| 131 | + tmpData[index][col] = Float.parseFloat(values[col]); |
| 132 | + } |
| 133 | + |
| 134 | + index++; |
| 135 | + } |
| 136 | + |
| 137 | + normalizeColumn(1, tmpData); |
| 138 | + normalizeColumn(2, tmpData); |
| 139 | + |
| 140 | + this.data = tmpData; |
| 141 | + INDArray arrData = Nd4j.createFromArray(tmpData); |
| 142 | + INDArray arrFeatures = arrData.getColumns(1, 2); |
| 143 | + INDArray c1 = arrData.getColumns(0); |
| 144 | + INDArray c2 = c1.mul(-1).addi(1.0); |
| 145 | + INDArray labels = Nd4j.hstack(c1, c2); |
| 146 | + ds = new DataSet(arrFeatures, labels); |
| 147 | + } |
| 148 | + |
| 149 | + /** |
| 150 | + * Normalize the data in a given column. Normally one would use datavec. |
| 151 | + * @param c column to normalise. |
| 152 | + * @param tmpData java float array. |
| 153 | + */ |
| 154 | + private void normalizeColumn(int c, float[][] tmpData){ |
| 155 | + int numPoints = tmpData.length; |
| 156 | + float min= tmpData[0][c]; |
| 157 | + float max= tmpData[0][c]; |
| 158 | + for (float[] tmpDatum : tmpData) { |
| 159 | + float x = tmpDatum[c]; |
| 160 | + if (x < min) { |
| 161 | + min = x; |
| 162 | + } |
| 163 | + if (x > max) { |
| 164 | + max = x; |
| 165 | + } |
| 166 | + } |
| 167 | + |
| 168 | + for (int i=0; i<numPoints; i++){ |
| 169 | + float x = tmpData[i][c]; |
| 170 | + tmpData[i][c] = (x - min) / (max - min); |
| 171 | + } |
| 172 | + } |
| 173 | + |
| 174 | + private void BuildNN(){ |
| 175 | + int seed = 123; |
| 176 | + double learningRate = 0.01; |
| 177 | + int numInputs = 2; |
| 178 | + int numOutputs = 2; |
| 179 | + int numHiddenNodes = 20; |
| 180 | + int nEpochs = 200; |
| 181 | + |
| 182 | + MultiLayerConfiguration conf = new NeuralNetConfiguration.Builder() |
| 183 | + .seed(seed) |
| 184 | + .weightInit(WeightInit.XAVIER) |
| 185 | + .updater(new Nesterovs(learningRate, 0.9)) |
| 186 | + .list() |
| 187 | + .layer(new DenseLayer.Builder().nIn(numInputs).nOut(numHiddenNodes) |
| 188 | + .activation(Activation.RELU) |
| 189 | + .build()) |
| 190 | + .layer(new OutputLayer.Builder(LossFunctions.LossFunction.NEGATIVELOGLIKELIHOOD) |
| 191 | + .activation(Activation.SOFTMAX) |
| 192 | + .nIn(numHiddenNodes).nOut(numOutputs).build()) |
| 193 | + .build(); |
| 194 | + |
| 195 | + model = new MultiLayerNetwork(conf); |
| 196 | + model.init(); |
| 197 | + model.setListeners(new ScoreIterationListener(10)); |
| 198 | + |
| 199 | + for(int i = 0; i<nEpochs; i++){ |
| 200 | + model.fit(ds); |
| 201 | + } |
| 202 | + |
| 203 | + Evaluation eval = new Evaluation(numOutputs); |
| 204 | + INDArray features = ds.getFeatures(); |
| 205 | + INDArray labels = ds.getLabels(); |
| 206 | + INDArray predicted = model.output(features,false); |
| 207 | + eval.eval(labels, predicted); |
| 208 | + System.out.println(eval.stats()); |
| 209 | + |
| 210 | + this.invalidate(); |
| 211 | + } |
| 212 | + /** |
| 213 | + * The x,y grid to calculate the NN output. Only needs to be calculated once. |
| 214 | + */ |
| 215 | + private void calcGrid(){ |
| 216 | + // x coordinates of the pixels for the NN. |
| 217 | + INDArray xPixels = Nd4j.linspace(0, 1.0, nPointsPerAxis, DataType.DOUBLE); |
| 218 | + // y coordinates of the pixels for the NN. |
| 219 | + INDArray yPixels = Nd4j.linspace(0, 1.0, nPointsPerAxis, DataType.DOUBLE); |
| 220 | + //create the mesh: |
| 221 | + INDArray [] mesh = Nd4j.meshgrid(xPixels, yPixels); |
| 222 | + xyGrid = Nd4j.vstack(mesh[0].ravel(), mesh[1].ravel()).transpose(); |
| 223 | + } |
| 224 | +} |
0 commit comments