On the 14th day of the November Gwen Challenge, check out the details of the event: the last Gwen Challenge 2021

There is a problem

When I looked at the code today, there was a piece of code that randomly initialized NP.random. Normal. It looked troublesome when I looked at the data, so I changed it to Np.arange. And then you start reporting errors.


First look at the source code looks like this:

features = np.random.normal(size=(4.1))
np.random.shuffle(features)
poly_features = np.power(features, np.arange(5).reshape(1, -1))
for i in range(5):
    poly_features[:, i] /= math.gamma(i + 1) 
Copy the code
  • Display random initialization feature, two-dimensional, shape is 4*1
  • Shuffle them randomly
  • Poly_feature is the storage feature from 0 to 4
  • Then divide each term of poly_feature by its factorial,gamma(n)It’s n minus 1 factorial which is n minus 1 factorial.

Then I started to change the code.

features = np.arange(4).reshape(-1.1)
poly_features = np.power(features, np.arange(5).reshape(1, -1))

for i in range(5):
    poly_features[:, i] /= math.gamma(i + 1)  
Copy the code
  • First of all,arangeMake sure you add it at the endReshape (1, 1)Is converted to x*1 dimension, x adjusts automatically according to the number of elements.
    • An error is reported that the broadcast mechanism is not available.

    Operands could not be broadcast together with shapes (4,) (1,5)

    • Because the default is one-dimensional 4 elements, not two-dimensional 4*1, the broadcast mechanism cannot be used.
  • Because I examine the code by looking at the data, I randomly shuffle the elementsnp.random.shuffle(features)The sentence was crossed out.
  • After thatfor i in range():This loop will generate an error
    • The reason is that the data types do not match. The array generated by Arrange is not a floating point number, which is required.

    TypeError: ufunc ‘true_divide’ output (typecode ‘d’) could not be coerced to provided output parameter (typecode ‘i’) according to the casting rule ”same_kind”

    It looks like we need a double but we’re generating an int.

Numpy data type conversion

How do YOU convert it to float.

  1. poly_features = poly_features.astype(np.float32)

    Add the above sentence after poly_features.

  2. Or you can just cast it by multiplying it,

    • Such asPoly_features = np.power(Features, NP.Arange (5).0 (1, -1))*1.0
    • butCan’tChange backPoly_features [:, I] = Poly_features [:, I]*1.0/math.gamma(I + 1), change the later does not take effect. I’m not going to get an error, but I’m going to multiply by int.