ARTICLE · 1136246
AI开发之Web基础快速入门主流深度学习框架介绍PyTorch
请在微信客户端打开






AI开发之Web基础快速入门主流深度学习框架介绍PyTorch
1)PyTorch框架介绍
前面两个介绍完,咱们在看看看其他的。pytorch是当前最主流,最受科研人员和企业工程师青睐的开源深度学习框架之一,它由facebook ai研究团队推出。与其他传统框架相比,pytorch的核心优势可以用两个词概括:动态图和python原生。
动态图机制(Imperative/Eager Execution):在老版本tf中,咱们必须先用代码设计出一张复杂的静态计算图就像先画好复杂的电路图,然后再开启会话session把数据喂进去运行。
而pytorch采用的是动态图机制也叫即时执行,这意味着它的计算图是随着代码运行动态构建的。咱们写一行矩阵乘法,它就立刻执行一行。这使得咱们可以直接使用python原生的if条件判断和for循环来改变神经网络的结构,极大地降低了开发门槛。调试极其丝滑由于它是纯python原生的风格,当代码报错时咱们不需要去排查让人头疼的底层静态图日志。咱们可以直接使用python标准的调试工具pdb,pycharm运行断点或者直接print,在任意一行代码处打印出张量的形状和数值。这种所见即所得的体验,让 pytorch成为了深度学习入门和算法实验的首选。
2)深度学习需要用到的库安装
python下载地址
https://www.python.org/downloads/
miniconda下载地址
https://repo.anaconda.com/miniconda/
pip install torch torchvision torchaudio numpy -i https://mirrors.aliyun.com/pypi/simple/
3)代码案例
在这个pytorch的案例中,咱们会发现显式数据转换咱们必须手动把numpy的数据用torch.tensor()包装成pytorch能看懂的tensor张量。手写求导三部曲pytorch没有隐藏 fit()的细节,咱们必须在代码里显式地写出下面三步
optimizer.zero_grad()(清空过去的斜率)
loss.backward()(高数反向求导)
optimizer.step()(让优化器真正去修改参数)
咱们总结一下哦如果说keras是傻瓜式的自动挡汽车,那么pytorch就是掌控感极强的手动挡跑车。虽然它比keras多写了十几行代码,但咱们在控制模型训练的每一步时,会觉得异常丝滑和透明哦!!!
import numpy as npimport torchimport torch.nn as nnimport torch.optim as optimRED = "\033[31m"GREEN = "\033[32m"YELLOW = "\033[33m"BOLD = "\033[1m"END = "\033[0m"# Construct traffic samples and standard data preprocessing# Feature format: [Request frequency, 404 count, Is robot UA, Page size MB]# Label definition: 0 = Normal user access, 1 = Malicious attack behaviorif __name__ == "__main__":# 1) Raw Web traffic feature matrixX_data = np.array([[2.1, 0.0, 0, 0.1], # 3) Normal traffic[95.4, 42.0, 1, 8.5], # 4) Vulnerability scanning (Attack)[4.5, 1.0, 0, 0.5], # 5) Normal traffic[1.2, 0.0, 0, 0.0], # 6) Normal traffic[88.0, 35.0, 1, 12.1], # 7) Credential stuffing (Attack)], dtype=np.float32)# True black and white labels (Ground truth)y_data = np.array([[0], [1], [0], [0], [1]], dtype=np.float32)visitor_names = ["User A", "User B", "User C", "User D", "User E"]# Feature normalization: Scale data to a uniform magnitudemean = X_data.mean(axis=0)std = X_data.std(axis=0) + 1e-8X_data_scaled = (X_data - mean) / std# Convert NumPy arrays to PyTorch TensorsX_tensor = torch.tensor(X_data_scaled, dtype=torch.float32)y_tensor = torch.tensor(y_data, dtype=torch.float32)# 2) Build the neural network layer by layer (PyTorch nn.Sequential base)# Sequential acts as a linear stack of layers similar to Kerasmodel = nn.Sequential(# Layer 1 (Hidden Layer): 8 neurons, takes 4-dimensional input features, uses ReLU activationnn.Linear(in_features=4, out_features=8),nn.ReLU(),# Layer 2 (Output Layer): 1 neuron, uses Sigmoid activation to output a risk probability between 0 and 1nn.Linear(in_features=8, out_features=1),nn.Sigmoid())# 3) Configure loss function and optimizer# BCELoss stands for Binary Cross Entropy Losscriterion = nn.BCELoss()optimizer = optim.SGD(model.parameters(), lr=0.1)# 4) Start the training loop to iteratively optimize parametersprint("-" * 75)print(f"{BOLD}{YELLOW}===== AI Threat Perception System: Training PyTorch Neural Network ====={END}")print("-" * 75)print("PyTorch sequential architecture initialized, starting training loop...")epochs = 1000for epoch in range(1, epochs + 1):# Forward pass: Compute predicted probabilities by passing X through the modely_pred = model(X_tensor)# Compute loss: Calculate the distance between predictions and ground truthloss = criterion(y_pred, y_tensor)# Backward pass: Clear old gradients, compute new gradients via backpropagationoptimizer.zero_grad()loss.backward()# Parameter update: Apply computed gradients to shift parameters towards global minimumoptimizer.step()print(f"\n{BOLD}{GREEN}Model training completed! Model parameters have successfully converged.{END}\n")# 5) Online inference and real-time Web gateway interception# torch.no_grad() disables gradient calculation to speed up evaluation and save memorywith torch.no_grad():probabilities = model(X_tensor).numpy().flatten()threshold = 0.5print("-" * 75)print(f"{BOLD}{YELLOW}===== AI WAF Gateway: Real-Time Live Traffic Inspection Active ====={END}")print("-" * 75)for name, score in zip(visitor_names, probabilities):if score > threshold:action = f"{BOLD}{RED}[BLOCK & DROP] - Intercepted by AI Neural Network! (Risk Prob: {score*100:.2f}%){END}"else:action = f"{BOLD}{GREEN}[PASS] - Clear Traffic. (Risk Prob: {score*100:.2f}%){END}"print(f"Live Flow: {name:<12} -> Predicted: {action}")print("-" * 75)
过去帮客户写的AI案例请看这里:
https://space.bilibili.com/1456034618/lists/3151496?type=season