深度学习实验1:pytorch基本操作与logistics、softmax回归的实现

本文详细介绍了使用PyTorch进行基础操作,包括矩阵运算,以及从零开始实现Logistic回归和Softmax函数,同时展示了如何利用torch.nn模块简化实现。作者还分享了实验过程中的心得和常见问题解决方法。
摘要由CSDN通过智能技术生成

说明:原文是用jupyter写的,手动改成markdown。

一、任务1 Pytorch基本操作考察

1.1 任务内容

见实验要求

1.2 任务思路及代码

简单实现即可

import torch
import numpy as np

M = torch.rand(1, 3)
N = torch.rand(2, 1)
print("M", M)
print("N", N)
print("M - N", M - N)
print("M.subtract(N)", M.subtract(N))
print("torch.subtract(M, N)", torch.subtract(M, N))

1.3 实验结果分析

第一种 调用tensor类的运算符重载直接计算
第二种 是类函数
第三种是torch的外部函数
运算过程中出现广播,最后都变成了 shape 2*3 矩阵减法

P = torch.normal(0, 0.01, size=(3, 2))
Q = torch.normal(0, 0.01, size=(4, 2))
print("P",P)
print('Q',Q)
print("the inverse of Q")
print(Q.T)
print("P dot Q")
P@Q.T
x = torch.ones(1, requires_grad=True)
y_1 = x * x
y_2 = (x*x*x).detach()
y_3 = y_2 + y_1
y_3.backward()
x.grad

在 x^3 使用detach 相当于 对于 y3来说 y2是个常量 不求其导数,最后只有y2在反向传播计算图中被计算了。

二、任务2 实现logistics回归

2.1 从零开始实现logistics回归

# 从零开始实现logistics回归

import torch
import numpy as np

def mylogistics(X):
    z =  X.matmul(w.T) + b
    return torch.sigmoid(z)
    # result = torch.where(f>0.5, 1.0, 0.0)


loss = torch.nn.BCEWithLogitsLoss()

def mySGD(params, lr):
    with torch.no_grad():
        for param in params:
            param -= lr*param.grad
            param.grad.zero_()

x = torch.randint(-100,100, size=(100, 2), dtype=torch.float32)
label = []
for i in range(x.shape[0]):
    if x[i, 0] < x[i, 1]:
        label.append(1.0)
    else:
        label.append(0.0)

y = torch.tensor(label)
y = y.reshape((-1, 1))
print(x.shape)
print(y.shape)
def acc_logistics(y_hat, y):
    result = torch.where(y_hat>=0.5, 1, 0)
    return (result == y)
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值