【2025校招】4399 NLP算法工程师笔试题

news2024/9/21 20:49:35

目录

  • 1. 第一题
  • 2. 第二题
  • 3. 第三题

⏰ 时间:2024/08/19
🔄 输入输出:ACM格式
⏳ 时长:2h

本试卷分为单选,自我评价题,编程题

单选和自我评价这里不再介绍,4399的编程题一如既往地抽象,明明是NLP岗位的笔试题,却考了OpenCV相关的知识。btw,跟网友讨论了下,4399似乎不同时间节点的笔试题是一样的???

1. 第一题

第一题是LC原题:441. 排列硬币,题目和题解请前往LC查看。

2. 第二题

题目描述

请使用OpenCV库编写程序,实现在视频文件中实时追踪一个人手持手机绿幕的四个顶点的坐标。

要求

  1. 使用颜色分割技术检测绿幕区域。(8分)
  2. 使用适当的方法(如轮廓检测)找到绿幕的四个顶点。(10分)
  3. 在视频帧中标记出这四个顶点。(8分)

手机绿幕指:手机屏幕显示全绿色图片,用于后期处理替换为其他界面,绿色范围:lower_green = np.array([35, 100, 100])upper_green = np.array([85, 255, 255])

测试用例

输入:green_screen_track.mp4

输出:带顶点标记的视频序列帧图片


题解

import cv2
import numpy as np

lower_green = np.array([35, 100, 100])
upper_green = np.array([85, 255, 255])

def get_largest_contour(contours):
    """ 获取最大轮廓 """
    max_contour = max(contours, key=cv2.contourArea)
    return max_contour

def get_four_vertices(contour):
    """ 近似轮廓为四边形 """
    epsilon = 0.02 * cv2.arcLength(contour, True)
    approx = cv2.approxPolyDP(contour, epsilon, True)
    if len(approx) == 4:
        return approx.reshape(4, 2)
    else:
        return None

def main(video_path):
    cap = cv2.VideoCapture(video_path)

    while cap.isOpened():
        ret, frame = cap.read()
        if not ret:
            break

        hsv_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
        mask = cv2.inRange(hsv_frame, lower_green, upper_green)
        contours, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

        if contours:
            largest_contour = get_largest_contour(contours)
            vertices = get_four_vertices(largest_contour)

            if vertices is not None:
                for (x, y) in vertices:
                    cv2.circle(frame, (x, y), 5, (0, 0, 255), -1)
                cv2.polylines(frame, [vertices], isClosed=True, color=(0, 255, 0), thickness=2)

        cv2.imshow('Green Screen Tracking', frame)

        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

    cap.release()
    cv2.destroyAllWindows()

if __name__ == "__main__":
    video_path = 'green_screen_track.mp4'
    main(video_path)

3. 第三题

You can use Chinese to answer the questions.

Problem Description

You need to use the Swin Transformer model to train a binary classifier to identify whether an image contains a green screen. Green screens are commonly used in video production and photography for background replacement in post-production. Your task is to write a program that uses the Swin Transformer model to train and evaluate the performance of this classifier.

Input Data

  1. Training Dataset: A set of images, including images with and without green screens.
  2. Labels: Labels for each image, where 0 indicates no green screen and 1 indicates the presence of a green screen.

Output Requirements

  1. Trained Model: Train a binary classifier using the Swin Transformer model.
  2. Model Evaluation: Evaluate the model’s accuracy, precision, recall, and F1-score on a validation or test set.

Programming Requirements

  1. Data Preprocessing: Including image loading, normalization, and label processing.
  2. Model Definition: Using the Swin Transformer model.
  3. Training Process: Including loss function, optimizer, and training loop.
  4. Evaluation Process: Evaluate the model’s performance on the validation or test set.
  5. Results Presentation: Output evaluation metrics and visualize some prediction results.

Here is a sample code framework to help you get started:

import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader, Dataset
from torchvision import transforms, datasets
from swin_transformer_pytorch import SwinTransformer
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
from PIL import Image

# Dataset class definition
class GreenScreenDataset(Dataset):
    def __init__(self, image_paths, labels, transform=None):
        self.image_paths = image_paths
        self.labels = labels
        self.transform = transform

    def __len__(self):
        return len(self.image_paths)

    def __getitem__(self, idx):
        image = Image.open(self.image_paths[idx]).convert('RGB')
        label = self.labels[idx]
        if self.transform:
            image = self.transform(image)
        return image, label

# Data preprocessing, please define transform
# TODO

# Load datasets
train_dataset = GreenScreenDataset(train_image_paths, train_labels, transform=transform)
train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)

val_dataset = GreenScreenDataset(val_image_paths, val_labels, transform=transform)
val_loader = DataLoader(val_dataset, batch_size=32, shuffle=False)

# Define the SwinTransformer model
# TODO

# Loss function and optimizer
criterion = nn.CrossEntropyLoss()
# TODO

# Training process
def train(model, train_loader, criterion, optimizer, num_epochs=10):
    model.train()
    for epoch in range(num_epochs):
        running_loss = 0.0
        for images, labels in train_loader:
            # TODO: forward pass, compute loss, backpropagation, optimizer step

            running_loss += loss.item()
        print(f'Epoch [{epoch+1}/{num_epochs}], Loss: {running_loss/len(train_loader):.4f}')

# Evaluation process
def evaluate(model, val_loader):
    model.eval()
    all_preds = []
    all_labels = []
    with torch.no_grad():
        for images, labels in val_loader:
            outputs = model(images)
            _, preds = torch.max(outputs, 1)
            all_preds.extend(preds.cpu().numpy())
            all_labels.extend(labels.cpu().numpy())
        accuracy = accuracy_score(all_labels, all_preds)
        # TODO: Calculate precision, recall, and F1-score
        print(f'Accuracy: {accuracy:.4f}, Precision: {precision:.4f}, Recall: {recall:.4f}, F1-score: {f1:.4f}')

# Train the model
train(model, train_loader, criterion, optimizer, num_epochs=10)

# Evaluate the model
evaluate(model, val_loader)

题解

该问题要求训练一个基于Swin Transformer模型的二分类器,用以识别图像中是否包含绿幕。解决方案涉及数据预处理、模型设计、训练和评估等多个环节。

首先,在数据预处理阶段,图像需要被调整大小并进行归一化,以满足Swin Transformer的输入需求。此外,数据集中的标签是二值化的,分别代表有无绿幕(0表示无绿幕,1表示有绿幕),确保数据集类能够准确处理这些标签是至关重要的。在模型设计上,使用了预训练的Swin Transformer模型,并针对二分类任务进行了微调。输出层被替换为一个具有两个节点的全连接层,分别对应两个类别。通过这种方式,模型能够有效地适应二分类任务。训练过程采用了标准的训练循环,设置了损失函数和优化器,并使用学习率调度器动态调整学习率。此外,为了防止过拟合,模型在训练过程中还应用了正则化技术,如dropout。在模型评估阶段,除了准确率,还使用了精确率、召回率和F1分数等指标,以全面评估模型在二分类任务中的表现。同时,为了更直观地展示模型效果,选择了一些样本图像进行可视化,显示它们的预测结果与实际标签的对比。

import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader, Dataset
from torchvision import transforms
from swin_transformer_pytorch import SwinTransformer
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
from PIL import Image
import matplotlib.pyplot as plt
import numpy as np

# 数据集类定义
class GreenScreenDataset(Dataset):
    def __init__(self, image_paths, labels, transform=None):
        self.image_paths = image_paths
        self.labels = labels
        self.transform = transform

    def __len__(self):
        return len(self.image_paths)

    def __getitem__(self, idx):
        image = Image.open(self.image_paths[idx]).convert('RGB')
        label = self.labels[idx]
        if self.transform:
            image = self.transform(image)
        return image, torch.tensor(label, dtype=torch.long)

# 数据预处理
transform = transforms.Compose([
    transforms.Resize((224, 224)),
    transforms.ToTensor(),
    transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
])

train_dataset = GreenScreenDataset(train_image_paths, train_labels, transform=transform)
train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)

val_dataset = GreenScreenDataset(val_image_paths, val_labels, transform=transform)
val_loader = DataLoader(val_dataset, batch_size=32, shuffle=False)

model = SwinTransformer(
    hidden_dim=96,
    layers=(2, 2, 6, 2),
    num_heads=(3, 6, 12, 24),
    num_classes=2,
    window_size=7,
    input_resolution=224
)
model = model.to(torch.device('cuda' if torch.cuda.is_available() else 'cpu'))

criterion = nn.CrossEntropyLoss()
optimizer = optim.AdamW(model.parameters(), lr=1e-4, weight_decay=0.01)
scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=5, gamma=0.1)

# 训练
def train(model, train_loader, criterion, optimizer, scheduler, num_epochs=10):
    model.train()
    for epoch in range(num_epochs):
        running_loss = 0.0
        for images, labels in train_loader:
            images, labels = images.to(device), labels.to(device)

            optimizer.zero_grad()
            outputs = model(images)
            loss = criterion(outputs, labels)
            loss.backward()
            optimizer.step()

            running_loss += loss.item()

        scheduler.step()
        print(f'Epoch [{epoch+1}/{num_epochs}], Loss: {running_loss/len(train_loader):.4f}')

# 模型评估
def evaluate(model, val_loader):
    model.eval()
    all_preds = []
    all_labels = []
    with torch.no_grad():
        for images, labels in val_loader:
            images, labels = images.to(device), labels.to(device)
            outputs = model(images)
            _, preds = torch.max(outputs, 1)
            all_preds.extend(preds.cpu().numpy())
            all_labels.extend(labels.cpu().numpy())

    accuracy = accuracy_score(all_labels, all_preds)
    precision = precision_score(all_labels, all_preds)
    recall = recall_score(all_labels, all_preds)
    f1 = f1_score(all_labels, all_preds)
    
    print(f'Accuracy: {accuracy:.4f}, Precision: {precision:.4f}, Recall: {recall:.4f}, F1-score: {f1:.4f}')

    return all_preds, all_labels

# 可视化
def visualize_predictions(val_loader, model):
    model.eval()
    images, labels = next(iter(val_loader))
    images, labels = images.to(device), labels.to(device)
    outputs = model(images)
    _, preds = torch.max(outputs, 1)

    images = images.cpu().numpy()
    preds = preds.cpu().numpy()
    labels = labels.cpu().numpy()

    # 可视化前6个样本
    plt.figure(figsize=(12, 8))
    for i in range(6):
        plt.subplot(2, 3, i + 1)
        image = np.transpose(images[i], (1, 2, 0))
        image = image * np.array([0.229, 0.224, 0.225]) + np.array([0.485, 0.456, 0.406])  # 反归一化
        image = np.clip(image, 0, 1)
        plt.imshow(image)
        plt.title(f'Pred: {preds[i]}, Actual: {labels[i]}')
        plt.axis('off')
    plt.show()


device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
train(model, train_loader, criterion, optimizer, scheduler, num_epochs=10)
all_preds, all_labels = evaluate(model, val_loader)
visualize_predictions(val_loader, model)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2057882.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

JavaScript(25)——BOM、延迟函数、JS执行机制

BOM BOM是浏览器对象模型 window对象是一个全局对象,也就是JavaScript中的顶级对象所有通过var定义的全局作用域中的变量,函数都会变成window对象的属性和方法window对象下的属性和方法调用的时候可以省略window 延时函数 let a setTimeout(回调函数…

Python(Falsk) + React Golang(Gin) + Vue 全栈开发的最佳实践

前面分别讲了 Python(Falsk) 、 React 、 Golang(Gin) 、 Vue(Element),现在整体的给大家汇报一下,这个是简单搭建的demo,后面的添砖加瓦需要自己动手咯,有不明白的可以参考一下小编前面的文章,也许会给大家有答疑解惑…

QTday04

1.思维导图 2. . #include "widget.h" #include "ui_widget.h" #include "widget.h"Widget::Widget(QWidget *parent): QWidget(parent), ui(new Ui::Widget), speecher(new QTextToSpeech(this)) //给语音播报者实例化空间{ui->setupUi(th…

ansible搭建+ansible常用模块

ansible搭建 管理机安装ansible,被管理节点必须打开ssh服务 1.管理机安装ansible yum -y install ansible 2.查看版本 ansible --version ansible 2.9.27 3.查找配置文件 find /etc/ -name "*ansible*" /etc/ansible /etc/ansible/ansible.cfg 4.三台被管理机…

轻松捕捉屏幕精彩,2024年录屏神器大盘点

随着技术的不断进步和用户需求的日益多样化,市场上的录屏软件更是层出不穷,各有千秋。今天,就让我们一同盘点那些和win10录屏快捷键一样可以快捷控制的专业录屏软件,探索它们如何助力我们更加高效地捕捉屏幕上的每一个精彩瞬间。 …

数据结构-链表-第二天

结合leetcode学习c 链表比数组更易增加和删除数据,但访问速度更慢 定义 链表(linked list)是一种线性数据结构,其中的每个元素都是一个节点对象,各个节点通过“引用”相连接。 引用记录了下一个节点的内存地址&#…

「字符串」前缀函数|KMP匹配:规范化next数组 / LeetCode 28(C++)

概述 为什么大家总觉得KMP难?难的根本就不是这个算法本身。 在互联网上你可以见到八十种KMP算法的next数组定义和模式串回滚策略,把一切都懂得特别混乱。很多时候初学者的难点根本不在于这个算法本身,而是它令人痛苦的百花齐放的定义。 有…

[C++] map、set的 红黑树 封装(一)

标题:[C] map、set的 红黑树 封装 水墨不写bug (图片来源于网络) 目录 一、红黑树与AVL树的比较(为什么容器选择红黑树) 二、map、set的封装 1.模板参数 2.红黑树迭代器设计 正文开始: 一、红黑树与AV…

RK3588J正式发布Ubuntu桌面系统,丝滑又便捷!

本文主要介绍瑞芯微RK3588J的Ubuntu系统桌面演示,开发环境如下: U-Boot:U-Boot-2017.09 Kernel:Linux-5.10.160 Ubuntu:Ubuntu20.04.6 LinuxSDK: rk3588-linux5.10-sdk-[版本号] (基于rk3…

【GH】【EXCEL】P7: Control

XL Label XL Dropdown XL CHECK BOX XL Button XL Scroller XL Spinner XL ListBox

RocketMQ源码分析 - 环境搭建

RocketMQ源码分析 - 环境搭建 环境搭建源码拉取导入IDEA调试1) 启动NameServer2) 启动Broker3) 发送消息4) 消费消息 环境搭建 依赖工具 JDK:1.8MavenIntellij IDEA 源码拉取 从官方仓库 https://github.com/apache/rocketmq clone或者download源码。 源码目录…

【微服务】微服务组件之Nacos注册中心和配置中心的使用

背景: 在当前的软件架构领域,微服务架构凭借其高度的可扩展性、灵活性和可维护性,已成为企业构建复杂应用的首选。微服务架构通过将应用拆分成一系列小的、独立的服务,实现了服务的解耦和复用,从而提高了应用的可扩展性…

Sass实现网页背景主题切换

Sass 实现网页背景主题切换 前言准备工作一、 简单的两种主题黑白切换1.定义主题2. 添加主题切换功能3. 修改 data-theme 属性 二、多种主题切换1. 定义主题2. 动态生成 CSS 变量1.遍历列表2.遍历映射3.高级用法 3. 设置默认主题4. 切换功能HTML 三、多种主题多种样式切换1. 定…

在 Fedora 上安装 LAMP(Linux、Apache、MySQL、PHP)的方法

前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到网站。 关于 LAMP LAMP 栈是一组用于启动和运行 Web 服务器的开源软件。该缩写代表 Linux、Apache、MySQL 和 PHP。由于服务器已经在运行 Fedo…

高性能web服务器1

基础 Web 服务简介 Web 服务是互联网的核心组成部分之一,它允许用户通过浏览器访问信息和应用程序。一个基础的 Web 服务通常由 Web 服务器软件、静态网页内容、以及可选的动态内容生成程序组成。 Web 服务器软件 Web 服务器软件是运行在服务器上的程序&#xff…

【Java 数据结构】PriorityQueue介绍

优先级队列 回顾二叉树堆堆是什么堆的实现初始化堆的创建向下调整建堆复杂度插入向上调整建堆复杂度删除 PriorityQueue类介绍PriorityQueue是什么PriorityQueue使用构造方法常用方法 PriorityQueue源码介绍Top-K问题 回顾二叉树 上一次我们简单的了解了二叉树这个数据结构, 但…

每天五分钟深度学习框架pytorch:神经网络工具箱nn的介绍

本文重点 我们前面一章学习了自动求导,这很有用,但是在实际使用中我们基本不会使用,因为这个技术过于底层,我们接下来将学习pytorch中的nn模块,它是构建于autograd之上的神经网络模块,也就是说我们使用pytorch封装好的神经网络层,它自动会具有求导的功能,也就是说这部…

夏晖WMS是什么?夏晖WMS怎么与金蝶云星空进行集成?

在数字化浪潮席卷全球的今天,企业对于业务流程的高效管理和数据集成的需求愈发迫切。夏晖WMS作为一款领先的仓库管理系统,与金蝶云星空ERP的集成成为了众多企业提升管理效率的关键环节。 夏晖WMS是什么? 夏晖WMS是一款由夏晖物流(上海&…

Golang | Leetcode Golang题解之第355题设计推特

题目: 题解: type Twitter struct {Tweets []intUserTweets map[int][]intFollows map[int][]intIsFollowMy map[int]bool }/** Initialize your data structure here. */ func Constructor() Twitter {// 每一次实例化的时候,都重新分配一次…

C语言 | Leetcode C语言题解之第354题俄罗斯套娃信封问题

题目: 题解: int cmp(int** a, int** b) {return (*a)[0] (*b)[0] ? (*b)[1] - (*a)[1] : (*a)[0] - (*b)[0]; }int maxEnvelopes(int** envelopes, int envelopesSize, int* envelopesColSize) {if (envelopesSize 0) {return 0;}qsort(envelopes, …