python pytorch view()函數

view是改变tensor的形状,并不只是简单的只是多行tensor拼接成一行,view中的-1是自适应的调整

A = torch.arange(0, 16)
print(A)
#tensor([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15])
B = A.view(-1,2)
print(B)
#tensor([[ 0,  1],
        [ 2,  3],
        [ 4,  5],
        [ 6,  7],
        [ 8,  9],
        [10, 11],
        [12, 13],
        [14, 15]])
B = A.view(2,-1)
print(B)
#tensor([[ 0,  1,  2,  3,  4,  5,  6,  7],
        [ 8,  9, 10, 11, 12, 13, 14, 15]])
C = A.view(-1,2,2)
print(C)
#tensor([[[ 0,  1],
         [ 2,  3]],

        [[ 4,  5],
         [ 6,  7]],

        [[ 8,  9],
         [10, 11]],

        [[12, 13],
         [14, 15]]])
C = A.view(2,2,-1)
print(C)
#tensor([[[ 0,  1,  2,  3],
         [ 4,  5,  6,  7]],

        [[ 8,  9, 10, 11],
         [12, 13, 14, 15]]])


 

### PyTorch框架简介 PyTorch 是一个由 Facebook 人工智能研究院(FAIR)于2016年发布的开源深度学习框架,专为 GPU 加速的深度神经网络编程而设计[^2]。该框架因其简洁、灵活和符合 Python 风格的特点而在科研和工业生产中得到广泛的应用。 ### 安装与环境配置 为了更好地利用 PyTorch 进行开发,建议使用 Anaconda 来管理 Python 环境及其依赖项。这不仅简化了包管理和虚拟环境创建的过程,还能够更方便地处理不同版本间的兼容性问题[^3]。 #### 创建并激活 Conda 虚拟环境 ```bash conda create -n pytorch_env python=3.9 conda activate pytorch_env ``` #### 安装 PyTorch 及其他必要库 可以通过官方推荐的方式安装适合当前系统的 PyTorch 版本: 对于 CUDA 支持的 GPU 用户: ```bash conda install pytorch torchvision torchaudio cudatoolkit=11.3 -c pytorch ``` 仅限 CPU 的用户则应执行如下命令: ```bash conda install pytorch torchvision torchaudio cpuonly -c pytorch ``` ### 基础概念介绍 在 PyTorch 中,`Tensor` 类似于 NumPy 的 `ndarray`,但是具有额外的功能支持自动求导机制,这对于实现反向传播算法至关重要。下面给出一段简单的代码来展示如何定义张量以及完成基本运算操作。 ```python import torch # 初始化两个随机矩阵作为输入数据 matrix_a = torch.randn(5, 3) matrix_b = torch.randn(3, 4) print(f'Matrix A:\n{matrix_a}') print(f'\nMatrix B:\n{matrix_b}') # 执行矩阵乘法 result_matrix = matrix_a.mm(matrix_b) print(f'\nResult Matrix (A * B):\n{result_matrix}') ``` 此外,PyTorch 提供了一个非常重要的特性——动态计算图。这意味着每次前向传递都会重新构建一个新的计算图结构,从而允许更加自然直观地编写自定义层或复杂模型架构。 ### 构建简单线性回归模型实例 这里提供了一段完整的代码片段用于说明怎样快速上手 PyTorch 开发流程:从准备数据集到训练过程直至最终评估预测性能。 ```python from sklearn.datasets import make_regression from sklearn.model_selection import train_test_split import numpy as np class LinearRegressionModel(torch.nn.Module): def __init__(self): super().__init__() self.linear_layer = torch.nn.Linear(in_features=1, out_features=1) def forward(self, x_input): prediction_output = self.linear_layer(x_input) return prediction_output def prepare_data(): X, y = make_regression(n_samples=1000, n_features=1, noise=0.1, random_state=7) # 将numpy数组转换成pytorch tensor对象 features_tensor = torch.from_numpy(X.astype(np.float32)) labels_tensor = torch.from_numpy(y.astype(np.float32)).view(-1, 1) return train_test_split(features_tensor, labels_tensor) if __name__ == '__main__': model_instance = LinearRegressionModel() criterion_function = torch.nn.MSELoss() # 使用均方误差损失函数 optimizer_algorithm = torch.optim.SGD(model_instance.parameters(), lr=0.01) training_set_x, test_set_x, training_set_y, test_set_y = prepare_data() epochs_number = 1000 for epoch_index in range(epochs_number): predictions_on_trainset = model_instance(training_set_x) loss_value = criterion_function(predictions_on_trainset, training_set_y) # 清除之前的梯度信息 optimizer_algorithm.zero_grad() # 计算新的梯度值 loss_value.backward() # 更新权重参数 optimizer_algorithm.step() if (epoch_index + 1) % 100 == 0: print(f'Epoch [{epoch_index+1}/{epochs_number}], Loss: {loss_value.item():.4f}') with torch.no_grad(): predicted_values_for_testsamples = model_instance(test_set_x).detach().numpy() actual_values_of_testsamples = test_set_y.numpy() mse_error = ((predicted_values_for_testsamples - actual_values_of_testsamples)**2).mean(axis=None) print(f'Test MSE Error after Training: {mse_error:.4f}') ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值