Python-API笔记

clone()、detach()

 

 

torch.nn.CosineSimilarity()

torch.nn.CosineSimilarity(dim=1, eps=1e-08):返回x1和x2之间的余弦相似度,沿dim计算。

复制代码
'''
输入 1:(∗1,D,∗2) 其中 D 位于位置 dim
输入2:(∗1,D,∗2),与x1相同的维数,在维度dim匹配x1大小,并且可以在其他维度上用 x1 广播。
输出:(∗1,∗2)
'''
input1 = torch.randn(100, 128)
input2 = torch.randn(100, 128)
cos = nn.CosineSimilarity(dim=1, eps=1e-6)
output = cos(input1, input2
复制代码

 

 

torch.flip()

flip(input,dim): 第一个参数是输入,第二个参数是输入的第几维度,按照维度对输入进行翻转。

复制代码
import torch
x = torch.arange(16).view(2, 2, 2,2)
print('x=\n',x)
a = torch.flip(x, [2])
print('a=\n',a)
a = torch.flip(x, [3])
print('a=\n',a)
'''
x=
 tensor([[[[ 0,  1],
          [ 2,  3]],
         [[ 4,  5],
          [ 6,  7]]],
        [[[ 8,  9],
          [10, 11]],
         [[12, 13],
          [14, 15]]]])
a=
 tensor([[[[ 2,  3],
          [ 0,  1]],
         [[ 6,  7],
          [ 4,  5]]],
        [[[10, 11],
          [ 8,  9]],
         [[14, 15],
          [12, 13]]]])
a=
 tensor([[[[ 1,  0],
          [ 3,  2]],
         [[ 5,  4],
          [ 7,  6]]],
        [[[ 9,  8],
          [11, 10]],
         [[13, 12],
          [15, 14]]]])
'''
复制代码

 

Python:sklearn数据预处理中fit(),transform()与fit_transform()

Fit(): Method calculates the parameters μ and σ and saves them as internal objects.

求得训练集X的均值、方差、最大值、最小值这些训练集X固有的属性。可以理解为一个训练过程。

Transform(): Method using these calculated parameters apply the transformation to a particular dataset.

在Fit的基础上,进行标准化,降维,归一化等操作(看具体用的是哪个工具,如PCA,StandardScaler等)。Fit_transform(): joins the fit() and transform() method for transformation of dataset.

fit_transform是fit和transform的组合,既包括了训练又包含了转换。

复制代码
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
sc.fit_tranform(X_train)
sc.tranform(X_test)
'''
必须先用fit_transform(trainData),之后再transform(testData),如果直接transform(testData),程序会报错.
如果fit_transfrom(trainData)后,使用fit_transform(testData)而不transform(testData),
虽然也能归一化,但是两个结果不是在同一个“标准”下的,具有明显差异。(一定要避免这种情况)
'''



import pandas as pd
import numpy as np

from sklearn.decomposition import PCA 

#==========================================================================================
X1=pd.DataFrame(np.arange(9).reshape((3,3)),index=['a','b','c'],
              columns=['one','two','three'])  

pca=PCA(n_components=1)

newData1=pca.fit_transform(X1)

pca.fit(X1)
newData2=pca.transform(X1)

"""
newData1和newData2结果一致
"""
#==========================================================================================
a=[[1,2,3],[5,6,7],[4,5,8]]

X2=pd.DataFrame(np.array(a),index=['a','b','c'],
              columns=['one','two','three'])  
pca_new=PCA(n_components=1)
pca_new.transform(X2)
"""
没有fit,直接transform报错:
NotFittedError: This PCA instance is not fitted yet. Call 'fit' with appropriate arguments before using this method.
"""
复制代码

 

torch.stack()

outputs = torch.stack(inputs, dim=?) → Tensor

沿着一个新维度对输入张量序列进行连接。 序列中所有的张量都应该为相同形状。

复制代码
# 假设是时间步T1的输出
T1 = torch.tensor([[1, 2, 3],
                [4, 5, 6],
                [7, 8, 9]])
# 假设是时间步T2的输出
T2 = torch.tensor([[10, 20, 30],
                [40, 50, 60],
                [70, 80, 90]])

print(torch.stack((T1,T2),dim=0).shape)
print(torch.stack((T1,T2),dim=1).shape)
print(torch.stack((T1,T2),dim=2).shape)
print(torch.stack((T1,T2),dim=3).shape)
# outputs:
torch.Size([2, 3, 3])
torch.Size([3, 2, 3])
torch.Size([3, 3, 2])
'选择的dim>len(outputs),所以报错'
IndexError: Dimension out of range (expected to be in range of [-3, 2], but got 3)
复制代码

 

torch.clamp()

torch.clamp(input, min, max, out=None) → Tensor
将输入input张量每个元素的夹紧到区间 [min,max][min,max],并返回结果到一个新张量。
操作定义如下:
          | min, if x_i < min
 y_i = | x_i, if min <= x_i <= max
          | max, if x_i > max

复制代码
a=torch.randint(low=0,high=10,size=(10,1))
print(a)
'''
tensor([[9.],
        [3.],
        [0.],
        [4.],
        [4.],
        [2.],
        [4.],
        [1.],
        [2.],
        [9.]])
'''
a=torch.clamp(a,3,9)
print(a)
'''
tensor([[9.],
        [3.],
        [3.],
        [4.],
        [4.],
        [3.],
        [4.],
        [3.],
        [3.],
        [9.]])
'''
复制代码

 

lambda表达式(匿名函数)

lambda表达式其实就是匿名函数。

# 关键字lambda表示匿名函数,冒号前面的x表示函数参数。
lambda x:x*x
def f(x):
    return x*x

匿名函数有个限制,就是只能有一个表达式,不用写return,返回值就是该表达式的结果。用匿名函数有个好处,因为函数没有名字,不必担心函数名冲突。

# 匿名函数也是一个函数对象,也可以把匿名函数赋值给一个变量,再利用变量来调用。
f = lambda x: x * x
# f = <function <lambda> at 0x101c6ef28>
# f(5) = 25
# 可以把匿名函数作为返回值返回
def build(x, y):
    return lambda: x * x + y * y

 

sort()与sorted()

sort(*,key = None,reverse = False)

list.sort()将list进行排序,返回None。sort有两个参数,key和reverse,都是‘keyword-only argument’,就是必须用arg_name =** 的方式传递了参数,即用key = 或者reverse=传递,当然也可以不传递,有默认值。

key这个参数:

list = [(3,66),(5,3),(1,23)]
# 默认来说
list.sort()
# list=[(1,23),(3,66),(5,3)]
# 如果排序依据是每个元组的第二个元素
list.sort(key = lambda item:item[1])
# list = [(5,3),(1,23),(3,66)]

reserve这个参数:默认是从小大到,即reserve为False的时候,如果reserve为True,排列顺序就是从大到小。

 

sorted(iterable,*,key=None,reverse=False)

sorted函数对任何iterable的对象进行排序,然后将排序结果返回。

sorted函数有三个参数,后两个参数的作用与sort()的两个参数作用相同,这里不与赘述。

random.seed() & np.random.seed()

  np.random.seed()函数用于生成指定随机数。seed()被设置了之后,np,random.random()可以按顺序产生一组固定的数组。如果使用相同的seed()值,则每次生成的随机数都相同;如果不设置这个值,那么每次生成的随机数不同。

复制代码
import random

# 随机数不一样
random.seed()
print('随机数1:',random.random())
random.seed()
print('随机数2:',random.random())

# 随机数一样
random.seed(1)
print('随机数3:',random.random())
random.seed(1)
print('随机数4:',random.random())
random.seed(2)
print('随机数5:',random.random())

'''
随机数1: 0.7643602170615428
随机数2: 0.31630323818329664
随机数3: 0.13436424411240122
随机数4: 0.13436424411240122
随机数5: 0.9560342718892494
'''
复制代码
复制代码
import numpy as np

np.random.seed(1)
L1 = np.random.randn(3, 3)
np.random.seed(1)
L2 = np.random.randn(3, 3)
print(L1)
print(L2)
# 结果
'''
[[ 1.62434536 -0.61175641 -0.52817175]
 [-1.07296862  0.86540763 -2.3015387 ]
 [ 1.74481176 -0.7612069   0.3190391 ]]
 
[[ 1.62434536 -0.61175641 -0.52817175]
 [-1.07296862  0.86540763 -2.3015387 ]
 [ 1.74481176 -0.7612069   0.3190391 ]]
'''
复制代码

 

shuffle -- 数组随机打乱

复制代码
import random
a=[1,2,3,4]
random.shuffle(a)
print(a)
'''
[4,1,3,2]
'''
random.shuffle(a)
print(a)
'''
[4,3,1,2]
'''
复制代码

 

np.arange -- 生成连续数值

千次阅读
import numpy as np
np.arange(0,1,0.1)
'''
array([0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9])
'''

 

写txt文件

Note=open('./coco_name.txt',mode='w')
for i in cat_name:
    Note.write(i+'\n')
Note.close()

 

读入json文件

object_path = './objects.json'
with open(object_path, 'r') as load_object:
    objects = json.load(load_object)

 

初始化map

name_map_num = {}
for name in total_names:
    name_num = {name:0}
    name_map_num.update(name_num)
posted @   fengzlj  阅读(64)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端
点击右上角即可分享
微信分享提示