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)
相关推荐
@forever@1 小时前
【JAVA】LinkedList与链表
java·python·链表
程序员爱钓鱼2 小时前
Python编程实战:面向对象与进阶语法——类型注解与代码规范(PEP 8)
后端·python·ipython
程序员爱钓鱼2 小时前
Python实战:用高德地图API批量获取地址所属街道并写回Excel
后端·python·ipython
reasonsummer3 小时前
【教学类-97-06】20251105“葡萄”橡皮泥黏贴(小班主题《苹果与橘子》)
python
卖个几把萌3 小时前
【16】Selenium+Python 接管已打开谷歌浏览器
python·selenium·测试工具
像风一样的男人@4 小时前
python --两个文件夹文件名比对(yolo 图和label标注比对检查)
windows·python·yolo
lllsure4 小时前
【Python】Dict(字典)
开发语言·python
tianyuanwo5 小时前
Rust开发完全指南:从入门到与Python高效融合
开发语言·python·rust
如何原谅奋力过但无声5 小时前
TensorFlow 2.x常用函数总结(持续更新)
人工智能·python·tensorflow
程序员-小李5 小时前
基于 Python + OpenCV 的人脸识别系统开发实战
开发语言·python·opencv