How to deal with data type of lists/numpy array in Python

Python中,一个list可以包含不同类型的object。例如:

1
2
3
4
a = [0, 10, -1.]
type(a[0]) : <class 'int'>
type(a[1]) : <class 'int'>
type(a[2]) : <class 'float'>

但是需要注意的是,当我们试图将list通过np.array(), np.zeros_like(), etc.转换为numpy array的时候,如果list中只包含int,则转换得到的numpy arraydtype将也是int64。如果list中包含至少一个float,则得到的numpy arraydtype将是float64

For example:

1
2
3
4
5
6
a = [0, 10, -1]
type(a[0]) : <class 'int'>
type(a[1]) : <class 'int'>
type(a[2]) : <class 'int'>

np.array(a).dtype : int64
1
2
3
4
5
6
a = [0, 10, -1.]
type(a[0]) : <class 'int'>
type(a[1]) : <class 'int'>
type(a[2]) : <class 'float'>

np.array(a).dtype : float64

实例

我是通过一下这段代码发现的这个问题:

1
2
3
4
5
6
7
8
9
10
11
12
13
def sigmoid(x):
    positive = x >= 0
    negative = x < 0
    xx = 1 / (1 + np.exp(- x[positive]))
    x[positive] = 1 / (1 + np.exp(- x[positive]))
    z = np.exp(x[negative])
    x[negative] = z / (z + 1)
    return x

def s1(x):
    return 1 / (1 + np.exp(- x))
def s2(x):
    return np.exp(x) / (np.exp(x) + 1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
a = [0, 10, -1]
b = sigmoid(np.array(a))
c = np.zeros_like(a)
d = np.zeros_like(a)

print(b.dtype)
print(c.dtype)
print(d.dtype)

for i, el in enumerate(a):
    c[i] = s1(el)
    d[i] = s2(el)
    
print("b =", b)
print("c =", c)
print("d =", d)
print("b - c", b - c)
print("b - d", b - d)


int64
int64
int64
b = [0 0 0]
c = [0 0 0]
d = [0 0 0]
b - c [0 0 0]
b - d [0 0 0]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
a = [0, 10, -1.]
b = sigmoid(np.array(a))
c = np.zeros_like(a)
d = np.zeros_like(a)

print(b.dtype)
print(c.dtype)
print(d.dtype)

for i, el in enumerate(a):
    c[i] = s1(el)
    d[i] = s2(el)
    
print("b =", b)
print("c =", c)
print("d =", d)
print("b - c", b - c)
print("b - d", b - d)


float64
float64
float64
b = [0.5        0.9999546  0.26894142]
c = [0.5        0.9999546  0.26894142]
d = [0.5        0.9999546  0.26894142]
b - c [0. 0. 0.]
b - d [0. 0. 0.]