caffe: test code for Deep Learning approach

简介: 1 #include // for snprintf 2 #include 3 #include 4 5 #include "boost/algorithm/string.
  1 #include <stdio.h>  // for snprintf
  2 #include <string>
  3 #include <vector>
  4 
  5 #include "boost/algorithm/string.hpp"
  6 #include "google/protobuf/text_format.h"
  7 
  8 #include "caffe/blob.hpp"
  9 #include "caffe/common.hpp"
 10 #include "caffe/net.hpp"
 11 #include "caffe/proto/caffe.pb.h"
 12 #include "caffe/util/db.hpp"
 13 #include "caffe/util/io.hpp"
 14 #include "caffe/vision_layers.hpp"
 15 
 16 using caffe::Blob;
 17 using caffe::Caffe;
 18 using caffe::Datum;
 19 using caffe::Net;
 20 using boost::shared_ptr;
 21 using std::string;
 22 namespace db = caffe::db;
 23 
 24 template<typename Dtype>
 25 int feature_extraction_pipeline(int argc, char** argv);
 26 
 27 int main(int argc, char** argv) {
 28   return feature_extraction_pipeline<float>(argc, argv);
 29 //  return feature_extraction_pipeline<double>(argc, argv);
 30 }
 31 
 32 template<typename Dtype>
 33 int feature_extraction_pipeline(int argc, char** argv) {
 34   ::google::InitGoogleLogging(argv[0]);
 35   const int num_required_args = 7;
 36   if (argc < num_required_args) {
 37     LOG(ERROR)<<
 38     "This program takes in a trained network and an input data layer, and then"
 39     " extract features of the input data produced by the net.\n"
 40     "Usage: extract_features  pretrained_net_param"
 41     "  feature_extraction_proto_file  extract_feature_blob_name1[,name2,...]"
 42     "  save_feature_dataset_name1[,name2,...]  num_mini_batches  db_type"
 43     "  [CPU/GPU] [DEVICE_ID=0]\n"
 44     "Note: you can extract multiple features in one pass by specifying"
 45     " multiple feature blob names and dataset names separated by ','."
 46     " The names cannot contain white space characters and the number of blobs"
 47     " and datasets must be equal.";
 48     return 1;
 49   }
 50   int arg_pos = num_required_args;
 51 
 52   arg_pos = num_required_args;
 53   if (argc > arg_pos && strcmp(argv[arg_pos], "GPU") == 0) {
 54     LOG(ERROR)<< "Using GPU";
 55     uint device_id = 0;
 56     if (argc > arg_pos + 1) {
 57       device_id = atoi(argv[arg_pos + 1]);
 58       CHECK_GE(device_id, 0);
 59     }
 60     LOG(ERROR) << "Using Device_id=" << device_id;
 61     Caffe::SetDevice(device_id);
 62     Caffe::set_mode(Caffe::GPU);
 63   } else {
 64     LOG(ERROR) << "Using CPU";
 65     Caffe::set_mode(Caffe::CPU);
 66   }
 67 
 68   arg_pos = 0;  // the name of the executable
 69   std::string pretrained_binary_proto(argv[++arg_pos]);
 70 
 71   // Expected prototxt contains at least one data layer such as
 72   //  the layer data_layer_name and one feature blob such as the
 73   //  fc7 top blob to extract features.
 74   /*
 75    layers {
 76      name: "data_layer_name"
 77      type: DATA
 78      data_param {
 79        source: "/path/to/your/images/to/extract/feature/images_leveldb"
 80        mean_file: "/path/to/your/image_mean.binaryproto"
 81        batch_size: 128
 82        crop_size: 227
 83        mirror: false
 84      }
 85      top: "data_blob_name"
 86      top: "label_blob_name"
 87    }
 88    layers {
 89      name: "drop7"
 90      type: DROPOUT
 91      dropout_param {
 92        dropout_ratio: 0.5
 93      }
 94      bottom: "fc7"
 95      top: "fc7"
 96    }
 97    */
 98   std::string feature_extraction_proto(argv[++arg_pos]);
 99   shared_ptr<Net<Dtype> > feature_extraction_net(
100       new Net<Dtype>(feature_extraction_proto, caffe::TEST));
101   feature_extraction_net->CopyTrainedLayersFrom(pretrained_binary_proto);
102 
103   std::string extract_feature_blob_names(argv[++arg_pos]);
104   std::vector<std::string> blob_names;
105   boost::split(blob_names, extract_feature_blob_names, boost::is_any_of(","));
106 
107   std::string save_feature_dataset_names(argv[++arg_pos]);
108   std::vector<std::string> dataset_names;
109   boost::split(dataset_names, save_feature_dataset_names,
110                boost::is_any_of(","));
111   CHECK_EQ(blob_names.size(), dataset_names.size()) <<
112       " the number of blob names and dataset names must be equal";
113   size_t num_features = blob_names.size();
114 
115   for (size_t i = 0; i < num_features; i++) {
116     CHECK(feature_extraction_net->has_blob(blob_names[i]))
117         << "Unknown feature blob name " << blob_names[i]
118         << " in the network " << feature_extraction_proto;
119   }
120 
121   int num_mini_batches = atoi(argv[++arg_pos]);
122 
123   std::vector<shared_ptr<db::DB> > feature_dbs;
124   std::vector<shared_ptr<db::Transaction> > txns;
125   const char* db_type = argv[++arg_pos];
126   for (size_t i = 0; i < num_features; ++i) {
127     LOG(INFO)<< "Opening dataset " << dataset_names[i];
128     shared_ptr<db::DB> db(db::GetDB(db_type));
129     db->Open(dataset_names.at(i), db::NEW);
130     feature_dbs.push_back(db);
131     shared_ptr<db::Transaction> txn(db->NewTransaction());
132     txns.push_back(txn);
133   }
134 
135   LOG(ERROR)<< "Extacting Features";
136 
137   Datum datum;
138   const int kMaxKeyStrLength = 100;
139   char key_str[kMaxKeyStrLength];
140   std::vector<Blob<float>*> input_vec;
141   std::vector<int> image_indices(num_features, 0);
142   for (int batch_index = 0; batch_index < num_mini_batches; ++batch_index) {
143     feature_extraction_net->Forward(input_vec);
144     for (int i = 0; i < num_features; ++i) {
145       const shared_ptr<Blob<Dtype> > feature_blob = feature_extraction_net
146           ->blob_by_name(blob_names[i]);
147       int batch_size = feature_blob->num();
148       int dim_features = feature_blob->count() / batch_size;
149       const Dtype* feature_blob_data;
150       for (int n = 0; n < batch_size; ++n) {
151         datum.set_height(feature_blob->height());
152         datum.set_width(feature_blob->width());
153         datum.set_channels(feature_blob->channels());
154         datum.clear_data();
155         datum.clear_float_data();
156         feature_blob_data = feature_blob->cpu_data() +
157             feature_blob->offset(n);
158         for (int d = 0; d < dim_features; ++d) {
159           datum.add_float_data(feature_blob_data[d]);
160         }
161         int length = snprintf(key_str, kMaxKeyStrLength, "%010d",
162             image_indices[i]);
163         string out;
164         CHECK(datum.SerializeToString(&out));
165         txns.at(i)->Put(std::string(key_str, length), out);
166         ++image_indices[i];
167         if (image_indices[i] % 1000 == 0) {
168           txns.at(i)->Commit();
169           txns.at(i).reset(feature_dbs.at(i)->NewTransaction());
170           LOG(ERROR)<< "Extracted features of " << image_indices[i] <<
171               " query images for feature blob " << blob_names[i];
172         }
173       }  // for (int n = 0; n < batch_size; ++n)
174     }  // for (int i = 0; i < num_features; ++i)
175   }  // for (int batch_index = 0; batch_index < num_mini_batches; ++batch_index)
176   // write the last batch
177   for (int i = 0; i < num_features; ++i) {
178     if (image_indices[i] % 1000 != 0) {
179       txns.at(i)->Commit();
180     }
181     LOG(ERROR)<< "Extracted features of " << image_indices[i] <<
182         " query images for feature blob " << blob_names[i];
183     feature_dbs.at(i)->Close();
184   }
185 
186   LOG(ERROR)<< "Successfully extracted the features!";
187   return 0;
188 }
View Code

 

相关文章
|
11天前
|
Linux Go 开发工具
手机上跑 DeepSeek 智能体:开源安卓客户端 DSH Go 安装与使用指南
DSH Go 是一款开源安卓客户端,将 DeepSeek Harness 智能体引擎装进手机:免 Root、免 Termux,一键安装即用;支持本机运行(内置 Ubuntu+Node.js)或远程接管电脑会话;具备插话打断、过程折叠、屏幕操控、端到端加密分享等特色功能,真正实现智能体“口袋化”。
11861 33
|
11天前
|
弹性计算 人工智能 API
Codex超详细入门指南(下载·安装·登录·上手,全版本覆盖,2026最新版)
建议收藏本教程,2026 全年各版本更新随时回来查阅。如果你在搭建过程中遇到任何问题,欢迎结合 阿里云工单系统 提交技术支持请求,或在 阿里云开发者社区 搜索 Codex 相关话题交流。 祝你编码愉快,效率翻倍!
3021 19
|
6天前
|
人工智能 安全 应用服务中间件
NGINX 爆出两处高危漏洞 可导致未经身份验证的远程代码执行
NGINX曝出两个高危漏洞(CVE-2026-123633和CVE-2026-123007),CVSS 9.2分,均属HTTP/2内存安全缺陷,无需认证即可远程执行代码。影响自2015年起的多个版本,静态站点亦受威胁。修复版本为开源版1.30.7/1.31.9。(239字)
1525 4
NGINX 爆出两处高危漏洞 可导致未经身份验证的远程代码执行
|
9天前
|
传感器 安全 区块链
Windows 电脑运行安卓应用教程:开源工具 ApkStart 双击 APK 即装、独立窗口运行
ApkStart 是一款开源Windows工具,让安卓APP像原生软件一样运行:双击APK即安装、生成真实图标、独立窗口启动、开始菜单可搜索。无需传统模拟器,内置QEMU运行时,支持数据互通、ARM兼容与命令行操作。(239字)
|
2天前
|
存储 安全 网络协议
模型列表里看不到新上线的模型?分清内置目录、端点探测与能力声明
在 DSH 中配置模型提供商时,最容易混淆的是三类不同的「模型信息来源」:**已安装目录**、**端点实时探测**和**使用者自行声明的能力**。内置提供商的探测结果来自已安装目录,即使 API 地址指向网关,也不会变成网关的实时列表;列表中出现某个模型 ID,也不代表端点确实支持相应的上下文窗口或图片输入。本文依次梳理三个配置路径、列表看似过时的原因、探测与真实请求的区别、凭据和网络的排查方式,以及安全边界。
448 95
|
13天前
|
人工智能 前端开发 API
阿里云Qwen4-Max 大模型详解:定位、特征、能力、适用场景与相对Qwen3-Max差异解析
2026年11月11日,阿里发布第四代旗舰模型Qwen4-Max预览版,首发千问AI平台Token Plan并接入千问办公、Qoder等入口。该版本聚焦知识理解、世界感知、编程与Agentic四项升级,主打复杂编程、专业办公、前端设计与专业软件操作等真实任务。预览期为11月11日10:00至11月25日24:00,仅支持Token Plan调用,到期后模型标识下线;限时2折、新用户再享5折,最低1折可体验。
|
8天前
|
人工智能
Google 提示「所在地区不可用」?进不去 Antigravity 或 Gemini,先查账号这个设置
进不去 Antigravity 或 Gemini,提示所在地区不可用?三步查清 Google 账号关联地区、官方更正表单理由选法与改区注意事项。
Google 提示「所在地区不可用」?进不去 Antigravity 或 Gemini,先查账号这个设置
|
13天前
|
JSON 前端开发 API
阿里云最新Qwen4-Max大模型介绍:模型定位、特征、能力、适用场景解析
2026 年 11 月 11 日,阿里发布第四代旗舰模型Qwen4-Max预览版,首发千问 AI 平台 Token Plan,并同步接入千问办公、Qoder 等入口。该版本聚焦知识理解、世界感知、编程与 Agentic 四项升级,主打复杂编程、专业办公、前端设计与专业软件操作。预览期至 11 月 25 日 24:00,到期后模型标识下线;限时 2 折、新用户再享 5 折,最低 1 折可体验。
|
9天前
|
人工智能 弹性计算 开发工具
零成本玩各大模型!DeepSeek Harness dsh-our-free-model 插件,13 个厂商模型直接用
总结一下:装这个插件,你不用注册、不用绑卡、不用填一个 Key,就能在 DeepSeek Harness 里用上 DeepSeek V4.1 Flash、Kimi K3 这一批前沿模型,而且是白嫖的、还不限量。三步搞定:下载插件,复制包含 `package.json` 的插件目录路径,在「添加插件」里粘贴路径安装并重启。无论是在阿里云 ECS 上通过命令行部署的 Web 版,还是本地的 Electron 桌面端,都能顺利跑通,快速搭建一套零成本的免费模型使用环境。
1673 1
|
12天前
|
Linux API iOS开发
【DSH】DeepSeek Harness新手保姆教程(下载+安装+配置+使用,2026最新实测)
DeepSeek Harness(dsh)是DeepSeek AI开源的智能体框架,秉持“一切皆插件”理念,支持读文件、改代码、跑命令、处理表格、联网搜索等操作。免费开源,兼容Windows/macOS/Linux,提供桌面端与网页端,可灵活安装插件扩展能力。

热门文章

最新文章