Skip to main content

神经网络基础

说明

一个简单的神经网络由输入层→隐藏层→输出层。

它是深度学习的最基础模型之一,用于解决分类回归问题。

组件作用
输入层接收原始数据(如特征 x1, x2)
权重(W)控制信号强度,每个输入乘以一个对应权重
偏置(b)用于调整输出,使模型更灵活
激活函数(如 ReLU / Sigmoid)给隐藏层或输出层加上非线性特性
隐藏层模拟人脑神经元之间的连接,进行特征转换和学习
输出层输出最终预测结果,如分类标签或回归值

示例1

# 逻辑回归
import numpy as np
import pandas as pd
from gradiet import gradient_type
class liner:
def __init__(self, loss_type = 'MES', active_type = 'sigmod'):
# 1.设置初始权重
self.w = 0
self.b = 0
# 学习率
self.lr = 0.01

self.loss_type = loss_type
self.active_type = active_type

# 激活函数
def get_active(self,y):
match self.active_type:
case 'sigmod':
return 1 / (1 + np.exp(-(y)))

# 线性函数
def get_ffn(self,x):
return self.w * x + self.b

# 获取损失
def get_loss(self,target,res):
match self.loss_type:
case 'MES':
return (target - res) ** 2 / 2

# 计算梯度
def count_g(self,target,predict,res):
gradient_func = gradient_type.loc[self.active_type, self.loss_type]
# 调用匿名函数
w, b = gradient_func(target, predict, res)
return w, b

# 梯度更新
def get_g(self,w,b):
self.w -= w * self.lr
self.b -= b * self.lr
return self.w, self.b

# 训练
def train(self, target, predict, ep):
for i in range(ep):
# 前向传播
y = self.get_ffn(predict)
res = self.get_active(y)

# 计算损失
loss = self.get_loss(target, res)

# 计算梯度
w, b = self.count_g(target, predict, res)

# 更新梯度
self.get_g(w,b)

if i % 10 == 0:
print(f"损失值:{loss}")

liner(loss_type='MES',active_type='sigmod').train(2, 1, 1000)

示例2

import torch
from sklearn.datasets import load_digits
# 手写数据集,输入64,输出10
databas = load_digits()

class Sq:
def __init__(self):
# 1*64 @ 64*40 @ 40*10
# 创建中间层矩阵
input_num = 64
midput_num = 40
output_num = 10

# 设置学习率
self.learn = 0.01

self.mid_first = torch.ones((input_num, midput_num), requires_grad=True)
self.mid_second = torch.ones((midput_num, output_num), requires_grad=True)

def res(self,x,y):
# 将获取的数据转换成张量
input_x = torch.from_numpy(x).float()
out_y_index = torch.tensor(y).long()
out_y = torch.zeros(10).float()
out_y[out_y_index] = 1

return input_x,out_y

def train(self,x,y):
for eporch in range(100):
input_x, out_y = self.res(x,y)

# 前向传播
out = input_x @ self.mid_first @ self.mid_second

# 这部分可以加入激活函数,例如softmax
# 算是函数可以替换,调用函数

# 计算损失(均方误差)
loss = ((out_y - out) ** 2).mean()

# 反向传播
loss.backward()

# 梯度更新
with torch.no_grad():
self.mid_first -= self.learn * self.mid_first.grad
self.mid_second -= self.learn * self.mid_second.grad

# 梯度清零
self.mid_first.grad.zero_()
self.mid_second.grad.zero_()

if eporch % 10 == 0:
print(f"损失值:{loss.item()}")

x = databas.data[0]
y = databas.target[0]
Sq().train(x, y)