Python NumPy中 -1 的作用
程序员文章站
2022-05-18 17:50:21
...
倒数第一
【TODO】
在list, tuple, array中表示倒数第一个
简单举例
a01 = [3, 2]
print("a01[:-1]:", a01[:-1]) # output: 3
print("a01[0:-1]:", a01[0:-1]) # output: 3
大原则:左闭(inclusive)右开(exclusive)原则
np.random.randint
randint(low, high=None, size=None, dtype=‘l’)
Return random integers from low
(inclusive) to high
(exclusive).
Return random integers from the “discrete uniform” distribution of
the specified dtype in the “half-open” interval [low
, high
). Ifhigh
is None (the default), then results are from [0, low
).
返回值:[low
, high
)
复杂举例
这段函数是从keras.utils.to_categorical复制过来的,将其改名为my_to_categorical,作用是生成one-hot码。
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# import the necessary packages
import numpy as np
def my_to_categorical(y, num_classes=None, dtype='float32'):
y = np.array(y, dtype='int')
input_shape = y.shape
if input_shape and input_shape[-1] == 1 and len(input_shape) > 1:
input_shape = tuple(input_shape[:-1])
y = y.ravel()
if not num_classes:
num_classes = np.max(y) + 1
n = y.shape[0]
categorical = np.zeros((n, num_classes), dtype=dtype)
categorical[np.arange(n), y] = 1
output_shape = input_shape + (num_classes,)
categorical = np.reshape(categorical, output_shape)
return categorical
a1 = np.random.randint(10, size=(3, 1)) # a1.shape = (3,1)
print(a1.shape)
print(a1)
print("#"*6, "my_to_categorical", "#"*6)
newA1 = my_to_categorical(a1, num_classes=10)
print(newA1)
自动推断
通过已知参数推断出的一个形状参数时,可以将其设置为-1.
【注意】不可以写成a2 = a1.reshape(2, -1, -1)
会报错:“can only specify one unknown dimension”只能指定一个未知维度
# import the necessary packages
import numpy as np
a1 = np.arange(36).reshape(4,9) # a1.shape = (4, 9)
a2 = a1.reshape(2, 3, -1) # 6 = 36 / (2*3)
print("a2.shape:",a2.shape) # a2.shape = (2, 3, 6)
a3 = a1.reshape(2, -1, 6) # 3 = 36 / (2*6)
print("a3.shape:",a3.shape) # a3.shape = (2, 3, 6)
上一篇: 五年从程序员到架构师!这是我见过史上最好的程序员职业规划
下一篇: data.table