说明:原文是用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)