pytorch机器学习人工智能示例代码

代码语言:python

所属分类:人工智能

代码描述:pytorch机器学习人工智能示例代码

代码标签: 人工智能 示例

下面为部分代码预览,完整代码请点击下载或在bfwstudio webide中打开

import torch


device = torch.device('cpu') # CPU环境
# device = torch.device('cuda') # Uncomment this to run on GPU GPU环境

# N is batch size; D_in is input dimension;
# H is hidden dimension; D_out is output dimension.
N, D_in, H, D_out = 64, 1000, 100, 10

# Create random input and output data
x = torch.randn(N, D_in, device=device)  # 输入 (64,1000)
y = torch.randn(N, D_out, device=device)  # 输出 (64,10)

# Randomly initialize weights
w1 = torch.randn(D_in, H, device=device)  # 输入层-隐藏层 权重 (1000,100)
w2 = torch.randn(H, D_out, device=device)  # 隐藏层-输出层 权重 (100,10)

learning_rate = 1e-6  # 学习率
for t in range(500):
    # Forward pass: compute predicted y 前向传播:计算预测的y
    h = x.mm(w1)  # 点乘 得到隐藏层 (64,100) 
    # torch.mm()矩阵相乘 
    # torch.mul() 矩阵位相乘
    h_relu = h.clamp(min=0)  # 计算relu激活函数 
    # torch.clamp(input, min, max, out=None) → Tensor 将输入input张量每个元素的夹紧到区间 [min,max][min,max],并返回结果到一个新张量。
    y_pred = h_relu.mm(w2)  # 点乘 得到输出层 (64,10)

    # Compute and print loss; loss is a sc.........完整代码请登录后点击上方下载按钮下载查看

网友评论0