Note——torch.size() & umr_maximum() array.max() & itertools.product()

torch.size

Note——torch.size() & umr_maximum() array.max() & itertools.product()_第1张图片

Problem

TypeError: ‘torch.Size’ object is not callable

Reason Analysis

torch.Size函数不可调用
因为torch只可以.size()

shape

Solution

将y.shape()替换为y.size()

y.shape

y+=torch.normal(0,0.01,y.size())

2

return umr_maximum(a, axis, None, out, keepdims, initial, where)

Problem

ValueError: zero-size array to reduction operation maximum which has no identity

Reason Analysis

数组“array”的“size”为0,所以无法进行计算;

umr_maximum()函数
array.max()函数

Solution

出错:
array.max()
具体原因:
“array”的size为0了,于是元素的个数为0,因而就不存在最大值

在调试时,可以先对数据的规范性进行验证
验证数组array的size是否为0

assert array.size != 0

itertools.product()

Formula

itertools.product(*iterables, repeat=1)

product 用于求多个可迭代对象的笛卡尔积(Cartesian Product)
它跟嵌套的 for 循环等价.

即:
product(A, B)

((x,y) for x in A for y in B)
的效果是一样的

本质essence:
先合成一个元组再组成list

Param

  • iterables 是可迭代对象
  • repeat指定 iterables 重复几次
    即:
    product(A,repeat=3)等价于product(A,A,A)

For example

import itertools
A = [1, 2, 3]
B = ['A', 'B', 'C']
for i in itertools.product(A,B):
    print(i)

Note——torch.size() & umr_maximum() array.max() & itertools.product()_第2张图片

直接使用

分别生成元组,然后合成一个list

import itertools
a = itertools.product(['A','B','C'], ['D','E'])
b = list(a)   
#按照顺序生成笛卡尔积,repeat默认为1
print(a,'\n','\n')
print(b)

set param

repeat=3

a = list(itertools.product(['A','B','C'], ['D','E'], repeat=3))
print(a) 

此list长度为216

在不设置 repeat 参数的时候,默认是1,生成的list长度时6 —— permutation and combination
3*2=6种

当设置 repeat=3 时,也就是说将 repeat=1(默认)的结果再重复2次后(也就是最后一共有3套一样的第一层结果)
从第一个结果(6种结果)取出一个元素的可能有6种
同理,从第二第三个重复结果中取出一个元素的可能各有6种,
So, 666=216种。

others

  1. 如果要从列表中随机取出几个不重复的元素的话
    (原来的列表本身元素不重复),可用 random.sample 方法。
import random
random.seed(1)   
#设置随机数种子,可用来检测相同的随机数得到的结果是否一致

n = 2
aa = random.sample(a, n)   
#随机从列表中取出n个元素
print(aa)
  1. 生成随机的坐标,另一种生成随机坐标的方法
random_list = list(itertools.product(range(1,4), range(1,2)))
# itertools.product([1,2,3],[1])
print(random_list)

n = 2
aa = random.sample(random_list, n)   
#随机取出列表中的n个元素
print(aa)

你可能感兴趣的:(#,PyTorch,Python,python)