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)
相关推荐
SamChan9014 分钟前
对比 4 种主流 PDF 文档解析方案:PyMuPDF vs pdfplumber vs Apache PDFBox vs 大模型 OCR
python·ai·pdf·ocr·apache·机器翻译
安_8 小时前
如何构建和使用向量索引?HNSW 和 IVF 有什么区别?
python·ai
counting money9 小时前
Java IO流详解:从InputStream到文件操作实战
java·开发语言·python
坚持学习前端日记10 小时前
Python SQLAlchemy ORM 从0到1精通实战手册(基础到复杂高阶)
数据库·python·oracle
北斗落凡尘10 小时前
LangGraph 入门实战(11)--输出模式
后端·python·langchain
雪碧聊技术11 小时前
安装Python(保姆级教程)
python·版本更新·python下载
++==11 小时前
JSON和Python的 四种核心容器
python·json
张龙68713 小时前
uv 全面指南:比 pip 快 100 倍的 Python 包管理器,从安装到团队落地
后端·python
@HNUSTer14 小时前
Python数据可视化科技图表绘制系列教程(八)
python·数据可视化·科技论文·专业制图·科研图表
专注仿真14 小时前
问答大模型技术方案算法实现-熵权法融合算法 + 交叉编码器重排算法
人工智能·python·算法·语言模型·问答大模型关键算法·熵权融合算法·交叉编码器重排算法