国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

首頁 后端開發(fā) Python教程 使用 VGG 進(jìn)行人臉和性別識別

使用 VGG 進(jìn)行人臉和性別識別

Nov 06, 2024 am 10:45 AM

Using VGGfor face and gender recognition

如何使用深度學(xué)習(xí)和 VGG16 構(gòu)建人臉和性別識別 Python 項(xiàng)目。

什么是深度學(xué)習(xí)?

深度學(xué)習(xí)是機(jī)器學(xué)習(xí)的一個(gè)子類別,是一種三層或多層的神經(jīng)網(wǎng)絡(luò)。這些神經(jīng)網(wǎng)絡(luò)試圖通過從大量數(shù)據(jù)中學(xué)習(xí)來模擬人腦的行為。雖然單層神經(jīng)網(wǎng)絡(luò)仍然可以做出近似預(yù)測,但額外的隱藏層可以幫助優(yōu)化和細(xì)化準(zhǔn)確性。

深度學(xué)習(xí)通過在無需人工干預(yù)的情況下執(zhí)行任務(wù)來提高自動(dòng)化程度。深度學(xué)習(xí)可以在數(shù)字助理、語音電視遙控器、信用卡欺詐檢測和自動(dòng)駕駛汽車中找到。

構(gòu)建 Python 項(xiàng)目

** 在 GitHub 上查看完整代碼:https://github.com/alexiacismaru/face-recognision

下載用于人臉檢測的VGG16人臉數(shù)據(jù)集和Haar Cascade XML文件,該文件將用于人臉識別任務(wù)中的預(yù)處理。

faceCascade = cv2.CascadeClassifier(os.path.join(base_path, "haarcascade_frontal_face_default.xml")) # haar cascade detects faces in images

vgg_face_dataset_url = "http://www.robots.ox.ac.uk/~vgg/data/vgg_face/vgg_face_dataset.tar.gz"

with request.urlopen(vgg_face_dataset_url) as r, open(os.path.join(base_path, "vgg_face_dataset.tar.gz"), 'wb') as f:
  f.write(r.read())

# extract VGG dataset
with tarfile.open(os.path.join(base_path, "vgg_face_dataset.tar.gz")) as f:
  f.extractall(os.path.join(base_path))

# download Haar Cascade for face detection
trained_haarcascade_url = "https://raw.githubusercontent.com/opencv/opencv/master/data/haarcascades/haarcascade_frontalface_default.xml"
with request.urlopen(trained_haarcascade_url) as r, open(os.path.join(base_path, "haarcascade_frontalface_default.xml"), 'wb') as f:
    f.write(r.read())

從 VGG 人臉數(shù)據(jù)集中選擇性地加載和處理一組預(yù)定義主題的特定數(shù)量的圖像。

# populate the list with the files of the celebrities that will be used for face recognition
all_subjects = [subject for subject in sorted(os.listdir(os.path.join(base_path, "vgg_face_dataset", "files"))) if subject.startswith("Jesse_Eisenberg") or subject.startswith("Sarah_Hyland") or subject.startswith("Michael_Cera") or subject.startswith("Mila_Kunis") and subject.endswith(".txt")]

# define number of subjects and how many pictures to extract
nb_subjects = 4
nb_images_per_subject = 40

通過打開與主題關(guān)聯(lián)的文本文件并閱讀內(nèi)容來迭代每個(gè)主題的文件。這些文件中的每一行都包含一個(gè)圖像的 URL。對于每個(gè) URL(指向圖像),代碼嘗試使用 urllib 加載圖像并將其轉(zhuǎn)換為 NumPy 數(shù)組。

images = []

for subject in all_subjects[:nb_subjects]:
  with open(os.path.join(base_path, "vgg_face_dataset", "files", subject), 'r') as f:
    lines = f.readlines()

  images_ = []
  for line in lines:
    url = line[line.find("http://"): line.find(".jpg") + 4]

    try:
      res = request.urlopen(url)
      img = np.asarray(bytearray(res.read()), dtype="uint8")
      # convert the image data into a format suitable for OpenCV
      # images are colored 
      img = cv2.imdecode(img, cv2.IMREAD_COLOR)
      h, w = img.shape[:2]
      images_.append(img)
      cv2_imshow(cv2.resize(img, (w // 5, h // 5)))

    except:
      pass

    # check if the required number of images has been reached
    if len(images_) == nb_images_per_subject:
      # add the list of images to the main images list and move to the next subject
      images.append(images_)
      break

人臉檢測設(shè)置

Using VGGfor face and gender recognition

  1. 找到圖像中的一張或多張面孔并將其放入框中。
  2. 確保人臉與數(shù)據(jù)庫一致,例如幾何、光度等。
  3. 從面部提取可用于識別任務(wù)的特征。
  4. 將面孔與準(zhǔn)備好的數(shù)據(jù)庫中的一張或多張已知面孔進(jìn)行匹配。
# create arrays for all 4 celebrities
jesse_images = []
michael_images = []
mila_images = []
sarah_images = []

faceCascade = cv2.CascadeClassifier(os.path.join(base_path, "haarcascade_frontalface_default.xml"))

# iterate over the subjects
for subject, images_ in zip(all_subjects, images):

  # create a grayscale copy to simplify the image and reduce computation
  for img in images_:
    img_ = img.copy()
    img_gray = cv2.cvtColor(img_, cv2.COLOR_BGR2GRAY)
    faces = faceCascade.detectMultiScale(
        img_gray,
        scaleFactor=1.2,
        minNeighbors=5,
        minSize=(30, 30),
        flags=cv2.CASCADE_SCALE_IMAGE
    )
    print("Found {} face(s)!".format(len(faces)))

    for (x, y, w, h) in faces:
        cv2.rectangle(img_, (x, y), (x+w, y+h), (0, 255, 0), 10)

    h, w = img_.shape[:2]
    resized_img = cv2.resize(img_, (224, 224))
    cv2_imshow(resized_img)

    if "Jesse_Eisenberg" in subject:
        jesse_images.append(resized_img)
    elif "Michael_Cera" in subject:
        michael_images.append(resized_img)
    elif "Mila_Kunis" in subject:
        mila_images.append(resized_img)
    elif "Sarah_Hyland" in subject:
        sarah_images.append(resized_img)

detectMultiScale 方法可識別圖像中的人臉。然后,它返回它認(rèn)為人臉?biāo)诘木匦蔚淖鴺?biāo)。對于圖像中的每張臉,都會(huì)在其周圍繪制一個(gè)矩形,指示該臉的位置。每個(gè)圖像的大小都調(diào)整為 224x224 像素。

將數(shù)據(jù)集拆分為訓(xùn)練集和驗(yàn)證集:

  • 訓(xùn)練集用于訓(xùn)練機(jī)器學(xué)習(xí)模型。它用于學(xué)習(xí)數(shù)據(jù)中的模式、特征和關(guān)系。該模型調(diào)整其參數(shù)以最大限度地減少對訓(xùn)練數(shù)據(jù)進(jìn)行的預(yù)測或分類的錯(cuò)誤。
  • 驗(yàn)證集評估模型在一組新數(shù)據(jù)上的性能。這有助于檢查模型對未見過的數(shù)據(jù)的泛化程度。驗(yàn)證集應(yīng)該是在模型訓(xùn)練期間不使用的獨(dú)立集。在訓(xùn)練期間混合/使用驗(yàn)證集中的信息可能會(huì)導(dǎo)致結(jié)果出現(xiàn)偏差。
faceCascade = cv2.CascadeClassifier(os.path.join(base_path, "haarcascade_frontal_face_default.xml")) # haar cascade detects faces in images

vgg_face_dataset_url = "http://www.robots.ox.ac.uk/~vgg/data/vgg_face/vgg_face_dataset.tar.gz"

with request.urlopen(vgg_face_dataset_url) as r, open(os.path.join(base_path, "vgg_face_dataset.tar.gz"), 'wb') as f:
  f.write(r.read())

# extract VGG dataset
with tarfile.open(os.path.join(base_path, "vgg_face_dataset.tar.gz")) as f:
  f.extractall(os.path.join(base_path))

# download Haar Cascade for face detection
trained_haarcascade_url = "https://raw.githubusercontent.com/opencv/opencv/master/data/haarcascades/haarcascade_frontalface_default.xml"
with request.urlopen(trained_haarcascade_url) as r, open(os.path.join(base_path, "haarcascade_frontalface_default.xml"), 'wb') as f:
    f.write(r.read())

數(shù)據(jù)增強(qiáng)

深度學(xué)習(xí)模型的準(zhǔn)確性取決于訓(xùn)練數(shù)據(jù)的質(zhì)量、數(shù)量和上下文含義。這是構(gòu)建深度學(xué)習(xí)模型時(shí)最常見的挑戰(zhàn)之一,而且成本高昂且耗時(shí)。公司使用數(shù)據(jù)增強(qiáng)來減少對訓(xùn)練示例的依賴,以快速構(gòu)建高精度模型。

數(shù)據(jù)增強(qiáng)是指通過從現(xiàn)有數(shù)據(jù)生成新數(shù)據(jù)點(diǎn)來人為地增加數(shù)據(jù)量。這包括對數(shù)據(jù)添加微小的更改或使用機(jī)器學(xué)習(xí)模型在原始數(shù)據(jù)的潛在空間中生成新的數(shù)據(jù)點(diǎn)以放大數(shù)據(jù)集。

合成數(shù)據(jù)代表不使用真實(shí)世界圖像的人工生成的數(shù)據(jù),由生成對抗網(wǎng)絡(luò)生成。

增強(qiáng)源自原始圖像,并進(jìn)行某種微小的幾何變換(例如翻轉(zhuǎn)、平移、旋轉(zhuǎn)或添加噪聲),以增加訓(xùn)練集的多樣性。

# populate the list with the files of the celebrities that will be used for face recognition
all_subjects = [subject for subject in sorted(os.listdir(os.path.join(base_path, "vgg_face_dataset", "files"))) if subject.startswith("Jesse_Eisenberg") or subject.startswith("Sarah_Hyland") or subject.startswith("Michael_Cera") or subject.startswith("Mila_Kunis") and subject.endswith(".txt")]

# define number of subjects and how many pictures to extract
nb_subjects = 4
nb_images_per_subject = 40

數(shù)據(jù)增強(qiáng)通過更多樣化的數(shù)據(jù)集提高了機(jī)器學(xué)習(xí)模型的性能,并降低了與數(shù)據(jù)收集相關(guān)的運(yùn)營成本:

  • 左右翻轉(zhuǎn):圖像以 0.7 的概率隨機(jī)水平翻轉(zhuǎn)。這模擬了由于圖像中主體的不同方向而導(dǎo)致的變化。
  • 旋轉(zhuǎn):圖像以 0.7 的概率輕微旋轉(zhuǎn)(雙向最多 10 度)。這通過模擬不同的頭部姿勢增加了數(shù)據(jù)集的可變性。
  • 灰度轉(zhuǎn)換:以0.1的概率將圖像轉(zhuǎn)換為灰度。這確保了模型可以處理圖像并從圖像中學(xué)習(xí),而不管其顏色信息如何。
  • 采樣:sample(50) 方法從原始集合中生成 50 個(gè)增強(qiáng)圖像。這擴(kuò)展了數(shù)據(jù)集,為模型提供了更多可供學(xué)習(xí)的數(shù)據(jù)。

實(shí)施 VGG16 模型

VGG16是一種廣泛用于圖像識別的卷積神經(jīng)網(wǎng)絡(luò)。它被認(rèn)為是最好的計(jì)算機(jī)視覺模型架構(gòu)之一。它由 16 層人工神經(jīng)元組成,可以增量處理圖像以提高準(zhǔn)確性。在VGG16中,“VGG”指的是牛津大學(xué)視覺幾何小組,而“16”指的是網(wǎng)絡(luò)的16個(gè)加權(quán)層

VGG16用于圖像識別和新圖像分類。 VGG16 網(wǎng)絡(luò)的預(yù)訓(xùn)練版本是在 ImageNet 視覺數(shù)據(jù)庫中超過一百萬張圖像上進(jìn)行訓(xùn)練的。 VGG16 可用于判斷圖像是否包含某些物品、動(dòng)物、植物等。

VGG16架構(gòu)

Using VGGfor face and gender recognition

有 13 個(gè)卷積層、5 個(gè) Max Pooling 層和 3 個(gè) Dense 層。這導(dǎo)致 21 個(gè)層具有 16 個(gè)權(quán)重,這意味著它有 16 個(gè)可學(xué)習(xí)參數(shù)層。 VGG16 將輸入張量大小設(shè)為 224x244。該模型側(cè)重于具有步幅為 1 的 3x3 濾波器的卷積層。它始終使用與步幅為 2 的 2x2 濾波器的 maxpool 層相同的填充。

Conv-1 層有 64 個(gè)過濾器,Conv-2 有 128 個(gè)過濾器,Conv-3 有 256 個(gè)過濾器,Conv 4 和 Conv 5 有 512 個(gè)過濾器,以及三個(gè)全連接層,其中前兩個(gè)層各有 4096 個(gè)通道,第三個(gè)層各有 4096 個(gè)通道執(zhí)行 1000 路 ILSVRC 分類并包含 1000 個(gè)通道(每個(gè)類別一個(gè))。最后一層是 soft-max 層。

開始準(zhǔn)備基礎(chǔ)模型。

faceCascade = cv2.CascadeClassifier(os.path.join(base_path, "haarcascade_frontal_face_default.xml")) # haar cascade detects faces in images

vgg_face_dataset_url = "http://www.robots.ox.ac.uk/~vgg/data/vgg_face/vgg_face_dataset.tar.gz"

with request.urlopen(vgg_face_dataset_url) as r, open(os.path.join(base_path, "vgg_face_dataset.tar.gz"), 'wb') as f:
  f.write(r.read())

# extract VGG dataset
with tarfile.open(os.path.join(base_path, "vgg_face_dataset.tar.gz")) as f:
  f.extractall(os.path.join(base_path))

# download Haar Cascade for face detection
trained_haarcascade_url = "https://raw.githubusercontent.com/opencv/opencv/master/data/haarcascades/haarcascade_frontalface_default.xml"
with request.urlopen(trained_haarcascade_url) as r, open(os.path.join(base_path, "haarcascade_frontalface_default.xml"), 'wb') as f:
    f.write(r.read())

為了確保模型能夠正確分類圖像,我們需要使用額外的層來擴(kuò)展模型。

# populate the list with the files of the celebrities that will be used for face recognition
all_subjects = [subject for subject in sorted(os.listdir(os.path.join(base_path, "vgg_face_dataset", "files"))) if subject.startswith("Jesse_Eisenberg") or subject.startswith("Sarah_Hyland") or subject.startswith("Michael_Cera") or subject.startswith("Mila_Kunis") and subject.endswith(".txt")]

# define number of subjects and how many pictures to extract
nb_subjects = 4
nb_images_per_subject = 40

全局平均池化 2D 層將從 VGG16 獲得的特征圖壓縮為每個(gè)圖的單個(gè) 1D 向量。它簡化了輸出并減少了參數(shù)總數(shù),有助于防止過度擬合。

密集層是添加的一系列完全連接(密集)層。每層包含指定數(shù)量的單元(1024、512 和 256),這些單元是根據(jù)常見實(shí)踐和實(shí)驗(yàn)選擇的。這些層進(jìn)一步處理 VGG16 提取的特征。

最后的密集層(輸出層)使用適合二元分類的 sigmoid 激活(我們的兩個(gè)類是“女性”和“男性”)。

亞當(dāng)優(yōu)化

Adam 優(yōu)化算法是隨機(jī)梯度下降過程的擴(kuò)展,用于根據(jù)訓(xùn)練數(shù)據(jù)迭代更新網(wǎng)絡(luò)權(quán)重。當(dāng)處理涉及大量數(shù)據(jù)或參數(shù)的大型問題時(shí),該方法非常有效。它需要更少的內(nèi)存并且效率更高。

該算法結(jié)合了兩種梯度下降方法:動(dòng)量和均方根傳播 (RMSP)。

動(dòng)量是一種算法,用于使用梯度的指數(shù)加權(quán)平均值來幫助加速梯度下降算法。

Using VGGfor face and gender recognition

均方根道具是一種自適應(yīng)學(xué)習(xí)算法,嘗試通過采用“指數(shù)移動(dòng)平均值”來改進(jìn) AdaGrad。

Using VGGfor face and gender recognition

由于 mt 和 vt 都初始化為 0(基于上述方法),因此觀察到它們有“偏向 0”的趨勢,因?yàn)?β1 和 β2 ≈ 1。此優(yōu)化器通過計(jì)算解決了這個(gè)問題“偏差校正”mt 和 vt。這樣做也是為了在達(dá)到全局最小值時(shí)控制權(quán)重,以防止接近它時(shí)出現(xiàn)高振蕩。使用的公式是:

Using VGGfor face and gender recognition

直觀上,我們在每次迭代后適應(yīng)梯度下降,使其在整個(gè)過程中保持受控且無偏差,因此得名 Adam。

現(xiàn)在,我們采用偏差校正權(quán)重參數(shù) (m_hat)t 和 (v_hat)t,而不是正常的權(quán)重參數(shù) mt 和 vt。將它們代入我們的一般方程,我們得到:

Using VGGfor face and gender recognition

來源:Geeksforgeeks,https://www.geeksforgeeks.org/adam-optimizer/

faceCascade = cv2.CascadeClassifier(os.path.join(base_path, "haarcascade_frontal_face_default.xml")) # haar cascade detects faces in images

vgg_face_dataset_url = "http://www.robots.ox.ac.uk/~vgg/data/vgg_face/vgg_face_dataset.tar.gz"

with request.urlopen(vgg_face_dataset_url) as r, open(os.path.join(base_path, "vgg_face_dataset.tar.gz"), 'wb') as f:
  f.write(r.read())

# extract VGG dataset
with tarfile.open(os.path.join(base_path, "vgg_face_dataset.tar.gz")) as f:
  f.extractall(os.path.join(base_path))

# download Haar Cascade for face detection
trained_haarcascade_url = "https://raw.githubusercontent.com/opencv/opencv/master/data/haarcascades/haarcascade_frontalface_default.xml"
with request.urlopen(trained_haarcascade_url) as r, open(os.path.join(base_path, "haarcascade_frontalface_default.xml"), 'wb') as f:
    f.write(r.read())

在深度學(xué)習(xí)環(huán)境中設(shè)置圖像數(shù)據(jù)預(yù)處理、增強(qiáng)和模型訓(xùn)練。

faceCascade = cv2.CascadeClassifier(os.path.join(base_path, "haarcascade_frontal_face_default.xml")) # haar cascade detects faces in images

vgg_face_dataset_url = "http://www.robots.ox.ac.uk/~vgg/data/vgg_face/vgg_face_dataset.tar.gz"

with request.urlopen(vgg_face_dataset_url) as r, open(os.path.join(base_path, "vgg_face_dataset.tar.gz"), 'wb') as f:
  f.write(r.read())

# extract VGG dataset
with tarfile.open(os.path.join(base_path, "vgg_face_dataset.tar.gz")) as f:
  f.extractall(os.path.join(base_path))

# download Haar Cascade for face detection
trained_haarcascade_url = "https://raw.githubusercontent.com/opencv/opencv/master/data/haarcascades/haarcascade_frontalface_default.xml"
with request.urlopen(trained_haarcascade_url) as r, open(os.path.join(base_path, "haarcascade_frontalface_default.xml"), 'wb') as f:
    f.write(r.read())
  • epochs:epochs 的數(shù)量指定整個(gè)訓(xùn)練數(shù)據(jù)集將通過神經(jīng)網(wǎng)絡(luò)向前和向后傳遞多少。該模型將遍歷訓(xùn)練數(shù)據(jù) 10 次。 epoch 是學(xué)習(xí)機(jī)器要學(xué)習(xí)的數(shù)據(jù)集的完整呈現(xiàn)。
  • batch_size:該參數(shù)定義一次通過網(wǎng)絡(luò)傳播的樣本數(shù)量。在這里,我們使用的批量大小為 30,這意味著模型將一次拍攝 30 張圖像,對其進(jìn)行處理,更新權(quán)重,然后繼續(xù)處理下一批 30 張圖像。

模型的性能是通過對驗(yàn)證集進(jìn)行預(yù)測來評估的。這可以讓我們了解模型對未見數(shù)據(jù)的執(zhí)行情況。對這些預(yù)測應(yīng)用閾值,將每個(gè)圖像分類為兩個(gè)類別之一(“男性”或“女性”)。

# populate the list with the files of the celebrities that will be used for face recognition
all_subjects = [subject for subject in sorted(os.listdir(os.path.join(base_path, "vgg_face_dataset", "files"))) if subject.startswith("Jesse_Eisenberg") or subject.startswith("Sarah_Hyland") or subject.startswith("Michael_Cera") or subject.startswith("Mila_Kunis") and subject.endswith(".txt")]

# define number of subjects and how many pictures to extract
nb_subjects = 4
nb_images_per_subject = 40

創(chuàng)建混淆矩陣以可視化準(zhǔn)確性。

images = []

for subject in all_subjects[:nb_subjects]:
  with open(os.path.join(base_path, "vgg_face_dataset", "files", subject), 'r') as f:
    lines = f.readlines()

  images_ = []
  for line in lines:
    url = line[line.find("http://"): line.find(".jpg") + 4]

    try:
      res = request.urlopen(url)
      img = np.asarray(bytearray(res.read()), dtype="uint8")
      # convert the image data into a format suitable for OpenCV
      # images are colored 
      img = cv2.imdecode(img, cv2.IMREAD_COLOR)
      h, w = img.shape[:2]
      images_.append(img)
      cv2_imshow(cv2.resize(img, (w // 5, h // 5)))

    except:
      pass

    # check if the required number of images has been reached
    if len(images_) == nb_images_per_subject:
      # add the list of images to the main images list and move to the next subject
      images.append(images_)
      break

對于二元分類,接收者操作特征 (ROC) 曲線和曲線下面積 (AUC) 對于理解真陽性率和假陽性率之間的權(quán)衡很有用。

# create arrays for all 4 celebrities
jesse_images = []
michael_images = []
mila_images = []
sarah_images = []

faceCascade = cv2.CascadeClassifier(os.path.join(base_path, "haarcascade_frontalface_default.xml"))

# iterate over the subjects
for subject, images_ in zip(all_subjects, images):

  # create a grayscale copy to simplify the image and reduce computation
  for img in images_:
    img_ = img.copy()
    img_gray = cv2.cvtColor(img_, cv2.COLOR_BGR2GRAY)
    faces = faceCascade.detectMultiScale(
        img_gray,
        scaleFactor=1.2,
        minNeighbors=5,
        minSize=(30, 30),
        flags=cv2.CASCADE_SCALE_IMAGE
    )
    print("Found {} face(s)!".format(len(faces)))

    for (x, y, w, h) in faces:
        cv2.rectangle(img_, (x, y), (x+w, y+h), (0, 255, 0), 10)

    h, w = img_.shape[:2]
    resized_img = cv2.resize(img_, (224, 224))
    cv2_imshow(resized_img)

    if "Jesse_Eisenberg" in subject:
        jesse_images.append(resized_img)
    elif "Michael_Cera" in subject:
        michael_images.append(resized_img)
    elif "Mila_Kunis" in subject:
        mila_images.append(resized_img)
    elif "Sarah_Hyland" in subject:
        sarah_images.append(resized_img)

結(jié)論

總之,通過使用深度學(xué)習(xí)和圖像處理算法,您可以構(gòu)建一個(gè) Python 項(xiàng)目來識別人臉并將其分類為男性或女性。

以上是使用 VGG 進(jìn)行人臉和性別識別的詳細(xì)內(nèi)容。更多信息請關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

本站聲明
本文內(nèi)容由網(wǎng)友自發(fā)貢獻(xiàn),版權(quán)歸原作者所有,本站不承擔(dān)相應(yīng)法律責(zé)任。如您發(fā)現(xiàn)有涉嫌抄襲侵權(quán)的內(nèi)容,請聯(lián)系admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費(fèi)脫衣服圖片

Undresser.AI Undress

Undresser.AI Undress

人工智能驅(qū)動(dòng)的應(yīng)用程序,用于創(chuàng)建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用于從照片中去除衣服的在線人工智能工具。

Clothoff.io

Clothoff.io

AI脫衣機(jī)

Video Face Swap

Video Face Swap

使用我們完全免費(fèi)的人工智能換臉工具輕松在任何視頻中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費(fèi)的代碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

功能強(qiáng)大的PHP集成開發(fā)環(huán)境

Dreamweaver CS6

Dreamweaver CS6

視覺化網(wǎng)頁開發(fā)工具

SublimeText3 Mac版

SublimeText3 Mac版

神級代碼編輯軟件(SublimeText3)

熱門話題

Laravel 教程
1601
29
PHP教程
1502
276
如何處理Python中的API身份驗(yàn)證 如何處理Python中的API身份驗(yàn)證 Jul 13, 2025 am 02:22 AM

處理API認(rèn)證的關(guān)鍵在于理解并正確使用認(rèn)證方式。1.APIKey是最簡單的認(rèn)證方式,通常放在請求頭或URL參數(shù)中;2.BasicAuth使用用戶名和密碼進(jìn)行Base64編碼傳輸,適合內(nèi)部系統(tǒng);3.OAuth2需先通過client_id和client_secret獲取Token,再在請求頭中帶上BearerToken;4.為應(yīng)對Token過期,可封裝Token管理類自動(dòng)刷新Token;總之,根據(jù)文檔選擇合適方式,并安全存儲(chǔ)密鑰信息是關(guān)鍵。

解釋Python斷言。 解釋Python斷言。 Jul 07, 2025 am 12:14 AM

Assert是Python用于調(diào)試的斷言工具,當(dāng)條件不滿足時(shí)拋出AssertionError。其語法為assert條件加可選錯(cuò)誤信息,適用于內(nèi)部邏輯驗(yàn)證如參數(shù)檢查、狀態(tài)確認(rèn)等,但不能用于安全或用戶輸入檢查,且應(yīng)配合清晰提示信息使用,僅限開發(fā)階段輔助調(diào)試而非替代異常處理。

如何一次迭代兩個(gè)列表 如何一次迭代兩個(gè)列表 Jul 09, 2025 am 01:13 AM

在Python中同時(shí)遍歷兩個(gè)列表的常用方法是使用zip()函數(shù),它會(huì)按順序配對多個(gè)列表并以最短為準(zhǔn);若列表長度不一致,可使用itertools.zip_longest()以最長為準(zhǔn)并填充缺失值;結(jié)合enumerate()可同時(shí)獲取索引。1.zip()簡潔實(shí)用,適合成對數(shù)據(jù)迭代;2.zip_longest()處理不一致長度時(shí)可填充默認(rèn)值;3.enumerate(zip())可在遍歷時(shí)獲取索引,滿足多種復(fù)雜場景需求。

什么是Python型提示? 什么是Python型提示? Jul 07, 2025 am 02:55 AM

typeHintsInpyThonsolverbromblemboyofambiguityandPotentialBugSindyNamalytyCodeByallowingDevelopsosteSpecefectifyExpectedTypes.theyenhancereadability,enablellybugdetection,andimprovetool.typehintsupport.typehintsareadsareadsareadsareadsareadsareadsareadsareadsareaddedusidocolon(

什么是Python迭代器? 什么是Python迭代器? Jul 08, 2025 am 02:56 AM

Inpython,IteratorSareObjectSthallowloopingThroughCollectionsByImplementing_iter __()和__next __()。1)iteratorsWiaTheIteratorProtocol,使用__ITER __()toreTurnterateratoratoranteratoratoranteratoratorAnterAnteratoratorant antheittheext__()

Python Fastapi教程 Python Fastapi教程 Jul 12, 2025 am 02:42 AM

要使用Python創(chuàng)建現(xiàn)代高效的API,推薦使用FastAPI;其基于標(biāo)準(zhǔn)Python類型提示,可自動(dòng)生成文檔,性能優(yōu)越。安裝FastAPI和ASGI服務(wù)器uvicorn后,即可編寫接口代碼。通過定義路由、編寫處理函數(shù)并返回?cái)?shù)據(jù),可以快速構(gòu)建API。FastAPI支持多種HTTP方法,并提供自動(dòng)生成的SwaggerUI和ReDoc文檔系統(tǒng)。URL參數(shù)可通過路徑定義捕獲,查詢參數(shù)則通過函數(shù)參數(shù)設(shè)置默認(rèn)值實(shí)現(xiàn)。合理使用Pydantic模型有助于提升開發(fā)效率和準(zhǔn)確性。

如何用Python測試API 如何用Python測試API Jul 12, 2025 am 02:47 AM

要測試API需使用Python的Requests庫,步驟為安裝庫、發(fā)送請求、驗(yàn)證響應(yīng)、設(shè)置超時(shí)與重試。首先通過pipinstallrequests安裝庫;接著用requests.get()或requests.post()等方法發(fā)送GET或POST請求;然后檢查response.status_code和response.json()確保返回結(jié)果符合預(yù)期;最后可添加timeout參數(shù)設(shè)置超時(shí)時(shí)間,并結(jié)合retrying庫實(shí)現(xiàn)自動(dòng)重試以增強(qiáng)穩(wěn)定性。

Python函數(shù)可變范圍 Python函數(shù)可變范圍 Jul 12, 2025 am 02:49 AM

在Python中,函數(shù)內(nèi)部定義的變量是局部變量,僅在函數(shù)內(nèi)有效;外部定義的是全局變量,可在任何地方讀取。1.局部變量隨函數(shù)執(zhí)行結(jié)束被銷毀;2.函數(shù)可訪問全局變量但不能直接修改,需用global關(guān)鍵字;3.嵌套函數(shù)中若要修改外層函數(shù)變量,需使用nonlocal關(guān)鍵字;4.同名變量在不同作用域互不影響;5.修改全局變量時(shí)必須聲明global,否則會(huì)引發(fā)UnboundLocalError錯(cuò)誤。理解這些規(guī)則有助于避免bug并寫出更可靠的函數(shù)。

See all articles