2.1 预备知识
2.2数据预处理
2.3 线性代数
2.4 微积分
import matplotlib.pyplot as plt
def f(x):
return x ** 3 - 1 / x
def f_prime(x):
return 3 * x ** 2 + 1 / x**2
# 生成x值的数组
x = np.linspace(-5, 5, 100)
# 计算y值和切线斜率
y = f(x)
m = f_prime(x)
x0 = 1
y0 = f(x0)
m0 = f_prime(x0)
b0 = y0 - m0 * x0
# 切线的方程
def tangent_line(x):
return m0 * x + b0
y_tangent = tangent_line(x)
# 绘制切线
plt.plot(x, y_tangent, label="tangent line")
plt.plot(x, y, label="f(x)")
# 显示图像
plt.xlabel("x")
plt.ylabel("y")
plt.legend()
plt.show()
x = torch.arange(2.0, requires_grad=True)#x0取0,x1取1
y = 3*x[0]**2+ 5*torch.exp(x[1])
y.backward()
print("f(x)的梯度:", x.grad)
#f(x)的梯度: tensor([ 0.0000, 13.5914])
print("验证梯度:", x.grad==torch.tensor([6*x[0], 5*torch.exp(x[1])]))
#验证梯度: tensor([True, True])
x = torch.arange(4.0,requires_grad=True)
y = torch.dot(x, x).sqrt()#dot意思两个数相乘再相加
y.backward()
print("f(x)的梯度:", x.grad)
print("验证结果:", x.grad==x/(torch.dot(x, x).sqrt()))
#x/(torch.dot(x, x).sqrt()是自己手算出来的,用来验证
2.5 自动微分