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

torch.size

Problem

TypeError: 'torch.Size' object is not callable

Reason Analysis

torch.Size函数不可调用

因为torch只可以.size()

shape

Solution

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

y.shape

python 复制代码
y+=torch.normal(0,0.01,y.size())

2

python 复制代码
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

python 复制代码
assert array.size != 0

itertools.product()

Formula

python 复制代码
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

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

直接使用

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

python 复制代码
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

python 复制代码
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 方法。
python 复制代码
import random
random.seed(1)   
#设置随机数种子,可用来检测相同的随机数得到的结果是否一致

n = 2
aa = random.sample(a, n)   
#随机从列表中取出n个元素
print(aa)
  1. 生成随机的坐标,另一种生成随机坐标的方法
python 复制代码
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)
相关推荐
chao_7892 小时前
二分查找篇——搜索旋转排序数组【LeetCode】一次二分查找
数据结构·python·算法·leetcode·二分查找
烛阴2 小时前
Python装饰器解除:如何让被装饰的函数重获自由?
前端·python
noravinsc3 小时前
django 一个表中包括id和parentid,如何通过parentid找到全部父爷id
python·django·sqlite
ajassi20003 小时前
开源 python 应用 开发(三)python语法介绍
linux·python·开源·自动化
沉默媛3 小时前
如何安装python以及jupyter notebook
开发语言·python·jupyter
Deng9452013144 小时前
基于Python的旅游数据可视化应用
python·numpy·pandas·旅游·数据可视化技术
2401_878624794 小时前
pytorch 自动微分
人工智能·pytorch·python·机器学习
胖达不服输4 小时前
「日拱一码」021 机器学习——特征工程
人工智能·python·机器学习·特征工程
screenCui6 小时前
macOS运行python程序遇libiomp5.dylib库冲突错误解决方案
开发语言·python·macos
小眼睛羊羊6 小时前
pyinstaller打包paddleocr
python