Python代码中经常会遇到 -1 这个数字,它主要有两个作用:
- 倒数第一
- 自动推断
倒数第一
在list, tuple, array中表示倒数第一个
简单举例
a01 = [3, 2]
print("a01[:-1]:", a01[:-1]) # output: 3
print("a01[0:-1]:", a01[0:-1]) # output: 3
复杂举例
大原则:左闭(inclusive)右开(exclusive)原则
【重要】这个原则在整个Python代码中都适用。
以NumPy.random.randint这个函数举例说明。
np.random.randint
randint(low, high=None, size=None, dtype=‘l’)
Return random integers from low
(inclusive) to high
(exclusive).
返回值:随机整数矩阵,范围:[low
, high
) 。
Return random integers from the “discrete uniform” distribution of
the specified dtype in the “half-open” interval [low
, high
).
返回指定数据类型的随机整数矩阵,其满足 “离散均匀”分布,其所在区间为半开区间[low
, high
)
If high
is None (the default), then results are from [0, low
).
如果high没有指定,则返回值范围是[0,low
).
Parameters
----------
size : int or tuple of ints, optional
整数或者整数元组,这个参数是可选的,不是必须提供的。
Output shape. 返回值的形状。
If the given shape is, e.g., (m, n, k)
, then m * n * k
samples are drawn.
如果 size
被指定为(m, n, k)
,则返回值是这种形状m * n * k
的矩阵。
Default is None, in which case a single value is returned.
默认值为None,此时返回一个整数。
Returns
-------
out : int or ndarray of ints
size
-shaped array of random integers from the appropriate
distribution, or a single such random int if size
not provided.
输出:如果size
没有指定,则返回一个整数;
如果提供size
,则返回 由size
指定形状的整数矩阵,其满足一种合适的分布 – “离散均匀”分布。
举例说明
np.random.randint(2, size=10)
array([1, 0, 0, 0, 1, 1, 0, 0, 1, 0])
【笔者说明】
low=2,没有指定high,说明随机整数是在[0,2)之间分布,即只可能是0或1
size=10,说明是一维矩阵,里面有10个数。
结果自然是ndarray类型的[1, 0, 0, 0, 1, 1, 0, 0, 1, 0]
更多例子可以参考docs.scipy.org的官方说明
链接:https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.random.randint.html
实际代码
这段函数是从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) # a1.shape = (3,1)
print("a1:\n", a1)
print("*" * 6, "my_to_categorical", "*" * 6)
oneHotA1 = my_to_categorical(a1, num_classes=10)
print("oneHotA1:\n", oneHotA1)
输出结果
a1:
[[3]
[1]
[4]]
****** my_to_categorical ******
oneHotA1:
[[ 0. 0. 0. 1. 0. 0. 0. 0. 0. 0.]
[ 0. 1. 0. 0. 0. 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 1. 0. 0. 0. 0. 0.]]
自动推断
通过已知参数推断出的一个形状参数时,可以将其设置为-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)
输出结果参考代码右边的 # 注释。