Skip to content Skip to sidebar Skip to footer

Typeerror: Only Size-1 Arrays Can Be Converted To Python Scalars Arrives During A Simple Program

When I tried this code, from math import exp import numpy as np w1=2 b1=0.5 b2=0.75 X=[[0, 1, 1, 1], [1, 1, 1, 1]] y=(np.dot(w1,X)-b1) tanh=np.vectorize((1-exp(-2*y))/(1+exp(-2*y

Solution 1:

In [269]: import math                                                           
In [270]: w1=2 
     ...: b1=0.5 
     ...: b2=0.75 
     ...: X=[[0, 1, 1, 1], [1, 1, 1, 1]] 
     ...: y=(np.dot(w1,X)-b1)                                                   
In [271]: X                                                                     
Out[271]: [[0, 1, 1, 1], [1, 1, 1, 1]]
In [273]: y                                                                     
Out[273]: 
array([[-0.5,  1.5,  1.5,  1.5],
       [ 1.5,  1.5,  1.5,  1.5]])

Python evaluates the argument to np.vectorize before it calls vectorize. It should be a function, but what you wrote was an expression.

The error arises in:

In [274]: math.exp(-2*y)                                                        
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent calllast)
<ipython-input-274-02e40bf10b29>in<module>----> 1 math.exp(-2*y)

TypeError: only size-1 arrays can be converted to Python scalars

y is an array; math.exp only works with scalar values. np.exp works with arrays:

In [275]: np.exp(-2*y)                                                          
Out[275]: 
array([[2.71828183, 0.04978707, 0.04978707, 0.04978707],
       [0.04978707, 0.04978707, 0.04978707, 0.04978707]])

With a lambdavectorize works:

In [276]: fn = np.vectorize( lambda z: (1-math.exp(-2*z))/(1+math.exp(-2*z)))   
In [277]: fn(y)                                                                 
Out[277]: 
array([[-0.46211716,  0.90514825,  0.90514825,  0.90514825],
       [ 0.90514825,  0.90514825,  0.90514825,  0.90514825]])

vectorize iterates through y, and passes an element, one at a time, to the lambda as z.

but this is faster:

In [278]: (1-np.exp(-2*y))/(1+np.exp(-2*y))                                     
Out[278]: 
array([[-0.46211716,  0.90514825,  0.90514825,  0.90514825],
       [ 0.90514825,  0.90514825,  0.90514825,  0.90514825]])

The vectorize is essentially a variation on this list comprehension:

In [280]: [ (1-math.exp(-2*z))/(1+math.exp(-2*z)) for z in y.ravel()]           
Out[280]: 
[-0.46211715726000974,
 0.9051482536448665,
 0.9051482536448665,
 0.9051482536448665,
 0.9051482536448665,
 0.9051482536448665,
 0.9051482536448665,
 0.9051482536448665]

Post a Comment for "Typeerror: Only Size-1 Arrays Can Be Converted To Python Scalars Arrives During A Simple Program"