首页
大事记
友情链接
留言板
关于
Search
1
解决SSH登录卡在"Last login"问题
1,477 阅读
2
无界拷贝文件在线传输系统开始公测
1,213 阅读
3
宝塔BT面板PHP防CC
1,065 阅读
4
高考作文论证方法之“广深高铁”
568 阅读
5
Linux环境安装Dlib——以Centos7为例
563 阅读
默认分类
新鲜科技
时事热点
学无止境
Python
Arduino
作文素材
C语言
踩坑记录
机器学习
资源分享
站长杂谈
登录
Search
标签搜索
机器学习
Datawhale
C语言
git
python
组队学习
物联网
esp8266
PHP
云顶书院
Linux
LLM
建站
网站
宝塔
开学
清明节
VPS
Arduino
开源硬件
MoyiTech
累计撰写
56
篇文章
累计收到
38
条评论
首页
栏目
默认分类
新鲜科技
时事热点
学无止境
Python
Arduino
作文素材
C语言
踩坑记录
机器学习
资源分享
站长杂谈
页面
大事记
友情链接
留言板
关于
搜索到
56
篇与
的结果
2025-11-21
FCP 源码阅读
论文:LANGUAGE MODELS CAN LEARN FROMVERBAL FEEDBACK WITHOUT SCALAR REWARDS原文:https://arxiv.org/pdf/2509.22638官方仓库:https://github.com/sail-sg/feedback-conditional-policy主要改动:critique 后替换了 promptreward 计算使用固定值修改了优势计算过程,不做均值方差的处理,直接为 reward主要代码位置:verl/recipe/fcp,但在原始 verl 代码里面也有一些修改,后面细说。训练脚本:verl/recipe/fcp/run_fcp.sh入口:verl/recipe/fcp/main_fcp.py训练 Pipeline:verl/recipe/fcp/fcp_ray_trainer.pyreward && critque:verl/verl/workers/reward_manager/gpt_critique_math_score.py配置文件:verl/recipe/fcp/config/fcp_trainer.yaml优势计算:verl/verl/trainer/ppo/core_algos.pyFCP 整体流程(verl/recipe/fcp/fcp_ray_trainer.py):取数据,rollout。调用 reward 获取 score 和 critique:FCP 是把 critique 过程都放在了 reward 里,一起返回给主流程。使用 critique + prompt + rollout 构造 sft data。对 sft data 计算优势:全置为 reward,等价于 SFT 损失。梯度更新。Reward 解读(verl/verl/workers/reward_manager/gpt_critique_math_score.py):去除 … tags:因为 online 的过程是给了 c+ 进行生成,所以需要获取到纯净的 prompt。调用 gpt api,使用 prompt + rollout + ground_truth 生成 critique 和 score(0-10)。reward 设置为 0-10:论文中没有详细说明,但可理解为在 SFT 中,针对于每条样本的权重。返回的数据中有:reward tensor、critique 等。Prompt:You are acting as a real-world human user of an LLM. Inputs: Question: \"\"\" {question} \"\"\" Model Answer: \"\"\" {model_answer} \"\"\" Reference Final Answer (used only for correctness check): \"\"\" {reference_answer} \"\"\" Your tasks: 1) Simulate "user feedback" from a normal, real-world user reacting to the Model Answer only. - Length: 1-3 sentences, colloquial tone, first person. - Content: purely subjective sentiment (e.g., helpfulness, confidence, confusion, satisfaction). - STRICT: Do NOT mention or allude to any symbols, formulas, variable names, or specialized concepts from the Question or the Model Answer. Do NOT quote text from the inputs. For example: "I think you are right, but your solution is really long and complicated." "You are a genius! You have all my respect." "I am confused. There seems to be a mistake in your solution." "What are you talking about? You are not answering my question." etc. 2) Simulate a professional reviewer evaluating the Model Answer along several dimensions, including but not limited to: • correctness — Compare the Model Answer's final result ONLY against the Reference Final Answer (if provided). Judge whether the end result matches; do not use the reference for any other purpose. • logical_rigor — Assess the soundness and gaplessness of reasoning within the Model Answer itself. Do NOT use the Reference Final Answer here. • completeness — Judge coverage of required parts and edge cases based on the Question and the Model Answer only. Do NOT use the Reference Final Answer here. • clarity — Evaluate organization, readability, and ease of following in the Model Answer. Do NOT use the Reference Final Answer here. Then provide a high-level summary (1-3 sentences) with overall judgment and broad observations. - STRICT for the high-level summary: Only use adjectives and adverbs to describe the Model Answer and reasoning process. DO NOT mention where it goes wrong and where it can do better. For example: "Your final answer is correct, but the solution is too long and complicated. There are also several logical errors in your solution." "The answer is partially correct. The reasoning is sound but not complete. Also, you are being too verbose." "The answer is totally wrong. It lacks soundness and is not complete. However, the solution is concise and clear." Hard constraints: - Keep all content in English. - Do not mention anything like "reference" or "python snippet". Output format: ### User-style feedback: <your 1-3 sentence feedback> ### Analysis along several dimensions: <your 1-3 sentence analysis> ### High-level summary: <your 1-3 sentence summary> ### Score (0-10): <one overall integer score>在配置中设置了优势计算器为 fcp(verl/recipe/fcp/config/fcp_trainer.yaml):algorithm: ... adv_estimator: fcp # 使用 FCP 专用的优势估计器,不需要 critic优势计算解读(verl/verl/trainer/ppo/core_algos.py):@register_adv_est(AdvantageEstimator.FCP) # or simply: @register_adv_est("fcp") def compute_fcp_outcome_advantage(token_level_rewards: torch.Tensor, response_mask: torch.Tensor, config: Optional[AlgoConfig] = None, index: Optional[np.ndarray] = None, reward_baselines: Optional[torch.Tensor] = None): """ Compute advantage for FCP Args: token_level_rewards: `(torch.Tensor)` shape: (bs, response_length) response_mask: `(torch.Tensor)` shape: (bs, response_length) Returns: advantages: `(torch.Tensor)` shape: (bs, response_length) Returns: `(torch.Tensor)` shape: (bs, response_length) """ # 由于在 reward 时,只给每个 rollout 的最后一个 token 位置进行了赋值,前面都是0,所以 score 先进行了一次聚合。 scores = token_level_rewards.sum(dim=-1) with torch.no_grad(): # 升维后,通过广播机制扩展到整个 response 序列中 scores = scores.unsqueeze(-1) * response_mask return scores, scoresprepare_sft_data 解读:def _prepare_sft_data(self, batch: DataProto, critiques: list[str]) -> DataProto: """ Prepare data for SFT training using chat template format. Format: user: "<critique><prompt>", assistant: "<response>" Args: batch: Original batch data critiques: List of critiques from GPT API Returns: DataProto: Restructured data for SFT training """ if self.config.algorithm.debug_mode: print("[DEBUG] ===== Preparing SFT Data =====") print(f"[DEBUG] Batch size: {len(batch)}") print(f"[DEBUG] Number of critiques: {len(critiques)}") sft_batch = deepcopy(batch) # 备份原始数据 sft_batch.batch["old_input_ids"] = batch.batch["prompts"].clone() sft_batch.batch["old_attention_mask"] = batch.batch["attention_mask"].clone() sft_batch.batch["old_position_ids"] = batch.batch["position_ids"].clone() # Get original prompts and responses (decode to text first) batch_size = len(batch) new_input_ids = [] new_attention_mask = [] new_prompts = [] new_position_ids = [] prompts = batch.batch["prompts"] position_ids = batch.batch["position_ids"] input_ids = batch.batch["input_ids"] attention_mask = batch.batch["attention_mask"] max_prompt_length = self.config.data.get("max_prompt_length", 1024) print(f"[DEBUG] prompts[0]: {prompts[0]}, type: {type(prompts[0])}") # 遍历每一个 rollout response = [] for i in range(batch_size): item_prompt_ids = prompts[i] prompt_length = len(item_prompt_ids) item_attn_mask = attention_mask[i] prompt_attn_mask = item_attn_mask[:prompt_length] valid_prompt_ids = item_prompt_ids[prompt_attn_mask.bool()] prompt_text = self.tokenizer.decode(valid_prompt_ids, skip_special_tokens=False) # 提取原始 prompt 中的 question user_content = prompt_text.split("</EF>")[1].split("<|im_end|>\n")[0] # Get critique text critique_text = critiques[i] if self.config.algorithm.debug_mode and i == 0: # Only debug first item to avoid spam print(f"[DEBUG] ===== Sample {i} =====") print(f"[DEBUG] Original prompt length: {len(item_prompt_ids)}") print(f"[DEBUG] Valid prompt length: {prompt_length}") print(f"[DEBUG] Prompt text: {prompt_text}") print(f"[DEBUG] User content: {user_content}") print(f"[DEBUG] Critique text: {critique_text}") # 构建替换了 critique 后的新 message messages = [ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": f"{self.config.algorithm.critique_start_token}{critique_text}{self.config.algorithm.critique_end_token}{user_content}"}, ] # Apply chat template raw_prompt = self.tokenizer.apply_chat_template( messages, add_generation_prompt=True, tokenize=False ) model_inputs = self.tokenizer(raw_prompt, return_tensors="pt", add_special_tokens=False) item_input_ids = model_inputs.pop("input_ids") item_attention_mask = model_inputs.pop("attention_mask") # if len(input_ids) > max_prompt_length: # raise RuntimeError(f"Prompt length {len(input_ids)} is greater than max_prompt_length {max_prompt_length}") # 对构建好的 prompt 进行 padding item_input_ids, item_attention_mask = verl_F.postprocess_data( input_ids=item_input_ids, attention_mask=item_attention_mask, max_length=max_prompt_length, pad_token_id=self.tokenizer.pad_token_id, left_pad=True, truncation=self.config.data.truncation, ) item_position_ids = compute_position_id_with_mask(item_attention_mask) response_ids = input_ids[i][max_prompt_length:] response.append(response_ids) new_input_ids.append(item_input_ids) new_attention_mask.append(item_attention_mask) new_prompts.append(item_prompt_ids) new_position_ids.append(item_position_ids) new_input_ids = torch.stack([x.squeeze(0) for x in new_input_ids], dim=0).to(input_ids[0].device) new_attention_mask = torch.stack([x.squeeze(0) for x in new_attention_mask], dim=0).to(attention_mask[0].device) new_prompts = torch.stack([x.squeeze(0) for x in new_prompts], dim=0).to(prompts[0].device) new_position_ids = torch.stack([x.squeeze(0) for x in new_position_ids], dim=0).to(position_ids[0].device) response = torch.stack([x.squeeze(0) for x in response], dim=0).to(input_ids[0].device) seq = torch.cat([new_input_ids, response], dim=-1) response_length = response.size(1) delta_position_id = torch.arange(1, response_length + 1, device=new_position_ids.device) delta_position_id = delta_position_id.unsqueeze(0).expand(batch_size, -1) response_position_ids = new_position_ids[..., -1:] + delta_position_id new_position_ids = torch.cat([new_position_ids, response_position_ids], dim=-1) response_attention_mask = get_response_mask( response_id=response, eos_token=[151643,151645], dtype=new_attention_mask.dtype ) new_attention_mask = torch.cat((new_attention_mask, response_attention_mask), dim=-1) # 没有改变 responses 和 response_mask 是因为在 FCP 中只是对 prompt 进行了替换,没有改变原始 response。 sft_batch.batch["prompts"] = new_prompts sft_batch.batch["input_ids"] = seq sft_batch.batch["attention_mask"] = new_attention_mask sft_batch.batch["position_ids"] = new_position_ids print(f"[DEBUG] : (after sft_batch) prompts.shape: {sft_batch.batch['prompts'].shape}, input_ids.shape: {sft_batch.batch['input_ids'].shape}, attention_mask.shape: {sft_batch.batch['attention_mask'].shape}, position_ids.shape: {sft_batch.batch['position_ids'].shape}") print(f"[DEBUG] (after sft_batch) prompts[0]: {new_prompts[0]}") print(f"[DEBUG] (after sft_batch) input_ids[0]: {seq[0]}") print(f"[DEBUG] (after sft_batch) attention_mask[0]: {new_attention_mask[0]}") print(f"[DEBUG] (after sft_batch) position_ids[0]: {new_position_ids[0]}") return sft_batch
2025年11月21日
4 阅读
0 评论
0 点赞
2024-10-03
AAR论文阅读
论文简介标题:Augmentation-Adapted Retriever Improves Generalization of Language Models as Generic Plug-In摘要:Retrieval augmentation can aid language models (LMs) in knowledge-intensive tasks by supplying them with external information. Prior works on retrieval augmentation usually jointly fine-tune the retriever and the LM, making them closely coupled. In this paper, we explore the scheme of generic retrieval plug-in: the retriever is to assist target LMs that may not be known beforehand or are unable to be fine-tuned together. To retrieve useful documents for unseen target LMs, we propose augmentation-adapted retriever (AAR), which learns LM’s preferences obtained from a known source LM. Experiments on the MMLU and PopQA datasets demonstrate that our AAR trained with a small source LM is able to significantly improve the zero-shot generalization of larger target LMs ranging from 250M Flan-T5 to 175B InstructGPT. Further analysis indicates that the preferences of different LMs overlap, enabling AAR trained with a single source LM to serve as a generic plug-in for various target LMs. Our code is open-sourced at https://github.com/OpenMatch/AugmentationAdapted-Retriever.一种名为“Augmentation-Adapted Retriever(AAR)”的方法,用于改进语言模型在无监督任务中的泛化能力。AAR 旨在为无法联合微调的黑盒大模型(如GPT)提供外部信息支持,并增强其在知识密集型任务中的表现。与现有的检索增强方法不同,AAR 通过从一个较小的已知模型(source LM)学习目标模型的偏好,从而适应不同的大模型。文章通过在 MMLU 和 PopQA 数据集上的实验表明,AAR 能显著提升目标大模型的零样本泛化能力,并且能够作为一个通用插件为各种目标模型服务。论文解读在现在的RAG任务中,包含了Retriever和LLM两个部分,通常情况下二者是分别进行预训练的,Retriever负责从嵌入的向量数据库中检索最相关的文档或片段,LLM负责生成。RAG和fine-tuning并不冲突,通过fine-tuning可以让Retriever和LLM紧密耦合,提升RAG系统的性能。这种方法适用于白盒子模型,但是对于提供线上API的黑盒子模型,我们多数情况下无法进行fine-tuning,所以本文提出了AAR方法,可以在Retriever更符合LLM的需要,从而无需对黑盒子模型进行fine-tuning。我们现在的Retriever一般使用的text embedding模型是通过对比学习进行训练。数据集的是使用人工标注的Positive Doc和自动筛选出来的Negative Doc(如ANCE)进行训练,由此得到的Retriever是满足了人工筛选的偏好,而不是LLM的偏好。由于LLM的训练数据有很大的overlap,所以我们可以使用一个很小的source LM(如Flan-T5)的偏好来替代LLM的偏好,那么Positive Docs就是人工标注doc和通过source LM计算出偏好更高的doc的并集,Negtive Docs就是沿用了ANCE的结果。对于这篇文章,我的理解是。其实作者借鉴了ANCE的思想做了一个Positive Doc的训练增强,从而提升了text embedding模型的检索能力,使其能够检索到更多source LM(或LLM)喜欢的docs。
2024年10月03日
164 阅读
0 评论
1 点赞
2023-11-24
背包问题算法
01背包问题01背包是一种动态规划问题。动态规划的核心就是状态转移方程有一个容量为V的背包,还有n个物体。现在忽略物体实际几何形状,我们认为只要背包的剩余容量大于等于物体体积,那就可以装进背包里。每个物体都有两个属性,即体积w和价值v。 问:如何向背包装物体才能使背包中物体的总价值最大?二维数组解法f[i][j] = max(f[i - 1][j], f[i - 1][j - w[i]] + v[j])i:选用前i种物品j:背包容量为jdp[i][j] 表示从下标为[0,i]的物品里任意取,放进容量为j的背包,价值总和最大是多少。for (int j = 0 ; j < weight[0]; j++) { // 如果把dp数组预先初始化为0了,这一步就可以省略。 dp[0][j] = 0; } // 正序遍历 for (int j = weight[0]; j <= bagWeight; j++) { dp[0][j] = value[0]; }有两个遍历维度:1. 物品和背包容量。 2. 所以要确定遍历顺序。两者都可以,先遍历物品好理解。先遍历物品,然后遍历背包重量:// weight数组的大小 就是物品个数 for(int i = 1; i < weight.size(); i++) { // 遍历物品 for(int j = 0; j <= bagWeight; j++) { // 遍历背包容量 if (j < weight[i]) dp[i][j] = dp[i - 1][j]; // 如果不能放下物品i else dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - weight[i]] + value[i]); } } 先遍历背包,再遍历物品:// weight数组的大小就是物品个数 for(int j = 0; j <= bagWeight; j++) { // 遍历背包容量 for(int i = 1; i < weight.size(); i++) { // 遍历物品 if (j < weight[i]) dp[i][j] = dp[i - 1][j]; else dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - weight[i]] + value[i]); } }为什么两种顺序都可以?要理解递归的本质和递推的方向。那么先遍历物品,再遍历背包的过程和先遍历背包,再遍历物品,dp[i][j]所需要的数据就是左上角,根本不影响dp[i][j]公式的推导。一维dp数组解决01背包问题dp[j] = max(dp[j], dp[j - weight[i]] + value[i]);一维dp数组如何初始化dp[j]表示:容量为j的背包,所背的物品价值可以最大为dp[j],那么dp[0]就应该是0,因为背包容量为0所背的物品的最大价值就是0。假设物品价值都是大于0的,所以dp数组初始化的时候,都初始为0就可以了。一维dp数组遍历顺序for(int i = 0; i < weight.size(); i++) { // 遍历物品 for(int j = bagWeight; j >= weight[i]; j--) { // 遍历背包容量 dp[j] = max(dp[j], dp[j - weight[i]] + value[i]); } }在01背包中二维dp数组的两个for遍历的先后循序是可以颠倒,一维dp数组的两个for循环先后循序一定是先遍历物品,再遍历背包容量。和二维dp的写法中,遍历背包的顺序是不一样的!一维dp遍历的时候,背包容量是从大到小:倒序遍历是为了保证物品i只被放入一次!为什么一维dp数组必须倒序遍历:如图,红线为数据更新来源,蓝线数据更新顺序:当前状态源于左上角和同背包容量方向如果先遍历物品再遍历背包且正序遍历,就会使一些同背包容量方向的数据被覆盖掉。如果先遍历背包再遍历物品,完全背包问题完全背包依然是一个动态规划问题有N件物品和一个最多能背重量为W的背包。第i件物品的重量是weight[i],得到的价值是value[i] 。每件物品都有无限个(也就是可以放入背包多次),求解将哪些物品装入背包里物品价值总和最大。完全背包和01背包问题唯一不同的地方就是,每种物品有无限件。01背包和完全背包唯一不同就是体现在遍历顺序上,所以针对遍历顺序进行分析。// 先遍历物品,再遍历背包 int[] dp = new int[bagWeight + 1]; for (int i = 0; i < weight.length; i++){ for (int j = 1; j <= bagWeight; j++){ if (j - weight[i] >= 0){ dp[j] = Math.max(dp[j], dp[j - weight[i]] + value[i]); } } }为什么遍历物品在外层循环,遍历背包容量在内层循环?在01背包中二维dp数组的两个for遍历的先后循序是可以颠倒,一维dp数组的两个for循环先后循序一定是先遍历物品,再遍历背包容量。在完全背包中,对于一维dp数组来说,其实两个for循环嵌套顺序无所谓:因为物品可以重复装。也就是说dp[j]是根据下标j之前所对应的dp[j]计算出来的。 只要保证下标j之前的dp[j]都是经过计算的就可以。完全背包中,两个for循环的先后循序,都不影响计算dp[j]所需要的值。为什么是正序遍历而不是倒序遍历了?因为在完全背包中,由于物品可以重复装填,那么就需要相同物品在不同背包容量时重复利用前面的数据。先遍历背包再遍历物品:// 先遍历背包,再遍历物品 for(int j = 0; j <= bagWeight; j++) { // 遍历背包容量 for(int i = 0; i < weight.size(); i++) { // 遍历物品 if (j - weight[i] >= 0) dp[j] = max(dp[j], dp[j - weight[i]] + value[i]); } }先遍历物品,再遍历背包:// 先遍历物品,再遍历背包 int[] dp = new int[bagWeight + 1]; for (int i = 0; i < weight.length; i++){ for (int j = 1; j <= bagWeight; j++){ if (j - weight[i] >= 0){ dp[j] = Math.max(dp[j], dp[j - weight[i]] + value[i]); } } }连续背包问题连续背包问题是指有一个容量为V的背包和n个物品,每个物品有一个体积v [i]和一个价值w [i],现在要将这些物品放入背包中,使得背包中物品的总价值最大。 与0/1背包问题不同的是,每个物品可以被放入多次,即是连续的。解题思路:单位价值优先使用贪心算法① 按价值密度(w/v)进行非递增排序② 按照排序先后,往里装。单个物品装完时换下一个,直到背包填满为止
2023年11月24日
345 阅读
1 评论
2 点赞
2023-11-15
多模态初探——驾驶汽车虚拟仿真视频数据理解
近期Datawhale组织了《2023全球智能汽车AI挑战赛——赛道二:智能驾驶汽车虚拟仿真视频数据理解赛道》比赛的赛事实践活动赛题:智能驾驶汽车虚拟仿真视频数据理解赛道任务:输入:元宇宙仿真平台生成的前视摄像头虚拟视频数据(8-10秒左右);输出:对视频中的信息进行综合理解,以指定的json文件格式,按照数据说明中的关键词(key)填充描述型的文本信息(value,中文/英文均可以);baseline理解CLIPbaseline主要采用了CLIP模型:CLIP是用文本作为监督信号来训练可迁移的视觉模型,特此学习一下CLIPCLIP参考资料:https://zhuanlan.zhihu.com/p/493489688How CLIP WorksCLIP是一种基于对比学习的多模态模型,与CV中的一些对比学习方法如moco和simclr不同的是,CLIP的训练数据是文本-图像对:(Text, Img)一张图像和它对应的文本描述,这里希望通过对比学习,模型能够学习到文本-图像对的匹配关系。如下图所示,CLIP包括两个模型:Text Encoder和Image Encoder,其中Text Encoder用来提取文本的特征,可以采用NLP中常用的text transformer模型;而Image Encoder用来提取图像的特征,可以采用常用CNN模型或者vision transformer。Text Encoder:text transformerImage Encoder: CNN or vision transformer这里对提取的文本特征和图像特征进行对比学习。对于一个包含N个文本-图像对的训练batch,将N个文本特征和N个图像特征两两组合,CLIP模型会预测出N²个可能的文本-图像对的相似度,这里的相似度直接计算文本特征和图像特征的余弦相似性(cosine similarity),即上图所示的矩阵。这里共有N个正样本,即真正属于一对的文本和图像(矩阵中的对角线元素),而剩余的N²−N个文本-图像对为负样本,那么CLIP的训练目标就是最大N个正样本的相似度,同时最小化N²−N个负样本的相似度How to zero-shot by CLIP与YOLO中使用的先预训练然后微调不同,CLIP可以直接实现zero-shot的图像分类,即不需要任何训练数据,就能在某个具体下游任务上实现分类根据任务的分类标签构建每个类别的描述文本:A photo of {label},然后将这些文本送入Text Encoder得到对应的文本特征,如果类别数目为N,那么将得到N个文本特征;将要预测的图像送入Image Encoder得到图像特征,然后与N个文本特征计算缩放的余弦相似度(和训练过程一致),然后选择相似度最大的文本对应的类别作为图像分类预测结果,进一步地,可以将这些相似度看成logits,送入softmax后可以到每个类别的预测概率在飞桨平台使用CLIP# 由于在平台没有默认安装CLIP模块,故需要先执行安装命令 !pip install paddleclip# 安装完后直接通过clip导入 from clip import tokenize, load_model # 载入预训练模型 model, transforms = load_model('ViT_B_32', pretrained=True)Pillow和OpenCV由于在之前仅仅接触过几次cv2和pil,都是直接从网上搜完代码直接调用的,没有深入里结果里面的具体含义,这次借着本次组队学习的机会,系统梳理一下cv2和pil的API先来看下本次baseline所用到的APIPIL# 导入pillow库中的Image from PIL import Image # 读入文件后是PIL类型(RGB) img = Image.open("zwk.png") # 补充:pytorch的顺序是(batch,c,h,w),tensorflow、numpy中是(batch,h,w,c)cv2# 导入cv2 import cv2 # 连接摄像头或读取视频文件,传入数字n代表第n号摄像头(从0开始),传入路径读取视频文件 cap = cv2.VideoCapture() # 按帧读取视频,ret为bool,frame为帧 ret, frame = cap.read() # 获取总帧数 cap.get(cv2.CAP_PROP_FRAME_COUNT) # 如果要抄中间的帧,需要先跳转到指定位置 cap.set(cv2.CAP_PROP_POS_FRAMES, n) # 由于cv2读取的图片默认BGR,而模型需要传入标准的RGB形式图片 image = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # 色彩通道转换:BGR -> RGB改进将需要预测的keywords改为["weather", "road_structure", "period", 'scerario'],可以使分数从93提升到119,看来CLIP对于识别一些诸如天气环境等静态信息还是比较有优势的。修改抽帧位置,但没有改进,可以再次尝试抽取多帧进行投票。(其实还试过切换为GPU,把整个视频所有帧都抽出来组成一个batch放进去计算整体概率,但是效果也不好)frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) # 获取视频总帧数 middle_frame_index = frame_count // 2 cap.set(cv2.CAP_PROP_POS_FRAMES, middle_frame_index) # 设置跳转当前位置到中间帧
2023年11月15日
359 阅读
0 评论
2 点赞
2023-10-27
使用亚马逊云科技服务器进行深度学习AI项目的线上部署
什么是Mutual AI?Mutual AI是一个致力于在人工智能新时代提供中文交互式科普的开源项目。项目目标:解决当前人工智能领域中机器学习和深度学习算法学习过程中的理论知识枯燥难懂的问题。解决初学者在实际操作过程中遇到的"黑匣子问题"。开源地址:YinHan-Zhang/Mutual-AI: Mutal Artificial Intelligence Project for novicies friendly (github.com)使用亚马逊云科技服务器进行线上搭建亚马逊云科技(Amazon Web Services,AWS)是全球领先的云计算服务提供商之一,为个人、企业和组织提供可靠的、灵活的和安全的云计算平台。其中,弹性云服务器Amazon EC2作为AWS的核心服务之一,提供了丰富的实例类型和配置选项,适用于各种不同规模和类型的应用需求本例程采用亚马逊云科技的弹性云服务器Amazon EC2进行部署了解更多购买信息:云主机_云服务器_Amazon EC2云虚拟服务器-亚马逊云科技 (amazonaws.cn)Amazon EC2提供安全、弹性、高可用的云服务器,随时启动,无需预先付费。它提供多种实例类型,包括通用型实例、计算优化实例、内存优化实例和存储优化实例,适用于各种不同的应用需求。Amazon EC2提供了以下不同类型的实例:`通用型实例:提供了平衡的计算、内存和网络资源,适用于大多数工作负载。计算优化实例:专注于提供高性能计算能力,适用于需要处理大量计算任务的应用,比如机器学习和高性能计算(HPC)。内存优化实例:针对内存密集型应用,提供大量的内存资源,能够支持处理大规模数据和内存密集型工作负载。存储优化实例:专注于提供高性能的存储系统,适用于需要处理大量存储和数据库操作的应用。除了常规实例外,亚马逊云还提供了加速计算实例,例如P3型实例,具备强大的处理能力和高速网络传输性能。本项目就采用了其中的P3型,配置如下:{callout color="#f0ad4e"}至多96 vCPU,768 GiB 内存多达 8 个 NVIDIA Tesla V100 GPU,各配有 5120 个 CUDA 核心和 640 个 Tensor 核心支持通过 NVLink 进行对等 GPU 通信提供高达 100Gbps 的聚合网络带宽{/callout}得益于AWS(亚马逊云)的高性能加速计算实例,可以使如此复杂的深度学习模型部署在线上部署运行环境准备本项目需要Python环境进行部署,其中Python3.9的编译安装教程请见:Linux编译安装Python3.9——以CentOS7为例 - MoyiTech的小站-IT博客-Maker BLOG (9998k.cn)其余模块已保存在requirements.txt,可使用pip进行快速安装Python 3.9Fastapi >=0.95.1Pillow >=9.4.0Torchvision >=0.15.0Torch >=2.0.0Torchaudio >=0.0.0Python-MultipartUvicorntensorflow >=2.12.0程序运行详细步骤克隆项目到本地git clone https://github.com/YinHan-Zhang/Mutual-AI使用pip安装Python依赖文件pip install -r requirements到项目文件夹,使用 uvicorn 运行程序uvicorn main:app搭建成功啦!打开网址 http://IP:8000/即可访问
2023年10月27日
420 阅读
1 评论
8 点赞
1
2
...
12