[DL4J] CSV

[목차]

(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

1. 참고 사이트

Data Load 관련하여서는 종합적으로 잘 정리된 사이트가 없어 이런저런 사이트나 소스코드를 참조

http://deeplearning4j.org/canova

http://deeplearning4j.org/image-data-pipeline.html

https://github.com/deeplearning4j/dl4j-0.4-examples/blob/master/src/main/java/org/deeplearning4j/examples/misc/csv/CSVExample.java

https://github.com/deeplearning4j/Canova/blob/master/canova-api/src/main/java/org/canova/api/records/reader/impl/CSVRecordReader.java

https://github.com/deeplearning4j/deeplearning4j/blob/3e5c6a942864ced574c7715ae548d5e3cb22982c/deeplearning4j-core/src/main/java/org/deeplearning4j/datasets/canova/RecordReaderDataSetIterator.java

https://github.com/deeplearning4j/Canova/tree/master/canova-api/src/main/java/org/canova/api/records/reader/impl

https://github.com/deeplearning4j/Canova/blob/master/canova-nd4j/canova-nd4j-image/src/main/java/org/canova/image/recordreader/ImageRecordReader.java

http://javadox.com/org.nd4j/canova-api/0.0.0.12/org/canova/api/records/reader/class-use/RecordReader.html

https://github.com/deeplearning4j/Canova

http://idosi.com/javadoc/DL4J/index.html?org/nd4j/jdbc/mysql/class-use/MysqlLoaderTest.html

2. Canova 개요

Canova 는 아래와 같은 특징을 갖는다.

– text, CSV, Image, Video, Sound 등을 DL4J 에서 사용하는 데이터 포맷 타입으로 변환하는 기능을 수행한다.

– 신경망 분석에 적합한 ARFF, SVMLight 등 포맷으로 변경한다

– Command Line으로도 실행할 수 있다.

– 특이한 데이터를 위하여 Custom 으로 Input Format 을 만들 수 있다.

Spark ,Hadoop, JDBC 연동 및 text, CSV, Image, Video, Sound 데이터 로딩 등 다양한 데이터 연동 방법이 있는데

각각의 케이스가 사용법이 달라서 따로 정리가 필요하다고 보여진다.

3. CSV Example

csv 파일을 신경망 분석에 적합한 포맷으로 변경하는 부분 예제

public class CSVExample {

private static Logger log = LoggerFactory.getLogger(CSVExample.class);

public static void main(String[] args) throws Exception {

//First: get the dataset using the record reader. CSVRecordReader handles loading/parsing
int numLinesToSkip = 0;
String delimiter = “,”;

/* 1. 데이터 Reader 정의

numLinesToSkip : 0으로 지정 보통 CSV 파일의 첫라인은 해더 명 등이 들어 있어서 SKIP

delimiter : 구분자 지정 여기서는 “,” */
RecordReader recordReader = new CSVRecordReader(numLinesToSkip,delimiter);
recordReader.initialize(new FileSplit(new ClassPathResource(“iris.txt”).getFile()));

//Second: the RecordReaderDataSetIterator handles conversion to DataSet objects, ready for use in neural network

/* 2. Data Set 변환

CSV 파일이라면, CSVRecordReader 와 RecordReaderDataSetIterator 별도의 개발 없이 두개 클레스를 활용하여

뉴런에 적합한 형태의 데이터로 충분히 변환 가능하다.

labelIndex : 몇개의 컬럼 데이터로 이루어져 있는지

numClasses : 가이드하고자 하는 구분자가 몇가지 종류인지

BatchSize : 몇개의 데이터를 로딩할 것인지 (Row 수)

*/

int labelIndex = 4; //5 values in each row of the iris.txt CSV: 4 input features followed by an integer label (class) index. Labels are the 5th value (index 4) in each row
int numClasses = 3; //3 classes (types of iris flowers) in the iris data set. Classes have integer values 0, 1 or 2
int batchSize = 150; //Iris data set: 150 examples total. We are loading all of them into one DataSet (not recommended for large data sets)
DataSetIterator iterator = new RecordReaderDataSetIterator(recordReader,batchSize,labelIndex,numClasses);

DataSet next = iterator.next();

final int numInputs = 4;
int outputNum = 3;
int iterations = 1000;
long seed = 6;

log.info("Build model....");
MultiLayerConfiguration conf = new NeuralNetConfiguration.Builder()
.seed(seed)
.iterations(iterations)
.learningRate(0.1)
.regularization(true).l2(1e-4)
.list(3)
.layer(0, new DenseLayer.Builder().nIn(numInputs).nOut(3)
.activation("tanh")
.weightInit(WeightInit.XAVIER)
.build())
.layer(1, new DenseLayer.Builder().nIn(3).nOut(3)
.activation("tanh")
.weightInit(WeightInit.XAVIER)
.build())
.layer(2, new OutputLayer.Builder(LossFunctions.LossFunction.NEGATIVELOGLIKELIHOOD)
.weightInit(WeightInit.XAVIER)
.activation("softmax")
.nIn(3).nOut(outputNum).build())
.backprop(true).pretrain(false)
.build();

//run the model
MultiLayerNetwork model = new MultiLayerNetwork(conf);
model.init();
model.setListeners(new ScoreIterationListener(100));

 

/* 3. Data 훈련

DataSet 은 정규화, Shuffle 및 훈련용 데이터와 검증용 데이터를 분리하는 등 Util 성 기능도 제공하며

위에서 정의한 뉴런에 model.fit (Data) 와 같은 형태로 사용하여 모델을 훈련 시킬 수 있다.

*/

next.normalizeZeroMeanZeroUnitVariance();
next.shuffle();
split test and train
SplitTestAndTrain testAndTrain = next.splitTestAndTrain(0.65); //Use 65% of data for training

DataSet trainingData = testAndTrain.getTrain();
model.fit(trainingData);

 

/* 4. 모델 평가

테스트 데이터 Set 으로 모델 예측 결과와 원래 알고 있는 결과를 비교하여 모델의 정확도를 평가한다.

*/

//evaluate the model on the test set
Evaluation eval = new Evaluation(3);
DataSet test = testAndTrain.getTest();
INDArray output = model.output(test.getFeatureMatrix());
eval.eval(test.getLabels(), output);
log.info(eval.stats());
}

}

 

3 thoughts on “[DL4J] CSV

  1. You’ve got an excellent blog here! would you like to make some invitation posts on my site?

  2. Really nice post, I definitely love this site, keep on it.

  3. Your place is valueble for me. Thanks!

Leave a Reply to marvel contest of champions hack tool Cancel reply

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