CNTK icon indicating copy to clipboard operation
CNTK copied to clipboard

Regression with CNTKTextFormatReader, NDL, Macros

Open whitmark opened this issue 10 years ago • 9 comments

I am attempting to take another run at a regression analysis using the CNTKTextFormatReader and separate NDL and Macro components to map one set of continuous inputs to a set of continuous outputs. In previous successful classification runs I made classes above and below the threshold value but now I would like to generate a specific regression value.

The features and labels are correctly formatted for the CNTKTextFormatReader and appear to load fine.

|F F1 F2 F3 F4 . . . F24 |L L1  (omitted from dataset)
|F -1.0 0.5216 1.8387 1.7813 . . . 1.2212 |L 7.0
|F 1.0 0.5827 1.2609 0.5088 . . .  1.4712 |L 15.0
|F -1.0 0.6569 0.9688 1.0690 . . . 1.3793 |L 2.0
|F 1.0 0.8834 1.1500 0.7419 . . . 1.6850 |L 3.0

in the NDL I am using one hidden layer with ReLU activation but am getting the same value for all output nodes so unclear if regression is supported, the model is not generalizing or my formulation is incorrect.

19.418846
19.418846
19.418846
19.418846

In the absence of an example, I could use some clarification on how to configure the NDL for a regression analysis and whether ErrorPrediction() is a valid function for this purpose. Once this is worked out, it would be useful to include a regression example in the wiki.

Code, data, and outputs provided at zip below: DLT_DNN02.zip

Thanks!

Config:

# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE file in the project root for full license information.

# currentDirectory=$(SolutionDir)/<path to corresponding data folder> 
RootDir = ".."

ConfigDir = "$RootDir$/Config"
DataDir   = "$RootDir$/Data"
OutputDir = "$RootDir$/Output"
ModelDir  = "$OutputDir$/Models"

# which commands to run
command=Train:Test:Output:dumpNodeInfo

#required...
precision = "float"
modelPath="$OutputDir$/Models/dlt_dnn02.dnn"    # where to write the model to
ndlMacros="$ConfigDir$/Macros.ndl"

# uncomment the following line to write logs to a file 
stderr = "$OutputDir$/dtl_dnn02_out"
traceLevel=1

deviceId=-1                 # CPU < 0
inputDimension=24   # input data dimensions
labelDimension=1        # label dimensions

#######################################
#  TRAINING CONFIG                    #
#######################################
Train=[
    action="train"

    NDLNetworkBuilder=[
        networkDescription = "$ConfigDir$/dlt_dnn02.ndl"
  ]

    SGD = [ 
        epochSize=0                         # =0 means size of the training set
        minibatchSize=100
        learningRatesPerMB=0.1            # learning rates per MB
        momentumPerMB = 0           
        maxEpochs=10
    ]

    # parameter values for the reader
    reader = [
        readerType = "CNTKTextFormatReader"
        file = "Train-DLT-dnn02.txt"
        randomize = "none"
        maxErrors = 100
        traceLevel = 2

        input = [
            features = [
                alias = "F"
                dim = 24
                format = "dense"
            ]       
            labels = [
                alias = "L"
                dim = 1
                format = "dense"
            ]
        ]   
    ]   
]

#######################################
#  TEST CONFIG                        #
#######################################
Test=[

    action="test"

    reader = [
        readerType = "CNTKTextFormatReader"
        file = "Test-DLT-dnn02.txt"
        #skipSequenceIds = "true"               
        randomize = "none"
        maxErrors = 100
        traceLevel = 2

        input = [
            features = [
                alias = "F"
                dim = 24
                format = "dense"
            ]       
            labels = [
                alias = "L"
                dim = 1
                format = "dense"
            ]
        ]   
    ]   
]

NDL:

# macros to include
load = ndlDLTMacros

# the actual NDL that defines the network
run = DNN

ndlDLTMacros = [
    featDim = 24
    labelDim = 1

    features = Input(featDim)
    labels = Input(labelDim)
]

DNN = [

        # Variables
    hiddenDim = 24

        # Layer Operations
    # DNNSigmoidLayer and DNNLayer are defined in Macros.ndl
    h1 = DNNReLULayer(featDim, hiddenDim, features, 1)
    ol = DNNLayer(hiddenDim, labelDim, h1, 1)

    # Criterion
    err = SquareError(labels, ol)

    # Eval
    ep = ErrorPrediction(labels, ol)

    # Special Nodes
    FeatureNodes = (features)
    LabelNodes = (labels)
    CriterionNodes = (err)
    EvalNodes = (ep)
    OutputNodes = (ol)
]

Macros:

DNNSigmoidLayer(inDim, outDim, x, parmScale) = [
        # Parameters
    W = Parameter(outDim, inDim, init="uniform", initValueScale=parmScale) 
    b = Parameter(outDim, 1,     init="uniform", initValueScale=parmScale) 
    # Functions
    t = Times(W, x)
    z = Plus(t, b)
    y = Sigmoid(z)
]

DNNReLULayer(inDim, outDim, x, parmScale) = [
        # Parameters
    W = Parameter(outDim, inDim, init="uniform", initValueScale=parmScale) 
    b = Parameter(outDim, 1,     init="uniform", initValueScale=parmScale) 
    # Functions
    t = Times(W, x)
    z = Plus(t, b)
    y = RectifiedLinear(z)
]

DNNLayer(inDim, outDim, x, parmScale) = [
        # Parameters
    W = Parameter(outDim, inDim, init="uniform", initValueScale=parmScale)
    b = Parameter(outDim, 1,     init="uniform", initValueScale=parmScale)
    # Functions    
    t = Times(W, x)
    z = Plus(t, b)
]

whitmark avatar Apr 19 '16 10:04 whitmark

Yep, I'd love to see an NDL and a SimpleNetworkBuilder regression example. It seems a lot of people are asking for examples but are being ignored. I've tried setting up regression in SNB, but the predictions look strange. I suspect it's still using a softmax output layer, rather than simple regression?

@whitmark I used trainingCriterion = "squareError", evalCriterion = "ErrorPrediction", and a single output layer. Of course I can't definitively say this is correct.

xenmind avatar Apr 20 '16 02:04 xenmind

I think several people have already made it to work with the UCIFastReader? Someone even uploaded an example case when they report an issue earlier?

If you use the most recent master branch. It should just work.

dongyu888 avatar Apr 20 '16 05:04 dongyu888

I do not believe a viable regression example has been posted yet. I had posted Simple Regression NotifyFunctionValuesMBSizeModified Exception #354 and resolved the reader problem but could not get the regression to work as expected, but as I stated before my formulation may be incorrect so a working example would be useful.

I decided to switch from the UCIFastReader to the CNTKTextReader since the former is being deprecated and given the following comments in that post:

@dongyu888 - The UCIFastReader’s randomization code has many limitations I think. You might want to randomly order your training samples offline and then turn randomization off in your readers by specifying

@raaaar - CNTKText is agnostic of the input type (regression/category/label/feature/etc) and will work just fine with this data/config.

Only the UCIFastReader has a labeType = "Regression", CNTKText does not require it for regression data.

I also wanted to use NDL vs SimpleNetworkBuilder so I could see explicitly what was going on under the hood and modify accordingly.

To eliminate potential issues due to the data, I have changed out the train/test data to a public domain dataset from the Cortana Intelligence Gallary (Experiment: Compare Regressors) that uses a Boston housing dataset from tunedit.org that is described here in arff format that can be read with any editor.

The goal is to use the 13 feature variables to predict the mean value of owner-occupied homes in $1000's in the last column of the dataset. I have transformed the dataset with 506 records to accommodate the CNTKTextReader and split it equally between training and test to match what was done in the Azure ML Studio experiment (although not randomly).

|F 0.36894 22 5.86 0 0.431 8.259 8.4 8.9067 7 330 19.1 396.9 3.54 |L 42.8
|F 0.04819 80 3.64 0 0.392 6.108 32 9.2203 1 315 16.4 392.89 6.57 |L 21.9
|F 0.03548 80 3.64 0 0.392 5.876 19.1 9.2203 1 315 16.4 395.18 9.25 |L 20.9
|F 0.01538 90 3.75 0 0.394 7.454 34.2 6.3361 3 244 15.9 386.34 3.11 |L 44

As advised, I have since rebuild the master branch this morning but am still getting the same unexpected output with the same value.

-4487.721680
-4487.721680
-4487.721680
-4487.721680

In the absence of an example, I could use some clarification on how to configure the NDL for a regression analysis and whether ErrorPrediction() is a valid function for this purpose. Once this is worked out, it would be useful to include a regression example in the wiki.

Code, data, and outputs provided at zip below: HOUSING_DNN02.zip

Thanks!

Config:

# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE file in the project root for full license information.

# currentDirectory=$(SolutionDir)/<path to corresponding data folder> 
RootDir = ".."

ConfigDir = "$RootDir$/Config"
DataDir   = "$RootDir$/Data"
OutputDir = "$RootDir$/Output"
ModelDir  = "$OutputDir$/Models"

# which commands to run
command=Train:Test:Output:dumpNodeInfo

#required...
precision = "float"
modelPath="$OutputDir$/Models/housing_dnn02.dnn"    # where to write the model to
ndlMacros="$ConfigDir$/Macros.ndl"

# uncomment the following line to write logs to a file 
stderr = "$OutputDir$/housing_dnn02_out"
traceLevel=1

deviceId=-1                 # CPU < 0
inputDimension=13   # input data dimensions
labelDimension=1        # label dimensions

#######################################
#  TRAINING CONFIG                    #
#######################################
Train=[
    action="train"

    NDLNetworkBuilder=[
        networkDescription = "$ConfigDir$/housing_dnn02.ndl"
  ]

    SGD = [ 
        epochSize=0                         # =0 means size of the training set
        minibatchSize=100
        learningRatesPerMB=0.1            # learning rates per MB
        momentumPerMB = 0           
        maxEpochs=10
    ]

    # parameter values for the reader
    reader = [
        readerType = "CNTKTextFormatReader"
        file = "Train-housing-dnn02.txt"
        randomize = "none"
        maxErrors = 100
        traceLevel = 2

        input = [
            features = [
                alias = "F"
                dim = 13
                format = "dense"
            ]       
            labels = [
                alias = "L"
                dim = 1
                format = "dense"
            ]
        ]   
    ]   
]

#######################################
#  TEST CONFIG                        #
#######################################
Test=[

    action="test"

    reader = [
        readerType = "CNTKTextFormatReader"
        file = "Test-housing-dnn02.txt"
        #skipSequenceIds = "true"               
        randomize = "none"
        maxErrors = 100
        traceLevel = 2

        input = [
            features = [
                alias = "F"
                dim = 13
                format = "dense"
            ]       
            labels = [
                alias = "L"
                dim = 1
                format = "dense"
            ]
        ]   
    ]   
]

NDL:

# macros to include
load = ndlDLTMacros

# the actual NDL that defines the network
run = DNN

ndlDLTMacros = [
    featDim = 13
    labelDim = 1

    features = Input(featDim)
    labels = Input(labelDim)
]

DNN = [

        # Variables
    hiddenDim = 13

        # Layer Operations
    # DNNSigmoidLayer and DNNLayer are defined in Macros.ndl
    h1 = DNNReLULayer(featDim, hiddenDim, features, 1)
    ol = DNNLayer(hiddenDim, labelDim, h1, 1)

    # Criterion
    err = SquareError(labels, ol)

    # Eval
    ep = ErrorPrediction(labels, ol)

    # Special Nodes
    FeatureNodes = (features)
    LabelNodes = (labels)
    CriterionNodes = (err)
    EvalNodes = (ep)
    OutputNodes = (ol)
]

Macros:

DNNSigmoidLayer(inDim, outDim, x, parmScale) = [
        # Parameters
    W = Parameter(outDim, inDim, init="uniform", initValueScale=parmScale) 
    b = Parameter(outDim, 1,     init="uniform", initValueScale=parmScale) 
    # Functions
    t = Times(W, x)
    z = Plus(t, b)
    y = Sigmoid(z)
]

DNNReLULayer(inDim, outDim, x, parmScale) = [
        # Parameters
    W = Parameter(outDim, inDim, init="uniform", initValueScale=parmScale) 
    b = Parameter(outDim, 1,     init="uniform", initValueScale=parmScale) 
    # Functions
    t = Times(W, x)
    z = Plus(t, b)
    y = RectifiedLinear(z)
]

DNNLayer(inDim, outDim, x, parmScale) = [
        # Parameters
    W = Parameter(outDim, inDim, init="uniform", initValueScale=parmScale)
    b = Parameter(outDim, 1,     init="uniform", initValueScale=parmScale)
    # Functions    
    t = Times(W, x)
    z = Plus(t, b)
]

whitmark avatar Apr 20 '16 10:04 whitmark

@dongyu888 Yep I used that code as a base for my regression. Turns out the spurious results were from a bug in my feature generation code, so everything is working as expected. Looking forward to seeing how the NDL regression example develops. Thanks for such beautiful software!

xenmind avatar Apr 20 '16 16:04 xenmind

I believe the example referenced above is from post #97. I have reproduced at the link and config file below that uses the SimpleNetworkBuilder and UCIFastReader. Am I to assume this should also work with NDL and the CNTKTextFormatReader even though there is no explicit "Regression" parameter?

auto-mpg-02

# Parameters can be overwritten on the command line
# for example: cntk configFile=myConfigFile RootDir=../.. 
# For running from Visual Studio add
# currentDirectory=$(SolutionDir)/<path to corresponding data folder> 
RootDir = ".."

ConfigDir = "$RootDir$/Config"
DataDir = "$RootDir$/Data"
OutputDir = "$RootDir$/OutputUCIFastReaderFix"
ModelDir = "$OutputDir$/Models"

# deviceId=-1 for CPU, >=0 for GPU devices, "auto" chooses the best GPU, or CPU if no usable GPU is available
deviceId = auto

command = SimpleWithOne_Demo_Train:SimpleWithOne_Demo_Test:SimpleWithOne_Demo_Write:SimpleWithOne_Demo_Dumpnode
#command = SimpleWithOne_Demo_Cv
#command = SimpleWithOne_Demo_Write

precision = "float"
traceLevel = 0
modelPath = "$ModelDir$/simple-with-one.dnn"
#outputNodeNames = ScaledLogLikelihood
#outputNodeNames = SquareError

stdErr = "$OutputDir$/Logs/"

#######################################
#  TRAINING CONFIG                    #
#######################################

SimpleWithOne_Demo_Train = [
    action = "train"

    # Notation xxx:yyy*n:zzz is equivalent to xxx, then yyy repeated n times, then zzz
    # Example: 10:20*3:5 is equivalent to 10:20:20:20:5
    SimpleNetworkBuilder = [
        # 2 input, 2 50-element hidden, 2 output
        layerSizes = 1:2
        trainingCriterion = "squareError"
        evalCriterion = "ErrorPrediction"
        layerTypes = "Sigmoid"
#        layerTypes = "RectifiedLinear"
        initValueScale = 1.0
        applyMeanVarNorm = true
        uniformInit = true
#        needPrior = true
    ]

    SGD = [
        # epochSize = 0 means epochSize is the size of the training set 
        epochSize = 0 
        minibatchSize = 398 
#        learningRatesPerMB = 0.5:0.2*20:0.1
        learningRatesPerMB = 0.2:0.1*20:0.01
        momentumPerMB = 0.9
        dropoutRate = 0.0
        maxEpochs = 1000
    ]

    # Parameter values for the reader
    reader = [
        readerType = "UCIFastReader"
        file = "$DataDir$/data-mpg-mpg-weight.csv"
        miniBatchMode = "partial"
        randomize = "auto"
        verbosity = 0  

        features = [
            dim = 1        # two-dimensional input data
            start = 2      # Start with first element on line
        ]

        labels = [
            start = 0      # Skip two elements
            dim = 2        # One label dimension
            labelDim = 2
            labelMappingFile = "$DataDir$/label-mapping.txt"
            labelType = "regression"
        ]
    ]
]

########################################
#  TEST RESULTS                        #
#  (computes prediction error and      #
#   perplexity on a test set and       #
#   writes the output to the console.) #
########################################

SimpleWithOne_Demo_Test = [
    action = "test"

    # Parameter values for the reader
    reader = [
        readerType = "UCIFastReader"
        file = "$DataDir$/data-mpg-mpg-weight.csv"
        miniBatchMode = "partial"
        randomize = "auto"
        verbosity = 0  

        features = [
            dim = 1        # two-dimensional input data
            start = 2      # Start with first element on line
        ]

        labels = [
            start = 0      # Skip two elements
            dim = 2        # One label dimension
            labelDim = 2
            labelMappingFile = "$DataDir$/label-mapping.txt"
            labelType = "regression"
        ]
    ]
]

whitmark avatar Apr 20 '16 17:04 whitmark

@whitmark re: your model predicting the same unusual value. I've had this before and it was because my model was grossly overfitting. See this: why_the_prediction_or_the_output_of_neural_network_does_not_change_during_the_test_phase.

I'd recommend normalising your data, simplifying your topology, adding regularisation, etc., to minimise the potential for overfitting.

xenmind avatar Apr 21 '16 01:04 xenmind

@xenmind thanks for the advice as its a bit counter intuitive why all the test output would be the same number.

I am having better success with the NDL below where I use Sigmoid (vs ReLU) for activation and PerDimMeanVarNormalization(), but kept in 100 hidden nodes to emulate the Azure ML experiment that uses its "min-max" normalizer to linearly rescale every feature to the [0,1] interval.

Which begs the question, do you have to explicitly de-normalize the output in NDL to get a useful regression value? Does the SimpleNetworkBuilder do this automatically when it sees the labelType=Regression?

I have a similar question re: applying regularization and being able to get back to a useful output value.

NDL:

# macros to include
load = ndlDLTMacros

# the actual NDL that defines the network
run = DNN

ndlDLTMacros = [
    featDim = 13
    labelDim = 1

    # input definitions
    features = Input(featDim)
    labels = Input(labelDim)    

    # input precompute
    featMean = Mean(Features)
    featInvStd = InvStdDev(Features)
    featInput = PerDimMeanVarNormalization(features, featMean, featInvStd) 

]

DNN = [

   # Variables
    hiddenDim = 100

    # Layer Operations
    # DNNSigmoidLayer and DNNLayer are defined in Macros.ndl
    h1 = DNNSigmoidLayer(featDim, hiddenDim, featInput, 1)
    ol = DNNLayer(hiddenDim, labelDim, h1, 1)

    # Training criterion
    sqerr = SquareError(labels, ol)    

    # Evaluation criterion
    ep = ErrorPrediction(labels, ol)    

    # Special Nodes
    FeatureNodes = (features)
    LabelNodes = (labels)
    CriterionNodes = (sqerr)
    EvalNodes = (ep)
    OutputNodes = (ol)
]

Azure ML Studio Housing NN Config: housing nn regression settings

whitmark avatar Apr 21 '16 18:04 whitmark

I believe if you use CNTK to normalize, the prediction step should denormalize the output. If you use your own normalization method you'll have to denormalize the output to get more sensible values. I don't believe regularization will scale or distort your output, they're simply methods to force the learning of simpler models and hopefully reduce overfitting.

xenmind avatar Apr 25 '16 17:04 xenmind

Thank you for your advice.

whitmark avatar Apr 25 '16 21:04 whitmark