[DL4J] Complex Network

[목차]

(0) 환경 설정 : DL4J 개발 환경 설정 및 예제 설명 (完)

(1) Data Iterator : 사용하고자 하는 데이터를 DL4J 에서 사용가능한 형태로 변환하는 작업 개발 필요

• Canova: The Rosetta Stone of Vectorization

• Spark

• Hadoop

• JDBC

Text ,CSV (完)

• Image (完)

• Sound

• Video

(2) Net : 사용할 신경망의 형태가 어떤 것이 있는지 이해하고 선택, 활용 할 수 있어야 함
• Restricted Boltzmann machines (完)
• Convolutional nets (完)
• Recursive autoencoders (完)
• Recurrent nets: Long Short-Term Memory (LSTM) (including bi-directional LSTMs)
• Deep-belief networks
• Denoising and Stacked Denoising autoencoders
• Deep autoencoders

(3) Activation : Weight + Bias 결과 다음 적용할 함수 결정 (예 : SigMoid : Chap1 에서 설명한 것)

• ReLU (完)
• Leaky ReLU
• Tanh
• Sigmoid
• Hard Tanh
• Softmax
• Identity
• ELU: Exponential Linear Units
• Softsign
• Softplus

(4) Loss&Objective Functions : 일부 데이터를 누락함으로써 더 Robust 한 모델을 만들 수 있다.
• Reconstruction entropy
• Squared loss
• Mean squared error
• Multi-class cross entropy for classification
• Negative log likelihood
• RMSE_XENT

(5) Hyperparameters : 모든 Layer 에 공통적으로 적용되는 파라메터로 숙지 필요

• Dropout (random ommission of feature detectors to prevent overfitting)
• Sparsity (force activations of sparse/rare inputs)
• Adagrad (feature-specific learning-rate optimization)
• L1 and L2 regularization (weight decay)
• Weight transforms (useful for deep autoencoders)
• Probability distribution manipulation for initial weight generation
• Gradient normalization and clipping

(6) Event Listener & Result Anal : 분석 중간 발생하는 이벤트를 받아서 처리 및 결과에 대한 검증 및 비지니스 연동 등

(7) 모델 저장 및 로딩

• 매번 모든 데이터를 로딩하여 학습 시키는 것이 아니라, 모델 자체를 저장하고, 새로 발생하는 데이터만 학습 시킴으로써,

모델의 즉각적인 학습효과와 대량 데이터 처리에 따른 Performacne 문제를 해결 할수 있을 것으로 보임

http://deeplearning4j.org/modelpersistence

(8) Grapth 의 종류

MultiLayerNetwork

ComputationGraph

1. DL4J 제공 Grapth 의 종류와 차이

(1) MultiLayerNetwork : 지금까지의 예제에서 일반적으로 사용했던 형태로 어느정도 정해진 틀을 손쉽게 사용할 수 있도록 제공하는 형태

(2) ComputationGraph : 더 자유롭게 변형이 가능한 형태로 저금 더 정의가 복잡하지만 (1) 에서 제공하는 기능 전체 수용가능하며, 추가적인 변형 가능

– Multiple network input arrays : 복수의 Input 을 받는 node 설계

– Multiple network outputs (including mixed classification/regression architectures) : Out put 값을 그 다음 Layer 의 복수의 Node 로 전송

– Layers connected to other layers using a directed acyclic graph connection structure (instead of just a stack of layers) : 별도의 직접 연결 경로 지정

※ 위 3가지 Case 를 구현하는 방법은 아래서 다루도록 함

2. ComputationGrapth 의 기본 구성

(1) LayerVertex

MultiLayerNetwork를 사용할때 layer(1, DenseLayer.Builder() …. 와 같이 정의했던 것과 같은 맥락으로 LayerVertex 에서는 아래와 같은 두 가지 방법으로 정의

.addLayer(레이어명,레이어 클래스,인풋값 Label)

.addLayer(레이어명,레이어 클래스,전처리 클래스, 인풋값 Label)

EX) .addLayer(“L1”, new GravesLSTM.Builder().nIn(5).nOut(5).build(), “input”)

※ 결국 MultiLayerNetwork 와 동일한 형태이지만, Layer 와 Layer 간의 관계를 좀더 자유롭게 정의할 수 있게 되겠다~

아래 예제는 .addLayer(“L2”,new RnnOutputLayer.Builder().nIn(5+5).nOut(5).build(), “input”, “L1”) 와 같이 정의하여

OUTPUT 을 두군데로 연결하도록 하는 것이다.

K-052

[예제]

ComputationGraphConfiguration conf = new NeuralNetConfiguration.Builder()
.learningRate(0.01)
.graphBuilder()
.addInputs("input") //can use any label for this
.addLayer("L1", new GravesLSTM.Builder().nIn(5).nOut(5).build(), "input")
.addLayer("L2",new RnnOutputLayer.Builder().nIn(5+5).nOut(5).build(), "input", "L1")
.setOutputs("L2")//We need to specify the network outputs and their order
.build();

ComputationGraph net = new ComputationGraph(conf);
net.init();

 

(2) InputVertex

MultiLayerNetwork에서는 INDArrays 에 정의된 형태 그대로 신경망의 데이터로 사용한다

반면에 ComputationGraph 에서는 원하는 데이터 항목명 및 순서를 정의할 수 있다

.addInputs(String…) 형태로 사용 INDArrays 에서 사용하는 Label 명을 넣으면 됨

(3) ElementWiseVertex

MultiLayerNetwork에서는 불가능 했던 행위들로 한개 이상의 Activation 을 받아서 누락시키거나, 더하거나 하는 행위를 하는 Vertex

인풋에 사용되는 Activation들의 사이즈는 모두 같아야 하며, 인풋과 아웃풋의 사이즈도 같아야 한다.

[예제]

 public void testBasicIrisWithElementWiseNode(){

ElementWiseVertex.Op[] ops = new ElementWiseVertex.Op[]{ElementWiseVertex.Op.Add, ElementWiseVertex.Op.Subtract};

for( ElementWiseVertex.Op op : ops ) {

Nd4j.getRandom().setSeed(12345);
ComputationGraphConfiguration conf = new NeuralNetConfiguration.Builder()
.seed(12345)
.optimizationAlgo(OptimizationAlgorithm.STOCHASTIC_GRADIENT_DESCENT)
.weightInit(WeightInit.DISTRIBUTION).dist(new NormalDistribution(0, 1))
.updater(Updater.NONE).learningRate(1.0)
.graphBuilder()
.addInputs("input")
.addLayer("l1", new DenseLayer.Builder().nIn(4).nOut(5).activation("tanh").build(), "input")
.addLayer("l2", new DenseLayer.Builder().nIn(4).nOut(5).activation("sigmoid").build(), "input")
.addVertex("elementwise", new ElementWiseVertex(op), "l1", "l2")
.addLayer("outputLayer", new OutputLayer.Builder().lossFunction(LossFunctions.LossFunction.MCXENT)
.activation("softmax").nIn(5).nOut(3).build(), "elementwise")
.setOutputs("outputLayer")
.pretrain(false).backprop(true)
.build();

ComputationGraph graph = new ComputationGraph(conf);
graph.init();

int numParams = (4 * 5 + 5) + (4 * 5 + 5) + (5 * 3 + 3);
assertEquals(numParams, graph.numParams());

Nd4j.getRandom().setSeed(12345);
int nParams = graph.numParams();
INDArray newParams = Nd4j.rand(1, nParams);
graph.setParams(newParams);

DataSet ds = new IrisDataSetIterator(150, 150).next();
INDArray min = ds.getFeatureMatrix().min(0);
INDArray max = ds.getFeatureMatrix().max(0);
ds.getFeatureMatrix().subiRowVector(min).diviRowVector(max.sub(min));
INDArray input = ds.getFeatureMatrix();
INDArray labels = ds.getLabels();

if (PRINT_RESULTS) {
System.out.println("testBasicIrisWithElementWiseVertex(op=" + op + ")");
for (int j = 0; j < graph.getNumLayers(); j++)
System.out.println("Layer " + j + " # params: " + graph.getLayer(j).numParams());
}

boolean gradOK = GradientCheckUtil.checkGradients(graph, DEFAULT_EPS, DEFAULT_MAX_REL_ERROR,
PRINT_RESULTS, RETURN_ON_FIRST_FAILURE, new INDArray[]{input}, new INDArray[]{labels});

String msg = "testBasicIrisWithElementWiseVertex(op=" + op + ")";
assertTrue(msg, gradOK);
}
}

 

(4) MergeVertex

MultiLayerNetwork에서는 불가능 했던 행위들로 복수개의 Activation 을 Merging 하는 행위를 수행한다.

예를 들어 두개의 Activation 이 각각 IN(3) , OUT(5) 라고 하면 MergeVertex 는 IN(10) , OUT(3) 이 된다.

K-051

[예제]

ComputationGraphConfiguration conf = new NeuralNetConfiguration.Builder()
.learningRate(0.01)
.graphBuilder()
.addInputs("input1", "input2")
.addLayer("L1", new DenseLayer.Builder().nIn(3).nOut(4).build(), "input1")
.addLayer("L2", new DenseLayer.Builder().nIn(3).nOut(4).build(), "input2")
.addVertex("merge", new MergeVertex(), "L1", "L2")
.addLayer("out", new OutputLayer.Builder().nIn(4+4).nOut(3).build(), "merge")
.setOutputs("out")
.build();

 

(5) SubsetVertex

MultiLayerNetwork에서는 불가능 했던 행위들로 다른 Layer 의 일부를 추출하여 별도의 Layer 로 만들 수 있다.

.addVertex("subset1", new SubsetVertex(0,4), "layer1")

 

(6) Multi-Task Learning

MultiLayerNetwork에서와 같이 최종적인 Output Layer 에서는 복수개의 결과를 갖을 수 있다. 그 예제는 아래와 같다.

K-053

[예제]

ComputationGraphConfiguration conf = new NeuralNetConfiguration.Builder()
.learningRate(0.01)
.graphBuilder()
.addInputs("input")
.addLayer("L1", new DenseLayer.Builder().nIn(3).nOut(4).build(), "input")
.addLayer("out1", new OutputLayer.Builder()
.lossFunction(LossFunctions.LossFunction.NEGATIVELOGLIKELIHOOD)
.nIn(4).nOut(3).build(), "L1")
.addLayer("out2", new OutputLayer.Builder()
.lossFunction(LossFunctions.LossFunction.MSE)
.nIn(4).nOut(2).build(), "L1")
.setOutputs("out1","out2")
.build();

 

(7) 데이터의 학습

학습용 데이터 구성시 하나의 Input 과 하나의 Output 값을 갖는 Activation 을 정의하는 것이라면 MultiLayerNetwork에서 사용한

데이터셋을 그대로 사용할 수 있다. 그러나, 복수의 인폿, 아웃풋을 갖는 Activation 을 설계하고자 한다면 별도의 과정이 필요하다.

int numLinesToSkip = 0;
String fileDelimiter = ",";
RecordReader rr = new CSVRecordReader(numLinesToSkip,fileDelimiter);
String csvPath = "/path/to/my/file.csv";
rr.initialize(new FileSplit(new File(csvPath)));

int batchSize = 4;
MultiDataSetIterator iterator = new RecordReaderMultiDataSetIterator.Builder(batchSize)
.addReader("myReader",rr)
.addInput("myReader",0,2) //Input: columns 0 to 2 inclusive
.addOutput("myReader",3,4) //Output: columns 3 to 4 inclusive
.build();

 

5 thoughts on “[DL4J] Complex Network

  1. I was waiting for this type of topic. Thank you very much for the post.

  2. Nice post. I learn something more difficult on distinct
    sites everyday. It will constantly be provoking to
    read content from other writers and practice a little something from their shop.
    I’d favor to use some with the content on my site whether you do’t mind.
    Natually I’ll give you a link in your web blog. Thanks for sharing.

  3. There’s clearly a bundle to know concerning this. I presume you made certain nice points
    in features also.

  4. There are some interesting points in time in this article
    but I do’t understand if I see all of them middle to heart.
    There’s some validity but I ‘ll take hold opinion until I look
    into it further. Good article , thanks and we want more!

    Added to FeedBurner as well.

  5. Hi there! This post could not be written any better!
    Reading through this post reminds me of my previous room mate!
    He consistently kept talking about this. I ‘ll forward this post to him.
    Quite confident he’ll have a great read. Thank you for sharing!

Leave a Reply to lords mobile hack ios Cancel reply

Your email address will not be published. Required fields are marked *