「日拱一碼」024 機器學習——防止過擬合

目錄

數據層面

數據增強

數據正則化

?數據采樣

模型結構層面

簡化模型

添加正則化層

早停法(Early Stopping)

訓練過程層面

使用交叉驗證

使用集成學習

調整學習率


防止過擬合是機器學習中一個非常重要的問題,它可以幫助模型在新的數據上表現得更好。以下將從數據層面、模型結構層面和訓練過程層面對防止過擬合的方法進行分類介紹

數據層面

數據增強

數據增強通過對訓練數據進行變換(如旋轉、縮放、裁剪等),增加數據的多樣性,從而減少模型對訓練數據的過擬合

## 數據層面
# 1. 數據增強import numpy as np
import matplotlib.pyplot as plt
from tensorflow.keras.datasets import mnist
from tensorflow.keras.preprocessing.image import ImageDataGenerator# 加載 MNIST 數據集
(x_train, y_train), (x_test, y_test) = mnist.load_data()# 將圖像數據轉換為浮點數并歸一化
x_train = x_train.astype('float32') / 255.0
x_test = x_test.astype('float32') / 255.0# 將圖像數據擴展為 4D 張量 (samples, height, width, channels)
x_train = np.expand_dims(x_train, -1)
x_test = np.expand_dims(x_test, -1)# 創建數據增強生成器
datagen = ImageDataGenerator(rotation_range=20,  # 隨機旋轉度數范圍width_shift_range=0.1,  # 隨機水平移動范圍height_shift_range=0.1,  # 隨機垂直移動范圍shear_range=0.2,  # 剪切強度zoom_range=0.2,  # 隨機縮放范圍horizontal_flip=False,  # 不進行水平翻轉(因為數字圖像水平翻轉可能沒有意義)fill_mode='nearest'  # 填充新創建像素的方法
)# 選擇一張圖像進行增強
sample_image = x_train[0]  # 選擇第一張圖像
sample_image = np.expand_dims(sample_image, 0)  # 添加批次維度# 使用數據增強生成器生成增強后的圖像
augmented_images = datagen.flow(sample_image, batch_size=1)# 可視化增強后的圖像
plt.figure(figsize=(10, 6))
for i in range(10):  # 生成并顯示 10 張增強后的圖像augmented_image = next(augmented_images)[0]  # 獲取一張增強后的圖像plt.subplot(2, 5, i + 1)plt.imshow(augmented_image.squeeze(), cmap='gray')  # 顯示灰度圖像plt.axis('off')  # 關閉坐標軸
plt.show()

數據正則化

數據正則化通過對輸入數據進行歸一化或標準化,使數據的分布更加均勻,減少模型對數據的過擬合

# 2. 數據正則化import numpy as np
import matplotlib.pyplot as plt
from tensorflow.keras.datasets import mnist
from sklearn.preprocessing import StandardScaler
from imblearn.over_sampling import SMOTE
from imblearn.under_sampling import RandomUnderSampler# 加載 MNIST 數據集
(x_train, y_train), (x_test, y_test) = mnist.load_data()# 將圖像數據轉換為浮點數
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')# 數據歸一化(將像素值縮放到 [0, 1])
x_train_normalized = x_train / 255.0
x_test_normalized = x_test / 255.0# 數據標準化(將數據縮放到均值為 0,標準差為 1)
scaler = StandardScaler()
x_train_reshaped = x_train.reshape(-1, 28 * 28)  # 將圖像數據展平為二維數組
x_test_reshaped = x_test.reshape(-1, 28 * 28)x_train_standardized = scaler.fit_transform(x_train_reshaped)
x_test_standardized = scaler.transform(x_test_reshaped)# 可視化歸一化和標準化的效果
def plot_images(images, title):plt.figure(figsize=(10, 2))for i in range(10):plt.subplot(1, 10, i + 1)plt.imshow(images[i], cmap='gray')plt.axis('off')plt.suptitle(title)plt.show()# 顯示原始圖像
plot_images(x_train[:10], "Original Images")# 顯示歸一化后的圖像
plot_images(x_train_normalized[:10], "Normalized Images")# 顯示標準化后的圖像
plot_images(x_train_standardized[:10].reshape(-1, 28, 28), "Standardized Images")

?

數據采樣

數據采樣可以通過欠采樣(減少多數類樣本)或過采樣(增加少數類樣本)來平衡數據集,減少模型對多數類的過擬合

# 3. 數據采樣import numpy as np
import matplotlib.pyplot as plt
from tensorflow.keras.datasets import mnist
from sklearn.preprocessing import StandardScaler
from imblearn.over_sampling import SMOTE
from imblearn.under_sampling import RandomUnderSampler# 加載 MNIST 數據集
(x_train, y_train), (x_test, y_test) = mnist.load_data()# 將圖像數據轉換為浮點數
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')# 模擬不平衡數據集(選擇數字 0 和數字 1)
x_train_sampled = x_train[y_train < 2]
y_train_sampled = y_train[y_train < 2]# 過采樣(SMOTE)
smote = SMOTE(random_state=42)
x_resampled, y_resampled = smote.fit_resample(x_train_sampled.reshape(-1, 28 * 28), y_train_sampled)# 欠采樣(RandomUnderSampler)
undersampler = RandomUnderSampler(random_state=42)
x_undersampled, y_undersampled = undersampler.fit_resample(x_train_sampled.reshape(-1, 28 * 28), y_train_sampled)# 可視化過采樣和欠采樣的效果
def plot_sampled_images(images, labels, title):plt.figure(figsize=(10, 2))for i in range(10):plt.subplot(1, 10, i + 1)plt.imshow(images[i].reshape(28, 28), cmap='gray')plt.title(labels[i])plt.axis('off')plt.suptitle(title)plt.show()# 顯示過采樣后的圖像
plot_sampled_images(x_resampled[:10], y_resampled[:10], "Over-sampled Images")# 顯示欠采樣后的圖像
plot_sampled_images(x_undersampled[:10], y_undersampled[:10], "Under-sampled Images")

模型結構層面

簡化模型

選擇更簡單的模型結構或減少模型的復雜度,可以有效減少過擬合。例如,減少神經網絡的層數或神經元數量

## 模型結構層面# 1. 簡化模型
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.keras.datasets import mnist
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.callbacks import EarlyStopping# 加載 MNIST 數據集
(x_train, y_train), (x_test, y_test) = mnist.load_data()# 數據預處理
x_train = x_train.astype('float32') / 255.0
x_test = x_test.astype('float32') / 255.0
x_train = x_train.reshape(-1, 28 * 28)
x_test = x_test.reshape(-1, 28 * 28)# 構建簡化模型
model = Sequential()
model.add(Dense(64, activation='relu', input_shape=(28 * 28,)))  # 較少的神經元
model.add(Dense(10, activation='softmax'))# 編譯模型
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])# 訓練模型
history_simple = model.fit(x_train, y_train,validation_split=0.2,epochs=50,batch_size=128
)# 可視化訓練過程
def plot_training_history(history, title):plt.figure(figsize=(12, 4))# 繪制訓練和驗證的損失plt.subplot(1, 2, 1)plt.plot(history.history['loss'], label='Training Loss')plt.plot(history.history['val_loss'], label='Validation Loss')plt.title(f'Training and Validation Loss ({title})')plt.xlabel('Epochs')plt.ylabel('Loss')plt.legend()# 繪制訓練和驗證的準確率plt.subplot(1, 2, 2)plt.plot(history.history['accuracy'], label='Training Accuracy')plt.plot(history.history['val_accuracy'], label='Validation Accuracy')plt.title(f'Training and Validation Accuracy ({title})')plt.xlabel('Epochs')plt.ylabel('Accuracy')plt.legend()plt.tight_layout()plt.show()# 調用可視化函數
plot_training_history(history_simple, "Simple Model")

添加正則化層

在模型中添加正則化層(如 Dropout 或 L1/L2 正則化),可以減少模型對訓練數據的依賴

# 2. 添加正則化層from tensorflow.keras.regularizers import l2
from tensorflow.keras.layers import Dropout
from tensorflow.keras.layers import Dense
from tensorflow.keras.datasets import mnist
from tensorflow.keras.models import Sequential
import matplotlib.pyplot as plt# 加載 MNIST 數據集
(x_train, y_train), (x_test, y_test) = mnist.load_data()# 數據預處理
x_train = x_train.astype('float32') / 255.0
x_test = x_test.astype('float32') / 255.0
x_train = x_train.reshape(-1, 28 * 28)
x_test = x_test.reshape(-1, 28 * 28)# 構建帶有正則化層的模型
model = Sequential()
model.add(Dense(256, activation='relu', kernel_regularizer=l2(0.01), input_shape=(28 * 28,)))  # L2 正則化
model.add(Dropout(0.5))  # Dropout
model.add(Dense(128, activation='relu', kernel_regularizer=l2(0.01)))
model.add(Dropout(0.5))
model.add(Dense(10, activation='softmax'))# 編譯模型
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])# 訓練模型
history_regularized = model.fit(x_train, y_train,validation_split=0.2,epochs=50,batch_size=128
)# 可視化訓練過程
def plot_training_history(history, title):plt.figure(figsize=(12, 4))# 繪制訓練和驗證的損失plt.subplot(1, 2, 1)plt.plot(history.history['loss'], label='Training Loss')plt.plot(history.history['val_loss'], label='Validation Loss')plt.title(f'Training and Validation Loss ({title})')plt.xlabel('Epochs')plt.ylabel('Loss')plt.legend()# 繪制訓練和驗證的準確率plt.subplot(1, 2, 2)plt.plot(history.history['accuracy'], label='Training Accuracy')plt.plot(history.history['val_accuracy'], label='Validation Accuracy')plt.title(f'Training and Validation Accuracy ({title})')plt.xlabel('Epochs')plt.ylabel('Accuracy')plt.legend()plt.tight_layout()plt.show()# 可視化訓練過程
plot_training_history(history_regularized, "Regularized Model")

早停法(Early Stopping)

早停法通過在訓練過程中監控驗證集的損失,當驗證集的損失不再下降時停止訓練,從而避免過擬合

# 3. 早停法(Early Stopping)from tensorflow.keras.callbacks import EarlyStopping
from tensorflow.keras.datasets import mnist
from tensorflow.keras.layers import Dense
from tensorflow.keras.models import Sequential
import matplotlib.pyplot as plt# 加載 MNIST 數據集
(x_train, y_train), (x_test, y_test) = mnist.load_data()# 數據預處理
x_train = x_train.astype('float32') / 255.0
x_test = x_test.astype('float32') / 255.0
x_train = x_train.reshape(-1, 28 * 28)
x_test = x_test.reshape(-1, 28 * 28)# 構建模型
model = Sequential()
model.add(Dense(256, activation='relu', input_shape=(28 * 28,)))
model.add(Dense(128, activation='relu'))
model.add(Dense(10, activation='softmax'))# 編譯模型
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])# 設置早停法
early_stopping = EarlyStopping(monitor='val_loss', patience=5, restore_best_weights=True)# 訓練模型
history_early_stopping = model.fit(x_train, y_train,validation_split=0.2,epochs=50,batch_size=128,callbacks=[early_stopping]
)# 可視化訓練過程
def plot_training_history(history, title):plt.figure(figsize=(12, 4))# 繪制訓練和驗證的損失plt.subplot(1, 2, 1)plt.plot(history.history['loss'], label='Training Loss')plt.plot(history.history['val_loss'], label='Validation Loss')plt.title(f'Training and Validation Loss ({title})')plt.xlabel('Epochs')plt.ylabel('Loss')plt.legend()# 繪制訓練和驗證的準確率plt.subplot(1, 2, 2)plt.plot(history.history['accuracy'], label='Training Accuracy')plt.plot(history.history['val_accuracy'], label='Validation Accuracy')plt.title(f'Training and Validation Accuracy ({title})')plt.xlabel('Epochs')plt.ylabel('Accuracy')plt.legend()plt.tight_layout()plt.show()# 可視化訓練過程
plot_training_history(history_early_stopping, "Early Stopping")

訓練過程層面

使用交叉驗證

交叉驗證可以更好地評估模型的泛化能力,避免模型對特定訓練集的過擬合

## 訓練過程層面# 1. 使用交叉驗證
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.keras.datasets import mnist
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from sklearn.model_selection import KFold# 加載 MNIST 數據集
(x_train, y_train), (x_test, y_test) = mnist.load_data()# 數據預處理
x_train = x_train.astype('float32') / 255.0
x_test = x_test.astype('float32') / 255.0
x_train = x_train.reshape(-1, 28 * 28)
x_test = x_test.reshape(-1, 28 * 28)# 定義模型
def create_model():model = Sequential()model.add(Dense(256, activation='relu', input_shape=(28 * 28,)))model.add(Dense(128, activation='relu'))model.add(Dense(10, activation='softmax'))model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])return model# K 折交叉驗證
kf = KFold(n_splits=5, shuffle=True, random_state=42)
fold_no = 1
accuracies = []for train_index, val_index in kf.split(x_train):print(f'Training on fold {fold_no}...')x_train_fold, x_val_fold = x_train[train_index], x_train[val_index]y_train_fold, y_val_fold = y_train[train_index], y_train[val_index]model = create_model()model.fit(x_train_fold, y_train_fold, epochs=10, batch_size=128, verbose=0)scores = model.evaluate(x_val_fold, y_val_fold, verbose=0)accuracies.append(scores[1])print(f'Score for fold {fold_no}: {model.metrics_names[0]} of {scores[0]}; {model.metrics_names[1]} of {scores[1] * 100}%')fold_no += 1# 輸出交叉驗證的平均準確率
print(f'Average accuracy: {np.mean(accuracies) * 100}%') # 97.5766670703888%

使用集成學習

集成學習通過組合多個模型來提高模型的泛化能力,減少過擬合

# 2. 使用集成學習from sklearn.ensemble import VotingClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
from tensorflow.keras.datasets import mnist
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score# 加載 MNIST 數據集
(x_train, y_train), (x_test, y_test) = mnist.load_data()# 數據預處理
x_train = x_train.astype('float32') / 255.0
x_test = x_test.astype('float32') / 255.0
x_train = x_train.reshape(-1, 28 * 28)
x_test = x_test.reshape(-1, 28 * 28)# 定義多個模型
model1 = LogisticRegression(max_iter=1000, random_state=42)
model2 = SVC(probability=True, random_state=42)
model3 = RandomForestClassifier(random_state=42)# 創建集成模型
ensemble_model = VotingClassifier(estimators=[('lr', model1), ('svc', model2), ('rf', model3)], voting='soft')# 訓練集成模型
ensemble_model.fit(x_train, y_train)# 預測并評估
y_pred = ensemble_model.predict(x_test)
accuracy = accuracy_score(y_test, y_pred)
print(f'Ensemble model accuracy: {accuracy * 100}%')   # 97.21%

調整學習率

適當調整學習率可以避免模型在訓練過程中過度擬合訓練數據

# 3. 調整學習率
from tensorflow.keras.callbacks import ReduceLROnPlateau
from tensorflow.keras.layers import Dense
import matplotlib.pyplot as plt
from tensorflow.keras.datasets import mnist
from tensorflow.keras.models import Sequential# 加載 MNIST 數據集
(x_train, y_train), (x_test, y_test) = mnist.load_data()# 數據預處理
x_train = x_train.astype('float32') / 255.0
x_test = x_test.astype('float32') / 255.0
x_train = x_train.reshape(-1, 28 * 28)
x_test = x_test.reshape(-1, 28 * 28)# 定義模型
model = Sequential()
model.add(Dense(256, activation='relu', input_shape=(28 * 28,)))
model.add(Dense(128, activation='relu'))
model.add(Dense(10, activation='softmax'))
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])# 設置動態調整學習率
reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.5, patience=3, min_lr=0.00001)# 訓練模型
history = model.fit(x_train, y_train,validation_split=0.2,epochs=50,batch_size=128,callbacks=[reduce_lr]
)# 可視化訓練過程
def plot_training_history(history, title):plt.figure(figsize=(12, 4))# 繪制訓練和驗證的損失plt.subplot(1, 2, 1)plt.plot(history.history['loss'], label='Training Loss')plt.plot(history.history['val_loss'], label='Validation Loss')plt.title(f'Training and Validation Loss ({title})')plt.xlabel('Epochs')plt.ylabel('Loss')plt.legend()# 繪制訓練和驗證的準確率plt.subplot(1, 2, 2)plt.plot(history.history['accuracy'], label='Training Accuracy')plt.plot(history.history['val_accuracy'], label='Validation Accuracy')plt.title(f'Training and Validation Accuracy ({title})')plt.xlabel('Epochs')plt.ylabel('Accuracy')plt.legend()plt.tight_layout()plt.show()# 可視化訓練過程
plot_training_history(history, "Dynamic Learning Rate")

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/web/88514.shtml
繁體地址,請注明出處:http://hk.pswp.cn/web/88514.shtml
英文地址,請注明出處:http://en.pswp.cn/web/88514.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

持有對象-泛型和類型安全的容器

我們需要管理一批對象序列&#xff0c;但是又對實際運行的時候的對象類型和對象序列長度不確定的時候&#xff0c;用簡單的對象引用無法滿足&#xff0c;java有ArrayList,Map,Set等這些容器類提供&#xff0c;這些都實現了Collections接口&#xff0c;所以都屬于Collections類。…

《財稅企業經營管理秘籍(一):行業適配的獲客方式》

在財稅服務這片競爭激烈的紅海中&#xff0c;客戶資源如同氧氣——沒有它&#xff0c;企業寸步難行。然而殘酷的現實是&#xff0c;許多財稅企業正深陷“獲客泥潭”&#xff1a;投入巨大精力與成本&#xff0c;換來的卻是轉化渺茫、增長停滯的困境。高質量線索&#xff0c;已成…

使用tensorflow的多項式回歸的例子(一)

多項式回歸例1%matplotlib inlineimport tensorflow as tfimport numpy as npimport matplotlib.pyplot as plttrX np.linspace(-1, 1, 101)num_coeffs 6trY_coeffs [1, 2, 3, 4, 5, 6]trY 0for i in range(num_coeffs):trY trY_coeffs[i] * np.power(trX, i)trY np.rand…

STM32F103C8T6基于HAL庫驅動NB-IoT模塊BC26通信詳 解

一、引言&#xff1a; NB-IoT技術與應用場景NB-IoT&#xff08; Narrow Band Internet of Things &#xff09;作為低功耗廣域網&#xff08; LPWAN &#xff09;的核心技術&#xff0c;以其廣覆 蓋、低功耗、大連接、低成本的特性&#xff0c;廣泛應用于智能表計、環境監測、…

iOS 性能測試工具全流程:主流工具實戰對比與適用場景

在iOS開發中&#xff0c;性能優化往往被安排到開發后期&#xff0c;甚至上線前才臨時補救。但性能瓶頸通常是架構設計、資源加載、動畫機制等多方面共同作用的結果&#xff0c;僅憑肉眼感知和log輸出&#xff0c;難以精準定位。 一套合適的性能測試工具組合&#xff0c;不僅能幫…

目標檢測:視覺系統中的CNN-Transformer融合網絡

一、背景 無人機&#xff08;UAVs&#xff09;在城市自動巡邏中發揮著重要作用&#xff0c;但它們在圖像識別方面面臨挑戰&#xff0c;尤其是小目標檢測和目標遮擋問題。此外&#xff0c;無人機的高速飛行要求檢測系統具備實時處理能力。 為解決這些問題&#xff0c;我們提出了…

揭示宇宙的隱藏對稱性:群論-AI云計算拓展核心內容

通過利用云計算&#xff0c;借助群論對宇宙對稱性的探索&#xff0c;從離散群和李群等基礎概念&#xff0c;逐步深入到量子力學和更高自旋系統中的高級應用。 對稱性遠不止是美學上的吸引力&#xff1b;它是編織在宇宙結構中的一個基本原則。從雪花的復雜圖案到控制粒子的基本定…

前端項目vue3項目集成eslint@9.x跟prettier

tips: 這些涉及編輯器的修改不一定能及時生效&#xff0c;如果沒有生效&#xff0c;可以試試重啟編輯器窗口 編輯器集成 我的編輯器是vscode&#xff0c;需要安裝這兩個編輯器插件eslint prettier我這個配置主要是通過eslint提供的配置cli命令生成&#xff0c;在里面加入了對pr…

登錄超時問題的排查方法與預防經驗分享

??一、排查方法????檢查網絡連接??確保網絡穩定&#xff0c;嘗試重啟路由器或切換網絡&#xff08;如從WiFi切換到移動數據&#xff09;。使用命令&#xff08;如 ping 或 traceroute&#xff09;測試網絡連通性&#xff0c;排查是否存在丟包或高延遲。??驗證服務端狀…

uniapp,Anroid10+版本如何保存圖片并刪除

Android 10系統開始 進一步增強了平臺功能&#xff0c;為外部存儲設備上的應用和用戶數據提供了更好的保護。作為這項工作的一部分&#xff0c;平臺引入了進一步的改進&#xff0c;以簡化向分區存儲的轉換。 為了讓用戶更好地控制自己的文件&#xff0c;保護用戶隱私數據&#…

Jenkins Pipeline 語法

Pipeline 簡介 Jenkins2.x 的核心是使用 pipeline 來構建項目,也就是流水線,將 Jenkins1.0 版本中基于表單的配置信息比如 JDK/SVN 以及參數的配置都轉變成了代碼,即 pipeline as Code。 傳統的表單方式有以下缺點: 需要大量的 web 表單交互,有時候需要進行很多次的切換…

搭建滲透測試環境

一、基于docker搭建靶場 #此步驟需要科學上網 #從軟件源中下載 docker.io 和 docker -compose 軟件包及其依賴項。 sudo apt-get install docker.io docker-compose #查看docker版本 docker -v #查看docker信息 docker info #重啟docker服務 sudo systemctl daemon-reload sudo…

(一)OpenCV——噪聲去除(降噪)

高斯濾波器&#xff08;針對高斯噪聲&#xff09; 高斯噪聲是指它的概率密度函數服從高斯分布&#xff08;即正態分布&#xff09;的一類噪聲。常見的高斯噪聲包括起伏噪聲、宇宙噪聲、熱噪聲和散粒噪聲等等。 高斯濾波(Gaussian filter) 包含許多種&#xff0c;包括低通、帶…

百度開源文心 4.5 系列開源大模型 GitCode 本地化部署,硅基流動:文心 vs. DeepSeek vs. Qwen 3.0 深度測評

百度開源文心 4.5 系列開源大模型 GitCode 本地化部署&#xff0c;硅基流動&#xff1a;文心 vs. DeepSeek vs. Qwen 3.0 深度測評 文章目錄百度開源文心 4.5 系列開源大模型 GitCode 本地化部署&#xff0c;硅基流動&#xff1a;文心 vs. DeepSeek vs. Qwen 3.0 深度測評背景百…

「日拱一碼」022 機器學習——數據劃分

目錄 基于單次隨機劃分的方法 普通單次隨機劃分&#xff08;train_test_split&#xff09; 分層單次隨機劃分(使用 train_test_split 的 stratify 參數) 基于多次隨機劃分的方法 普通多次隨機劃分(ShuffleSplit) 分層多次隨機劃分&#xff08;StratifiedShuffleSplit…

lora網關

所需配置的引腳&#xff0c;SPI傳輸&#xff0c;PG13復位&#xff08;輸出引腳&#xff0c;推挽輸出&#xff09;&#xff0c;PE2忙碌&#xff08;輸入引腳&#xff0c;浮空輸入&#xff09;PE6PE5輸出。若利用延時處理按鍵消抖&#xff0c;hal庫里用systick中斷實現延時&#…

5G IMS注冊關鍵一步:UE如何通過ePCO獲取P-CSCF地址

看似簡單的P-CSCF地址傳遞,背后是5G核心網控制面與用戶面的精密協作。ePCO作為高效的信令載體,承載著IMS業務觸達的第一把鑰匙。 在5G網絡中建立IMS PDN連接時,UE(用戶設備)獲取P-CSCF(Proxy-Call Session Control Function)地址是IMS業務(如VoLTE、VoNR)成功注冊和運…

JVM方法區的運行時常量區到底存儲哪些數據?

JDK8以后&#xff0c;運行時常量池邏輯上屬于方法區&#xff1b;但&#xff1a; 其中的字符串常量池實際位置移至到了java堆&#xff1b;其中一些符號引用也存儲到了元空間&#xff1b;字符串常量池&#xff0c;元空間&#xff0c;運行時常量區的具體關系請看這篇博客&#xf…

Go defer(二):從匯編的角度理解延遲調用的實現

Go的延遲調用機制會在當前函數返回前執行傳入的函數&#xff0c;它會經常被用于關閉文件描述符、關閉數據庫連接以及解鎖資源。之前的文章&#xff08; Go defer&#xff08;一&#xff09;&#xff1a;延遲調用的使用及其底層實現原理詳解 &#xff09;詳細介紹了defer的使用以…

Android 12系統源碼_分屏模式(一)從最近任務觸發分屏模式

前言 打開MainActivity&#xff0c;然后進入最近任務觸發分屏&#xff0c;可以成功進入分屏模式。 本篇文章我們來具體梳理一下這個過程的源碼調用流程。 一 launcher3階段 1.1 源碼 //packages/apps/Launcher3/quickstep/src/com/android/quickstep/views/TaskView.java publi…