PyTorch上搭建简单神经网络实现回归和分类的示例上搭建简单神经网络实现回归和分类的示例
本篇文章主要介绍了PyTorch上搭建简单神经网络实现回归和分类的示例,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过
来看看吧
本文介绍了PyTorch上搭建简单神经网络实现回归和分类的示例,分享给大家,具体如下:
一、一、PyTorch入门入门
1. 安装方法安装方法
登录PyTorch官网,http://pytorch.org,可以看到以下界面:
按上图的选项选择后即可得到Linux下conda指令:
conda install pytorch torchvision -c soumith
目前PyTorch仅支持MacOS和Linux,暂不支持Windows。安装 PyTorch 会安装两个模块,一个是torch,一个 torchvision, torch 是主模块,用来搭建神经网络
的,torchvision 是辅模块,有数据库,还有一些已经训练好的神经网络等着你直接用,比如 (VGG, AlexNet, ResNet)。
2. Numpy与与Torch
torch_data = torch.from_numpy(np_data)可以将numpy(array)格式转换为torch(tensor)格式;torch_data.numpy()又可以将torch的tensor格式转换为numpy的array格式。
注意Torch的Tensor和numpy的array会共享他们的存储空间,修改一个会导致另外的一个也被修改。
对于1维(1-D)的数据,numpy是以行向量的形式打印输出,而torch是以列向量的形式打印输出的。
其他例如sin, cos, abs,mean等numpy中的函数在torch中用法相同。需要注意的是,numpy中np.matmul(data, data)和data.dot(data)矩阵相乘会得到相同结果;torch中
torch.mm(tensor, tensor)是矩阵相乘的方法,得到一个矩阵,tensor.dot(tensor)会把tensor转换为1维的tensor,然后逐元素相乘后求和,得到与一个实数。
相关代码:相关代码:
import torch
import numpy as np
np_data = np.arange(6).reshape((2, 3))
torch_data = torch.from_numpy(np_data) # 将numpy(array)格式转换为torch(tensor)格式
tensor2array = torch_data.numpy()
print(
'numpy array:', np_data,
'torch tensor:', torch_data,
'tensor to array:', tensor2array,
) # torch数据格式在print的时候前后自动添加换行符
# abs
data = [-1, -2, 2, 2]
tensor = torch.FloatTensor(data)
print(
'abs',
'numpy: ', np.abs(data),
'torch: ', torch.abs(tensor)
) # 1维的数据,numpy是行向量形式显示,torch是列向量形式显示
# sin
print(
'sin',
'numpy: ', np.sin(data),
'torch: ', torch.sin(tensor)
)
# mean
print(