基础NLP | 02 深度学习基本原理

发布于:2025-07-25 ⋅ 阅读:(20) ⋅ 点赞:(0)

深度学习基本原理

数学基础

线代

向量运算

  • 加和
  • 内积
  • 向量夹角余旋值

矩阵

  • 加法
  • 乘法
  • 转置

向量到矩阵的互转

reshape

张量 tensor

将三个 2x2的矩阵排列在一起,就可以称之为3x2x2的张量

是神经网络的训练中最为常见的数据形式,维度相同的几个矩阵放在一起

这是2x2x2的张量
[ [ [ 1 , 2 ] , [ 3 , 4 ] ] , [ [ 5 , 6 ] , [ 7 , 8 ] ] ] \begin{bmatrix} [[1,2],\\ [3,4]],\\ [[5,6],\\ [7,8]]\end{bmatrix} [[1,2],[3,4]],[[5,6],[7,8]]
张量的常见操作

转置 x.transpose(1,2)
[ [ [ 1 , 3 ] , [ 2 , 4 ] ] , [ [ 5 , 7 ] , [ 6 , 8 ] ] ] \begin{bmatrix} [[1,3],\\ [2,4]],\\ [[5,7],\\ [6,8]]\end{bmatrix} [[1,3],[2,4]],[[5,7],[6,8]]
在上面的基础上转置 x.transpose(0,1)
[ [ [ 1 , 2 ] , [ 5 , 6 ] ] , [ [ 3 , 4 ] , [ 7 , 8 ] ] ] \begin{bmatrix} [[1,2],\\ [5,6]],\\ [[3,4],\\ [7,8]]\end{bmatrix} [[1,2],[5,6]],[[3,4],[7,8]]

numpy 常用操作

import numpy as np
import torch

x = np.array([[1,2,3],[4,5,6]])

print(x)
print(x.ndim)#维度  2
print(x.shape)# 获取行列维度  (2, 3)
print(x.size)#一共多少个数字  6
print(x.dtype)#类型   int64
print(np.sum(x))#矩阵内所有元素的和 21
print(np.sum(x,axis=0))#行相加 [5 7 9]
print(np.sum(x,axis=1))#列相加 [ 6 15]
print(np.reshape(x,(3,2)))#变换维度[[1 2]
 #[3 4]
 #[5 6]]

 #[[1.         1.41421356 1.73205081]
 #[2.         2.23606798 2.44948974]]
print(np.sqrt(x))#每个数字开平方

#[[  2.71828183   7.3890561   20.08553692]
# [ 54.59815003 148.4131591  403.42879349]]
print(np.exp(x))#每个数求指数
print(x.transpose())#转置
print(x.flatten())#变成一维向量 [1 2 3 4 5 6]


x = torch.FloatTensor(x)
print(x.shape)#torch.Size([2, 3])
#tensor([[  2.7183,   7.3891,  20.0855],
        # [ 54.5981, 148.4132, 403.4288]])
print(torch.exp(x))
print(torch.sum(x))#tensor(21.)
print(torch.sum(x,dim=0))#tensor([5., 7., 9.])
print(torch.sum(x,dim=1))#tensor([ 6., 15.])
'''
tensor([[1., 4.],
        [2., 5.],
        [3., 6.]])
'''
print(x.transpose(1,0))
print(x.flatten())#tensor([1., 2., 3., 4., 5., 6.])

导数, 梯度

表示函数变化的方向
f ′ ( x 0 ) = l i m Δ y Δ x = l i m f ( x 0 + Δ x ) − f ( x 0 ) Δ x f'(x_0) = lim\frac{\Delta y}{\Delta x} = lim \frac{f(x_0 + \Delta x) - f(x_0)}{\Delta x} f(x0)=limΔxΔy=limΔxf(x0+Δx)f(x0)
求导法则

  • 加法
  • 乘法
  • 除法
  • 链式求导

梯度

多元函数的导数

原函数: y = 3 x 1 2 + 4 x 2 2 + 5 x 3 2 y = 3x_1^2 + 4x_2^2 + 5x_3^2 y=3x12+4x22+5x32

导函数: y = 6 x 1 + 8 x 2 + 10 x 3 y = {6x_1 + 8x_2 + 10x_3} y=6x


网站公告

今日签到

点亮在社区的每一天
去签到