1

I need to make plot for: this function or this

I made plots before with this code:

x = np.arange(-5, 5, 0.1)
y1 = np.tanh(x)
plt.plot(x,y1)

but how to make something like this?

 if(x <= 0):
    y4 = 0
else:
    y4 = x

gives valueerror:The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

roweduncan
  • 11
  • 2

2 Answers2

0

Try this iterate over the array and apply the function:

def relu(x):
    if(x <= 0):
        y4 = 0
    else:
        y4 = x
    return y4

x = np.arange(-5, 5, 0.1)
array_for = np.array([relu(element) for element in x])
plt.plot(array_for)

enter image description here

alternatively, you can use numpy.vectorize or another solution posted here.

StandardIO
  • 156
  • 1
  • 7
0

You see the error because the result of x<0 gives multiple boolean (one per each element of x). Hence the if cannot resolve whether the condition is true or false.

In your case, you can simply compute y and then change its values based on conditions on x:

x=np.arange(-2, 2, 1)
y=np.exp(x)-1

# check content of y
print(y)


y[x<0]=0

# check updated content of y
print(y)
Luca Clissa
  • 810
  • 2
  • 7
  • 27