PyPI笔记

1 篇文章 0 订阅
1 篇文章 0 订阅

argparse

属性参数说明
argparse.ArgunmentParser()description创建
parser.add_argument()name, type, nargs, help‘- -name’关键字传参

copy

方法简介
copy.deepcopy()修改与原来的数据无关
copy.copy()与原数据同步修改

gym

属性参数说明
gym.spaces.prng
env.unwrapped()
env.spec

logging

属性参数说明
logging.getLogger()
setLevel()
handler()

matplotlib

import matplotlib.pyplot as plt
ax = plt.gca()   # (及该对象的常用方法)
属性参数说明
ax=plt.gca()
ax.set_facecolor()
ax.get_position()
ax.hlines()

plt.savefig

numpy

属性参数说明
np.std()计算(指定维度的)标准差

os

属性参数说明备注
os.environ()有关系统的各种信息os.environ.keys()
isfile()

pickle

python的pickle模块实现了基本的数据序列和反序列化。通过pickle模块的序列化操作我们能够将程序中运行的对象信息保存到文件中去,永久存储;通过pickle模块的反序列化操作,我们能够从文件中创建上一次程序保存的对象。参考这里

属性参数说明
pickle.dump()
pickle.load()

python

属性参数说明
hasattr(object, name)判断对象是否包含对应的属性
try: except AttributeError:
self.__dict __
format()
def function_name(cls, **kwargs)
assertassert函数主要是用来声明某个函数是真的,特别是实用于下列场景:如果非常确定使用的列表中至少含有一个元素,而且你想验证这一点,并且在其非真的时候引发一个错误。当assert()语句失败的时候,就会引发assertError
vars([object])返回对象object的属性和属性值的字典对象,如果没有参数,就打印当前调用位置的属性和属性值
修饰器作用
@staticmethod在不初始化一个对象的前提下,就可以调用其方法

multiprocessing

multiprocessing.Value()
原始锁(非递归锁)对象,类似于 threading.Lock 。一旦一个进程或者线程拿到了锁,后续的任何其他进程或线程的其他请求都会被阻塞直到锁被释放。任何进程或线程都可以释放锁。
multiprocessing.Process()

multiprocessing.cpu_count()

collections

collections模块包含了除list、dict、和tuple之外的容器数据类型,如counter、defaultdict、deque、namedtuple、orderdict

namedtuple

标准的元组使用数值索引来访问其成员。
记住每个索引对应的值是很容易出错的,尤其是在元组有多个元素的情况下。namedtuple为每个成员分配了名字。

import collections

Person = collections.namedtuple('Person', 'name age gender')

print ('Type of Person:', type(Person))

bob = Person(name='Bob', age=30, gender='male')
print ('\nRepresentation:', bob)

jane = Person(name='Jane', age=29, gender='female')
print ('\nField by name:', jane.name)

print ('\nFields by index:')
for p in [ bob, jane ]:
    print ('%s is a %d year old %s' % p)

输出:

Type of Person: <type 'type'>

Representation: Person(name='Bob', age=30, gender='male')

Field by name: Jane

Fields by index:
Bob is a 30 year old male
Jane is a 29 year old female
Transition = namedtuple('Transition', ['state', 'action', 'a_log_prob', 'reward', 'next_state'])
trans = Transition(state, action, action_prob, reward, next_state)
agent.store_transition(trans)

PyTorch

属性参数说明
torch.backends.cudnn.deterministiccuda设置
torch.backends.cudnn.benchmarkcuda设置
torch.manual_seed()为CPU设置随机种子
torch.cuda.manual_seed_all()为所有GPU设置随机种子
torch.nn.utils.clip_grad_norm_()
torch.set_num_threads()
torch.cat()
tensor.detach()
torch.from_numpy(ndarray)ndarray ==> tensor

torch

torch.clamp(input, min, max, *, out=None) → Tensor

>>> a = torch.randn(4)
>>> a
tensor([-1.7120,  0.1734, -0.0478, -0.0922])
>>> torch.clamp(a, min=-0.5, max=0.5)
tensor([-0.5000,  0.1734, -0.0478, -0.0922])

torch.gather()
利用index来索引input特定位置的数值

>>> t = torch.tensor([[1,2],[3,4]])
>>> torch.gather(t, 1, torch.tensor([[0,0],[1,0]]))
tensor([[ 1,  1],
        [ 4,  3]])

torch.unsqueeze(input, dim)

>>> x = torch.tensor([1, 2, 3, 4])
>>> torch.unsqueeze(x, 0)
tensor([[ 1,  2,  3,  4]])
>>> torch.unsqueeze(x, 1)
tensor([[ 1],
        [ 2],
        [ 3],
        [ 4]])

torch.no_grad()

>>> x = torch.tensor([1], requires_grad=True)
>>> with torch.no_grad():
...   y = x * 2
>>> y.requires_grad
False
>>> @torch.no_grad()
... def doubler(x):
...     return x * 2
>>> z = doubler(x)
>>> z.requires_grad
False

torch.nn

torch.nn.Linear(in_features: int, out_features: int, bias: bool = True)

# example
>>> m = nn.Linear(20, 30)
>>> input = torch.randn(128, 20)
>>> output = m(input)
>>> print(output.size())
torch.Size([128, 30])

torch.nn.utils

  • torch.nn.utils.clip_grad_norm_(parameters: Union[torch.Tensor, Iterable[torch.Tensor]], max_norm: float, norm_type: float = 2.0) → torch.Tensor

torch.nn.functional

  • torch.nn.functional.relu(input, inplace=False) → Tensor

Applies the rectified linear unit function element-wise.ReLU.
R e L U ( x ) = m a x ( 0 , x ) ReLU(x) = max(0, x) ReLU(x)=max(0,x)

  • torch.nn.functional.softmax(input, dim=None, _stacklevel=3, dtype=None)
    S o f t m a x ( x i ) = e x p ( x i ) ∑ j e x p ( x j ) Softmax(x_i)=\frac{exp(x_i)}{\textstyle\sum_{j}exp(x_j)} Softmax(xi)=jexp(xj)exp(xi)

torch.Tensor

item()==>number
This only works for tensors with one element.
view()
Returns a new tensor with the same data as the self tensor but of a different shape.
Example

>>> x = torch.randn(4, 4)
>>> x.size()
torch.Size([4, 4])
>>> y = x.view(16)
>>> y.size()
torch.Size([16])
>>> z = x.view(-1, 8)  # the size -1 is inferred from other dimensions
>>> z.size()
torch.Size([2, 8])

>>> a = torch.randn(1, 2, 3, 4)
>>> a.size()
torch.Size([1, 2, 3, 4])
>>> b = a.transpose(1, 2)  # Swaps 2nd and 3rd dimension
>>> b.size()
torch.Size([1, 3, 2, 4])
>>> c = a.view(1, 3, 2, 4)  # Does not change tensor layout in memory
>>> c.size()
torch.Size([1, 3, 2, 4])
>>> torch.equal(b, c)
False

torch.optim

import torch.optim as optim
  • Optimizer.step(closure)
    Performs a single optimization step (parameter update).
  • Optimizer.zero_grad(set_to_none: bool = False)
    Sets the gradients of all optimized torch.Tensor s to zero.

torch.distributions

class torch.distributions.categorical.Categorical(probs=None, logits=None, validate_args=None)

>>> m = Categorical(torch.tensor([ 0.25, 0.25, 0.25, 0.25 ]))
>>> m.sample()  # equal probability of 0, 1, 2, 3
tensor(3)

torch.utils.data

Sampler()
SubsetRandomSampler()

shutil

tensorboardX

import tensorboard
from tensorboardX import SummaryWriter

writer.add_scaler(self, log_dir=None, comment=’’, **kwargs)
log_dir为生成的文件所放的目录,comment为文件名称。默认目录为生成runs文件夹目录。
终端:tensorboard --logdir &{PATH_TO_LOG}
writer.add_graph()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值