Search code examples
pythonmxnet

Why is the output of this code not a two-dimensional form but a one-dimensional form?


from mxnet import nd

n_train, n_test, true_w, true_b = 100, 100, [1.2, -3.4, 5.6], 5

features = nd.random.normal(shape=(n_train + n_test, 1))
poly_features = nd.concat(features, nd.power(features, 2),
                         nd.power(features, 3))
labels = (true_w[0] * poly_features[:, 0] + true_w[1] * poly_features[:, 1] + true_w[2] * poly_features[:, 2] + true_b)
labels += nd.random.normal(scale=0.01, shape=labels.shape)

print(labels[:2])

Because the shapes of features and poly_features are all 2D NDArray, I think the output of this code is the form as below:

NDArray 2x1 @cpu(0),

but the real output form is

NDArray 2 @cpu(0).

Why is the output not a 2D NDArray?


Solution

  • While the features and poly_features are 2D NDArray, when you calculate labels you use only slices of poly_features, which are 1D NDArrays. Here is the code breaked in line:

    labels = true_w[0] * poly_features[:, 0] # true_w[0] is scalar, poly_features[:, 0] is 1D NDAarray
           + true_w[1] * poly_features[:, 1] # true_w[1] is scalar, poly_features[:, 1] is 1D NDAarray
           + true_w[2] * poly_features[:, 2] # true_w[2] is scalar, poly_features[:, 2] is 1D NDAarray
           + true_b # true_b is scalar
    
    

    So, you get 1D array as an answer.