持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第3天,点击查看活动详情
今天是十月更文计划第三天,第四篇
从今天这篇文章开始,我准备分享深度学习的基础网络,都是一些基础概念与知识。只为新手小白普及知识。网上有很多写这方面的博客,在学习的过程中都可以结合的看一看。预计三篇文章:ANN,CNN,RNN
ANN
多层感知机
多层感知机又被称为人工神经网络(ANN,Artificial Neural Network),是最简单的一种神经网络结构。结构分为输入层,隐层层,输出层。其中最简单的ANN只含有一个隐层。
全连接,前向传播
隐藏层的输出为(f (W1X+b1)),w1为权重,b1为偏执值。f为激活函数
使用激活函数,能够给神经元引入非线性因素。
激活函数一般使用Relu或者tanx
激活函数必须是连续并且可导的非线性函数,并且在一个合适的区间内,比如y值介于[0,1]之间。
实现代码如下:
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from torch import optim
from torch.utils.data import DataLoader, Dataset
x = np.array([[1, 2, 5], [3, 4, 5], [5, 6, 5]], dtype=np.float32)
y = np.array([[8], [8], [10]], dtype=np.float32)
class FD(Dataset):
def __init__(self, x, y):
self.x = x
self.y = y
def __len__(self):
return len(self.x)
def __getitem__(self, idx):
return x[idx], y[idx]
dataset = FD(x, y)
print("*" * 100)
for i in range(len(dataset)):
print(dataset[i])
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.fc1 = nn.Linear(3, 5)
self.fc2 = nn.Linear(5, 8)
self.fc3 = nn.Linear(8, 1)
def forward(self, x):
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
net = Net()
optimizer = optim.SGD(net.parameters(), lr=0.01)
criterion = nn.MSELoss()
dl = DataLoader(dataset=dataset, batch_size=1)
for i_batch, sample_batched in enumerate(dl):
input = sample_batched[0]
target = sample_batched[1]
print('::::', input, target)
optimizer.zero_grad()
output = net(input)
loss = criterion(output, target)
loss.backward()
optimizer.step()
print("i_batch:", i_batch, "loss:", loss)
print('-' * 100)
这是我在学习中写的最基础的实现代码,前面定义数据,定义Net()类,类中写你所需要的隐层的个数,并且在最后调用函数。
确定参数的方法就使用GSD梯度下降法,自己可以不断调整参数来进行测试。
在实现神经网络的过程中,首先需要安装torch
神经网络的构建均需要继承一个类:Torch.nn.Module,只有继承了才表明是一个神经网络模型。
nn.Linear(3, 5)表示是一个全连接的模型。
criterion = nn.MSELoss()表示将要计算损失函数。