没有合适的资源?快使用搜索试试~ 我知道了~
资源推荐
资源详情
资源评论
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(
'\nnumpy array:\n', np_data,
'\ntorch tensor:', torch_data,
'\ntensor to array:\n', tensor2array,
) # torch
数据格式在
print
的时候前后自动添加换行符
# abs
data = [-1, -2, 2, 2]
tensor = torch.FloatTensor(data)
print(
'\nabs',
'\nnumpy: \n', np.abs(data),
'\ntorch: ', torch.abs(tensor)
) # 1
维的数据,
numpy
是行向量形式显示,
torch
是列向量形式显
示
# sin
print(
'\nsin',
'\nnumpy: \n', np.sin(data),
'\ntorch: ', torch.sin(tensor)
)
# mean
print(
'\nmean',
'\nnumpy: ', np.mean(data),
'\ntorch: ', torch.mean(tensor)
)
#
矩阵相乘
data = [[1,2], [3,4]]
tensor = torch.FloatTensor(data)
print(
'\nmatrix multiplication (matmul)',
'\nnumpy: \n', np.matmul(data, data),
剩余14页未读,继续阅读
资源评论
程序猿小乙
- 粉丝: 62
- 资源: 1740
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功