AI开发之Web基础快速入门主流深度学习框架介绍Keras

发布时间:2026/10/7 20:35:41
AI开发之Web基础快速入门主流深度学习框架介绍Keras AI开发之Web基础快速入门主流深度学习框架介绍Keras1keras介绍tf咱们上手还是有一定难道的是不是咱们开始以来张量流搞懂以后如果想建一个神经网络需要自己去手写复杂的求导公式各种梯度前向/反向传播输入层隐藏层输出层看这的头大。所有后面出现了keras它是基于tk的高级神经网络官方积木箱。keras把复杂的矩阵微积分多层链式求导公式全部封装成了现成的乐高积木。咱们不需要关心什么是梯度带也不用手写反向传播直接把输入层隐藏层输出层一块块叠起来几行行代码就能搭好一个企业级的神经网络。所以总结就一句话keras它的特点是极简,优雅,极其适合新手入门。是因为它使用了keras高级api现在已经完美融入tf.keras中。如果和咱们以前用的老版本tf1.x相比这简直是降维打击。以前为了实现同样的功能咱们需要写出好几倍,甚至上百行极其臃肿的底层代码。现代tf/keras模式之所以能这么爽快主要是因为以下核心改变再也不用手动定义参数和公式 以前在老tf里咱们得自己用 tf.Variable去定义权重矩阵W和偏置b还要苦哈哈地写矩阵乘法公式tf.add(tf.matmul(X, W), b)一旦维度没对齐就疯狂报错。现在一个dense(8, activationrelu)keras在底层把这些数学细节全帮咱们默默做好了。告别恶心的会话session 以前老tf必须先建一个静态计算图然后开启会话with tf.Session() as sess:最后用 sess.run()把数据喂进去才能看到结果调试起来极其痛苦。现在的tf默认是动态图模式Eager Execution像写普通python和numpy一样写完一行就能立刻运行并看到结果。一行model.fit()搞定训练大循环 以前咱们要自己写for epoch in range(1000): 外循环里面还要写高数里的梯度下降去手动更新参数。现在 keras把这套标准的猜答案,算误差,改参数流水线直接封装成了model.fit()一行代码直接起飞。真正的乐高积木体验通过qequential()咱们只需要把层像叠积木一样堆起来keras会自动帮咱们计算上一层的输出怎么对接下一层的输入完全不需要操心结构连接问题。2深度学习需要用到的库安装python下载地址https://www.python.org/downloads/miniconda下载地址https://repo.anaconda.com/miniconda/pip install tensorflow -i https://mirrors.aliyun.com/pypi/simple/3代码案例这次咱们定义权重和偏置前向传播完全不需要写。 dense层在后台自动创建并使用默认的最佳算法初始化好了所有参数前向传播Keras内部自动完成所有层的矩阵相乘然后激活函数直接调用字符串。 只需写activationrelu和sigmoid就行了哦不需要再去写了损失函数直接调用字符串 只需写lossbinary_crossentropy以及咱们最后一步训练与求导循环只有一行代码model.fit(..., epochs1000)这一行直接替代了上面所有的求导更新和循环逻辑就行了。import numpy as npimport tensorflow as tffrom tensorflow.keras import Sequentialfrom tensorflow.keras.layers import DenseRED \033[31mGREEN \033[32mYELLOW \033[33mBOLD \033[1mEND \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 behavior# if __name__ __main__:# Raw Web traffic feature matrixX_data np.array([[2.1, 0.0, 0, 0.1], # Normal traffic[95.4, 42.0, 1, 8.5], # Vulnerability scanning (Attack)[4.5, 1.0, 0, 0.5], # Normal traffic[1.2, 0.0, 0, 0.0], # Normal traffic[88.0, 35.0, 1, 12.1], # Credential stuffing (Attack)], dtypenp.float32)# True black and white labels (Ground truth)y_data np.array([[0], [1], [0], [0], [1]], dtypenp.float32)visitor_names [User A, User B, User C, User D, User E]# Feature normalization: Scale data to a uniform magnitude to prevent large numbers from dominating trainingmean X_data.mean(axis0)std X_data.std(axis0) 1e-8X_data_scaled (X_data - mean) / std# # 2) Build the neural network layer by layer (Keras Sequential base)# # Sequential acts as a linear stack of layersmodel Sequential([# Layer 1 (Hidden Layer): 8 neurons, takes 4-dimensional input features, uses ReLU activationDense(units8, input_dim4, activationrelu, nameHidden_Layer),# Layer 2 (Output Layer): 1 neuron, uses Sigmoid activation to output a risk probability between 0 and 1Dense(units1, activationsigmoid, nameOutput_Layer)])# # 3) Configure loss function, optimizer, and metrics# model.compile(optimizertf.keras.optimizers.SGD(learning_rate0.1), # Optimizer: Updates parameters based on gradientslossbinary_crossentropy, # Loss function: Binary cross-entropy for binary classificationmetrics[accuracy] # Metric to monitor during training)# # 4) Start the training loop to iteratively optimize parameters# print(- * 75)print(f{BOLD}{YELLOW} AI Threat Perception System: Training Keras Sequential Model {END})print(- * 75)print(Keras model initialized, AI pipeline training loop starting...)# epochs1000 means the model iterates over the 5 samples 1000 timesmodel.fit(X_data_scaled, y_data, epochs1000, verbose0)print(f\n{BOLD}{GREEN}Model training completed! Model parameters have successfully converged.{END}\n)# # 5) Online inference and real-time Web gateway interception# # Call the predict method to execute the forward pass through the networkprobabilities model.predict(X_data_scaled, verbose0).flatten()threshold 0.5 # Risk control interception threshold