NumPy vectorize () or dot () display error

In the code below, y1 and y2 should be equal, but this is not the case. Could there be an error in vectorize () or dot ()?

import numpy as np
interval = np.arange(0, 30, 0.1)
y1 = [- 1.57 * max(0, x - 10) - 0.72 * max(0, 15 - x)
      - 1.09 * max(0, 20 - x) for x in interval]

def fun(x, pivot, truth):
    if truth: return max(0, x - pivot)
    else:     return max(0, pivot - x)

pivots = [10, 15, 20]
truths = [ 1,  0,  0]
coeffs = [-1.57, -0.72, -1.09]
y2 = [np.dot(np.vectorize(fun)(x, pivots, truths), coeffs) for x in interval]

import matplotlib.pyplot as plt
plt.plot(interval, y1, interval, y2)
plt.show()

Graphs y1 and y2: Graphical results

+2
source share
2 answers

To apply the correct casting rules, numpy uses your function occasionally with timezone values ​​(numpy.int64) to check what data it gives if it gives an integer 0, because what returned maxthen assumes the result of the calculation must be an integer and round off the rest of the results, but if you change the function to always return a float, using 0.0in max:

def fun(x, pivot, truth):
    if truth: return max(0.0, x - pivot)
    else:     return max(0.0, pivot - x)

, numpy, float .

+4

, , vectorize .

return dtype, - . , 0, vectorize . , , , return dtype.

- vectorize . . , .

np.vectorize(fun, otypes=[float])

.

===========

:

vfun = np.vectorize(fun, otypes=[float])
X = vfun(interval[:,None], pivots, truths)
print(X.shape)     # (300,3)
y2 = np.dot(X, coeffs)
print(y2.shape)    # (300,)

vectorize's.

, fun , x, , vectorize.

fun np.maximum, x:

def fun(x, pivot, truth):
    if truth: return np.maximum(0, x - pivot)
    else:     return np.maximum(0, pivot - x)

x 3 pivots truths, interval:

X = np.stack([fun(interval, p, t) for p, t in zip(pivots, truths)], axis=-1)
y2 = np.dot(X, coeffs)

3 ''

Xlist = [fun(interval, p, t)*c for p, t, c in zip(pivots, truths, coeffs)]
y2 = np.sum(Xlist, axis=0)

np.dot(..., coeffs) . , .

+5

Source: https://habr.com/ru/post/1664173/


All Articles