pytorch基础知识(个人学习记录分享)

一.基础知识

1.1两大法宝函数

pytorch就相当于是package,也就是一个工具箱的作用

下面这两个函数是学习时的一个很好的辅助函数

1.dir()函数:

作用:提供打开操作

2.help()函数;

作用:函数说明书

import torch
# print(torch.cuda.is_available())
print(dir(torch))
print(dir(torch.cuda))
print(dir(torch.cuda.is_available()))
#1.下面的图
#2.['Any', 'BFloat16Storage', 'BFloat16Tensor', 'BoolStorage', 'BoolTensor', 'ByteStorage', 'ByteTensor', 'CUDAGraph', 'CUDAPluggableAllocator', 'CharStorage', 'CharTensor', 'ComplexDoubleStorage', 'ComplexFloatStorage', 'CudaError', 'DeferredCudaCallError', 'Device', 'DoubleStorage', 'DoubleTensor', 'Event', 'ExternalStream', 'FloatStorage', 'FloatTensor', 'HalfStorage', 'HalfTensor', 'IntStorage', 'IntTensor', 'List', 'LongStorage', 'LongTensor', 'Optional', 'OutOfMemoryError', 'ShortStorage', 'ShortTensor', 'Stream', 'StreamContext', 'Tuple', 'Union', '_CudaBase', '_CudaDeviceProperties', '_DeviceGuard', '_HAS_PYNVML', '_LazySeedTracker', '_PYNVML_ERR', '_WrappedTritonKernel', '__all__', '__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', '_check_capability', '_check_cubins', '_cudart', '_device', '_device_count_nvml', '_device_t', '_dummy_type', '_exchange_device', '_get_device', '_get_device_index', '_get_generator', '_get_nvml_device_index', '_get_pynvml_handler', '_get_rng_state_offset', '_initialization_lock', '_initialized', '_is_compiled', '_is_in_bad_fork', '_lazy_call', '_lazy_init', '_lazy_new', '_lazy_seed_tracker', '_maybe_exchange_device', '_memory_viz', '_nvml_based_avail', '_parse_visible_devices', '_queued_calls', '_raw_device_count_nvml', '_raw_device_uuid_nvml', '_register_triton_kernels', '_set_rng_state_offset', '_set_stream_by_id', '_sleep', '_tls', '_transform_uuid_to_ordinals', '_utils', '_warn_typed_storage_removal', 'amp', 'caching_allocator_alloc', 'caching_allocator_delete', 'can_device_access_peer', 'cast', 'change_current_allocator', 'check_error', 'classproperty', 'clock_rate', 'contextlib', 'cudaStatus', 'cudart', 'current_blas_handle', 'current_device', 'current_stream', 'default_generators', 'default_stream', 'device', 'device_count', 'device_of', 'empty_cache', 'get_allocator_backend', 'get_arch_list', 'get_device_capability', 'get_device_name', 'get_device_properties', 'get_gencode_flags', 'get_rng_state', 'get_rng_state_all', 'get_sync_debug_mode', 'graph', 'graph_pool_handle', 'graphs', 'has_half', 'has_magma', 'importlib', 'init', 'initial_seed', 'ipc_collect', 'is_available', 'is_bf16_supported', 'is_current_stream_capturing', 'is_initialized', 'jiterator', 'list_gpu_processes', 'lru_cache', 'make_graphed_callables', 'manual_seed', 'manual_seed_all', 'max_memory_allocated', 'max_memory_cached', 'max_memory_reserved', 'mem_get_info', 'memory', 'memory_allocated', 'memory_cached', 'memory_reserved', 'memory_snapshot', 'memory_stats', 'memory_stats_as_nested_dict', 'memory_summary', 'memory_usage', 'nccl', 'nvtx', 'os', 'power_draw', 'profiler', 'random', 'reset_accumulated_memory_stats', 'reset_max_memory_allocated', 'reset_max_memory_cached', 'reset_peak_memory_stats', 'seed', 'seed_all', 'set_device', 'set_per_process_memory_fraction', 'set_rng_state', 'set_rng_state_all', 'set_stream', 'set_sync_debug_mode', 'sparse', 'stream', 'streams', 'synchronize', 'sys', 'temperature', 'threading', 'torch', 'traceback', 'utilization', 'warnings']
#3.['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__getstate__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'as_integer_ratio', 'bit_count', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']

当出现__def__这个情况的时候说明不在是分割区了,已经是确确实实的最下层函数了

help(torch.cuda.is_available)

#Help on function is_available in module torch.cuda:
#is_available() -> bool
#    Return a bool indicating if CUDA is currently available.

1.2不同的操作系统的不同运行方式

1.3.其他工具

二.基础数据类型(tensor)和相关知识

2.1介绍:

张量(tensor)表示一个数值组成的数组,这个数组可能有多个维度,它是pytorch中最基本的数据结构。

2.2有关张量的操作:

2.2.1导入torch库

① 虽然库为PyTorch库,但应该导入torch,而不是pytorch

import torch
x = torch.arange(12) # 初始化一个0-11的张量
 

#tensor([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])

2.2.2访问张量的形状

① 可以通过张量的shape属性来访问张量的形状和张量中元素的总数。

import torch
x = torch.arange(12) # 初始化一个0-11的张量
x.shape # 张量的形状
print(a.size())

#torch.Size([12])

注意:这里的shape和size的结果虽然一样,都是打印出矩阵的形状,但是他的用法是不同的,一个是方法,一个是属性

import torch
x = torch.arange(12) # 初始化一个0-11的张量
x.numel() # 张量中元素的总数

#12

2.2.3 改变张量形状

① 要改变一个张量的形状而不改变元素数量和元素值,可以调用reshape函数。

import torch
x = torch.arange(12) # 初始化一个0-11的张量
x = x.reshape(3,4) # 一维张量改为3行四列的张量
x
tensor([[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11]])

2.2.4 创建全0、全1张量

① 使用全0、全1、其他常量或者从特定分布中随即采样的数字。

import torch
y = torch.zeros((2,3,4))
print(y)
tensor([[[0., 0., 0., 0.],
         [0., 0., 0., 0.],
         [0., 0., 0., 0.]],

        [[0., 0., 0., 0.],
         [0., 0., 0., 0.],
         [0., 0., 0., 0.]]])

import torch
y = torch.ones((2,3,4))
print(y)
tensor([[[1., 1., 1., 1.],
         [1., 1., 1., 1.],
         [1., 1., 1., 1.]],

        [[1., 1., 1., 1.],
         [1., 1., 1., 1.],
         [1., 1., 1., 1.]]])

2.2.5 创建特定值张量

① 通过提供包含数值的Python列表(或嵌套列表)来为所需张量中的每个元素赋予确定值。

import torch
y = torch.tensor([[2,1,4,3],[1,2,3,4],[4,3,2,1]]) # 二维tensor
z = torch.tensor([[[2,1,4,3],[1,2,3,4],[4,3,2,1]]]) # 三维tensor
print(y)
print(z)
tensor([[2, 1, 4, 3],
        [1, 2, 3, 4],
        [4, 3, 2, 1]])
tensor([[[2, 1, 4, 3],
         [1, 2, 3, 4],
         [4, 3, 2, 1]]])

import torch
y = torch.tensor([[2,1,4,3],[1,2,3,4],[4,3,2,1]]) # 二维tensor
z = torch.tensor([[[2,1,4,3],[1,2,3,4],[4,3,2,1]]]) # 三维tensor
print(y.shape)
print(z.shape)
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值