labels.size(0) 是什么意思

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
⼈⼯智能之⼝罩检测算法 由于疫情的影响,⼝罩检测已经成为各个程序员竞相开发的⼀种算法。 百度的⼈脸检测SDK使⽤的还不错,他们还把⼝罩检测也给开源了 我这⾥使⽤基于OPENCV的检测 ⼀般的思路可能就是⼿机带有⼝罩和没有戴⼝罩的数据集进⾏训练,但是我暂时没有找到这些数据集,我就采⽤使⽤opencv原来带有的训 练集先检测出⼈脸,然后再对⼈脸检测⿐⼦和嘴巴。但是由于opencv的检测⿐⼦和嘴巴的算法准确性不⾼,需要经过附加条件检测是不是 真正的嘴巴和⿐⼦,如果在⼈脸中检测出了嘴巴和⿐⼦的话,那么没有戴⼝罩puttext no mask,否则就进⾏⼈脸识别 那么要进⾏⼈脸识别的话,需要采集本⼈的数据,然后在获取ORL的数据集⼀同训练。我这⾥获取了ORL提供的40个样本,每个样本⾥⾯ 有10个bmp格式的图像。 现在我们开始获取数据集,思路很简单,就是打开摄像头,对每⼀帧图像进⾏处理。对这每⼀帧图像识别出⼈脸,如果⼈脸的size为1,那 么表⽰这就是你的⼈脸,然后把处理后的⼈脸保存起来。 为了拍摄多⾓度图像,需要每处理⼀次都需要等待,设置⼀个计数器,当经过⼗次的拍摄后,就退出程序 int makepicture() { CascadeClassifier cascada; cascada.load("E:/OPENCV/opencv/sources/data/haarcascades/haarcascade_frontalface_default.xml"); VideoCapture cap(0); Mat frame, myFace; int pic_num = 1; while (1) { cap >> frame; vector<Rect> faces;//vector容器存检测到的faces Mat frame_gray; cvtColor(frame, frame_gray, COLOR_BGR2GRAY);//转灰度化,减少运算 cascada.detectMultiScale(frame_gray, faces, 1.1, 4, CV_HAAR_DO_ROUGH_SEARCH, Size(70, 70), Size(1000, 1000)); for (int i = 0; i < faces.size(); i++) { rectangle(frame, faces[i], Scalar(255, 0, 0), 2, 8, 0); } //当只有⼀个⼈脸时,开始拍照 if (faces.size() == 1) { Mat faceROI = frame_gray(faces[0]);//在灰度图中将圈出的脸所在区域裁剪出 //cout << faces[0].x << endl;//测试下face[0].x resize(faceROI, myFace, Size(92, 112));//将兴趣域size为92*112 putText(frame, to_string(pic_num), faces[0].tl(), 3, 1.2, (0, 0, 225), 2, 0);//在 faces[0].tl()的左上⾓上⾯写序号 string filename = "样本/s41/"+to_string(pic_num)+".bmp"; //存放在当前项⽬⽂件夹以1-10.jpg 命名,format就是转为字符串 imwrite(filename, myFace);//存在当前⽬录下 imshow(filename, myFace);//显⽰下size后的脸 waitKey(500);//等待500us destroyWindow(filename);//:销毁指定的窗⼝ pic_num++;//序号加1 if (pic_num == 11) { return 0;//当序号为11时退出循环 } } int c = waitKey(10); if ((char)c == 27) { break; } //10us内输⼊esc则退出循环 imshow("frame", frame);//显⽰视频流 waitKey(100);//等待100us } return 0; } 然后需要对⾃⼰的样本进⾏处理 void initdata() { /* 对于训练样本: Ptr<FaceRecognizer> model = createLBPHFaceRecognizer(); model->train(img, labels);train函数的两个参数也很简单,训练的图像组vector<Mat>和对应的标签组vector<int>,这个label标签只需保证同⼀个⼈的标签相同 即可,不需要保证图像的按标签顺序输⼊。 */ vect
智能计算系统实验2 实验2.1:基于三层神经⽹络实现⼿写数字识别 实验⽬的 1. 实现三层神经⽹络模型进⾏⼿写数字分类,建⽴⼀个简单⽽完整的神经⽹络⼯程。通过本实验理解神经⽹络中基本模块的作⽤和模块 间的关系,为后续建⽴更复杂的神经⽹络实验(如风格迁移)奠定基础。 2. 利⽤⾼级编程语⾔Python实现神经⽹络基本单元的前向传播(正向传播)和反向传播计算,加深对神经⽹络中基本单元的理解,包括 全连接层、激活函数、损失函数等基本单元。 3. 利⽤⾼级编程语⾔Python实现神经⽹络构建,以及训练神经⽹络所使⽤的梯度下降算法,加深对神经⽹络训练过程的理解。 实验过程 数据集读取和预处理 train_labels = self.load_mnist(os.path.join(MNIST_DIR, TRAIN_LABEL), False) test_images = self.load_mnist(os.path.join(MNIST_DIR, TEST_DATA), True) test_labels = self.load_mnist(os.path.join(MNIST_DIR, TEST_LABEL), False) 全连接层 self.output = np.matmul(self.input, self.weight) + self.bias self.d_weight = np.dot(self.input.T, top_diff) self.d_bias = np.sum(top_diff, axis=0) bottom_diff = np.dot(top_diff, self.weight.T) self.weight = self.weight - lr * self.d_weight self.bias = self.bias - lr * self.d_bias relu层 output = np.maximum(0, self.input) bottom_diff = top_diff bottom_diff[self.input < 0] = 0 softmax层 self.prob = input_exp / np.sum(input_exp, axis=1, keepdims=True) bottom_diff = (self.prob - self.label_onehot) / self.batch_size 组⽹ self.fc2 = FullConnectedLayer(self.hidden1, self.hidden2) self.relu2 = ReLULayer() 前向传播和反向传播 h2 = self.fc2.forward(h1) h2 = self.relu2.forward(h2) h3 = self.fc3.forward(h2) dh3 = self.fc3.backward(dloss) dh2 = self.relu2.backward(dh3) dh2 = self.fc2.backward(dh2) 推导过程 实验打分标准 实验2.2:基于DLP平台实现⼿写数字分类 实验⽬的 熟悉深度学习处理器 DLP 平台的使⽤,能使⽤已封装好的 Python 接⼝的机器学习编程库 pycnml 将第2.1节的神经⽹络推断部分移植到 DLP 平台,实现⼿写数字分类。具体包括: 1. 利⽤提供 pycnml 库中的 Python 接⼝搭建⼿写数字分类的三层神经⽹络。 2. 熟悉在 DLP 上运⾏神经⽹络的流程,为在后续章节详细学习 DLP ⾼性能库以及智 能编程语⾔打下基础。 3. 与第2.1节的实验进⾏⽐较,了解 DLP 相对于 CPU 的优势和劣势 实验过程 基本就是第⼀个实验的简化版,将layer的创建换成了pycml的接⼝,接⼝调⽤参考实验⼿册即可,注意要加载2.1实验保存的模型参数。 实验打分标准
package com.hexiang.utils; import java.sql.*; import java.util.*; /** * * Title: 数据库工具类 * * * Description: 将大部分的数据库操作放入这个类中, 包括数据库连接的建立, 自动释放等. * * * @author beansoft 日期: 2004年04月 * @version 2.0 */ public class DatabaseUtil { /** 数据库连接 */ private java.sql.Connection connection; /** * All database resources created by this class, should be free after all * operations, holds: ResultSet, Statement, PreparedStatement, etc. */ private ArrayList resourcesList = new ArrayList(5); public DatabaseUtil() { } /** 关闭数据库连接并释放所有数据库资源 */ public void close() { closeAllResources(); close(getConnection()); } /** * Close given connection. * * @param connection * Connection */ public static void close(Connection connection) { try { connection.close(); } catch (Exception ex) { System.err.println("Exception when close a connection: " + ex.getMessage()); } } /** * Close all resources created by this class. */ public void closeAllResources() { for (int i = 0; i < this.getResourcesList().size(); i++) { closeJDBCResource(getResourcesList().get(i)); } } /** * Close a jdbc resource, such as ResultSet, Statement, Connection.... All * these objects must have a method signature is void close(). * * @param resource - * jdbc resouce to close */ public void closeJDBCResource(Object resource) { try { Class clazz = resource.getClass(); java.lang.reflect.Method method = clazz.getMethod("close", null); method.invoke(resource, null); } catch (Exception e) { // e.printStackTrace(); } } /** * 执行 SELECT 等 SQL 语句并返回结果集. * * @param sql * 需要发送到数据库 SQL 语句 * @return a ResultSet object that contains the data produced * by the given query; never null */ public ResultSet executeQuery(String sql) { try { Statement statement = getStatement(); ResultSet rs = statement.executeQuery(sql); this.getResourcesList().add(rs); this.getResourcesList().add(statement);// BUG fix at 2006-04-29 by BeanSoft, added this to res list // MySql 数据库要求必需关闭 statement 对象, 否则释放不掉资源 // - 此观点错误, 因为关闭此对象后有时数据无法读出 //statement.close(); return rs; } catch (Exception ex) { System.out.println("Error in executeQuery(\"" + sql + "\"):" + ex); // ex.printStackTrace(); return null; } } /** * Executes the given SQL statement, which may be an INSERT, * UPDATE, or DELETE statement or an SQL * statement that returns nothing, such as an SQL DDL statement. 执行给定的 SQL * 语句, 这些语句可能是 INSERT, UPDATE 或者 DELETE 语句, 或者是一个不返回任何东西的 SQL 语句, 例如一个 SQL * DDL 语句. * * @param sql * an SQL INSERT,UPDATE or * DELETE statement or an SQL statement that * returns nothing * @return either the row count for INSERT, * UPDATE or DELETE statements, or * 0 for SQL statements that return nothing */ public int executeUpdate(String sql) { try { Statement statement = getStatement(); return statement.executeUpdate(sql); // MySql 数据库要求必需关闭 statement 对象, 否则释放不掉资源 // - 此观点错误, 因为关闭此对象后有时数据无法读出 //statement.close(); } catch (Exception ex) { System.out.println("Error in executeUpdate(): " + sql + " " + ex); //System.out.println("executeUpdate:" + sql); ex.printStackTrace(); } return -1; } /** * 返回记录总数, 使用方法: getAllCount("SELECT count(ID) from tableName") 2004-06-09 * 可滚动的 Statement 不能执行 SELECT MAX(ID) 之类的查询语句(SQLServer 2000) * * @param sql * 需要执行的 SQL * @return 记录总数 */ public int getAllCount(String sql) { try { Statement statement = getConnection().createStatement(); this.getResourcesList().add(statement); ResultSet rs = statement.executeQuery(sql); rs.next(); int cnt = rs.getInt(1); rs.close(); try { statement.close(); this.getResourcesList().remove(statement); } catch (Exception ex) { ex.printStackTrace(); } return cnt; } catch (Exception ex) { System.out.println("Exception in DatabaseUtil.getAllCount(" + sql + "):" + ex); ex.printStackTrace(); return 0; } } /** * 返回当前数据库连接. */ public java.sql.Connection getConnection() { return connection; } /** * 连接新的数据库对象到这个工具类, 首先尝试关闭老连接. */ public void setConnection(java.sql.Connection connection) { if (this.connection != null) { try { getConnection().close(); } catch (Exception ex) { } } this.connection = connection; } /** * Create a common statement from the database connection and return it. * * @return Statement */ public Statement getStatement() { // 首先尝试获取可滚动的 Statement, 然后才是普通 Statement Statement updatableStmt = getUpdatableStatement(); if (updatableStmt != null) return updatableStmt; try { Statement statement = getConnection().createStatement(); this.getResourcesList().add(statement); return statement; } catch (Exception ex) { System.out.println("Error in getStatement(): " + ex); } return null; } /** * Create a updatable and scrollable statement from the database connection * and return it. * * @return Statement */ public Statement getUpdatableStatement() { try { Statement statement = getConnection() .createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); this.getResourcesList().add(statement); return statement; } catch (Exception ex) { System.out.println("Error in getUpdatableStatement(): " + ex); } return null; } /** * Create a prepared statement and return it. * * @param sql * String SQL to prepare * @throws SQLException * any database exception * @return PreparedStatement the prepared statement */ public PreparedStatement getPreparedStatement(String sql) throws SQLException { try { PreparedStatement preparedStatement = getConnection() .prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); this.getResourcesList().add(preparedStatement); return preparedStatement; } catch (Exception ex) { ex.printStackTrace(); } return null; } /** * Return the resources list of this class. * * @return ArrayList the resources list */ public ArrayList getResourcesList() { return resourcesList; } /** * Fetch a string from the result set, and avoid return a null string. * * @param rs * the ResultSet * @param columnName * the column name * @return the fetched string */ public static String getString(ResultSet rs, String columnName) { try { String result = rs.getString(columnName); if (result == null) { result = ""; } return result; } catch (Exception ex) { } return ""; } /** * Get all the column labels * * @param resultSet * ResultSet * @return String[] */ public static String[] getColumns(ResultSet resultSet) { if (resultSet == null) { return null; } try { ResultSetMetaData metaData = resultSet.getMetaData(); int numberOfColumns = metaData.getColumnCount(); if (numberOfColumns <= 0) { return null; } String[] columns = new String[numberOfColumns]; //System.err.println("numberOfColumns=" + numberOfColumns); // Get the column names for (int column = 0; column < numberOfColumns; column++) { // System.out.print(metaData.getColumnLabel(column + 1) + "\t"); columns[column] = metaData.getColumnName(column + 1); } return columns; } catch (Exception ex) { ex.printStackTrace(); } return null; } /** * Get the row count of the result set. * * @param resultset * ResultSet * @throws SQLException * if a database access error occurs or the result set type is * TYPE_FORWARD_ONLY * @return int the row count * @since 1.2 */ public static int getRowCount(ResultSet resultset) throws SQLException { int row = 0; try { int currentRow = resultset.getRow(); // Remember old row position resultset.last(); row = resultset.getRow(); if (currentRow > 0) { resultset.absolute(row); } } catch (Exception ex) { ex.printStackTrace(); } return row; } /** * Get the column count of the result set. * * @param resultSet * ResultSet * @return int the column count */ public static int getColumnCount(ResultSet resultSet) { if (resultSet == null) { return 0; } try { ResultSetMetaData metaData = resultSet.getMetaData(); int numberOfColumns = metaData.getColumnCount(); return numberOfColumns; } catch (Exception ex) { ex.printStackTrace(); } return 0; } /** * Read one row's data from result set automatically and put the result it a * hashtable. Stored as "columnName" = "value", where value is converted to * String. * * @param resultSet * ResultSet * @return Hashtable */ public static final Hashtable readResultToHashtable(ResultSet resultSet) { if (resultSet == null) { return null; } Hashtable resultHash = new Hashtable(); try { String[] columns = getColumns(resultSet); if (columns != null) { // Read data column by column for (int i = 0; i < columns.length; i++) { resultHash.put(columns[i], getString(resultSet, columns[i])); } } } catch (Exception ex) { ex.printStackTrace(); } return resultHash; } /** * Read data from result set automatically and put the result it a * hashtable. Stored as "columnName" = "value", where value is converted to * String. * * Note: assume the default database string encoding is ISO8859-1. * * @param resultSet * ResultSet * @return Hashtable */ @SuppressWarnings("unchecked") public static final Hashtable readResultToHashtableISO(ResultSet resultSet) { if (resultSet == null) { return null; } Hashtable resultHash = new Hashtable(); try { String[] columns = getColumns(resultSet); if (columns != null) { // Read data column by column for (int i = 0; i < columns.length; i++) { String isoString = getString(resultSet, columns[i]); try { resultHash.put(columns[i], new String(isoString .getBytes("ISO8859-1"), "GBK")); } catch (Exception ex) { resultHash.put(columns[i], isoString); } } } } catch (Exception ex) { ex.printStackTrace(); } return resultHash; } /** Test this class. */ public static void main(String[] args) throws Exception { DatabaseUtil util = new DatabaseUtil(); // TODO: 从连接池工厂获取连接 // util.setConnection(ConnectionFactory.getConnection()); ResultSet rs = util.executeQuery("SELECT * FROM e_hyx_trans_info"); while (rs.next()) { Hashtable hash = readResultToHashtableISO(rs); Enumeration keys = hash.keys(); while (keys.hasMoreElements()) { Object key = keys.nextElement(); System.out.println(key + "=" + hash.get(key)); } } rs.close(); util.close(); } }
### 回答1: 这是一个编程类的问题,我可以回答。这个代码片段可能是在使用 PyTorch 进行深度学习时出现的,它的作用是获取一个张量(tensor)的第一维的大小。具体来说,labels 是一个张量,size(0) 表示获取它的第一维的大小。 ### 回答2: labels.size(0)是指标签张量的第一个维度的大小。 在深度学习中,常常需要对数据进行标注,即给数据赋予一个或多个正确的标签。标签张量通常是由整数或独热编码表示的,用于表示数据的类别。 在PyTorch中,标签张量是一个多维张量,维度的数量取决于数据的类型和标签的数量。对于一个二分类任务,标签张量的维度通常为[batch_size],其中batch_size表示数据的批量大小。而对于一个多分类任务,标签张量的维度通常为[batch_size, num_classes],其中num_classes表示类别的数量。 labels.size(0)就是表示标签张量第一个维度的大小,即表示标签的个数。这个大小与批量大小或类别的数量有关,因此可以用来获取标签的数量。 举个例子,如果标签张量labels的维度为[64, 10],则labels.size(0)的值为64,表示有64个标签。如果标签张量labels的维度为[32],则labels.size(0)的值为32,表示有32个标签。 通过labels.size(0)可以方便地获取标签的数量,在进行深度学习模型的训练和评估过程中,我们常常需要统计标签的个数以及计算准确率等指标,labels.size(0)可以帮助我们方便地进行这些操作。 ### 回答3: labels.size(0)代表labels张量的第一个维度的大小。根据张量的维度,labels.size(0)返回的是labels张量第一个维度上元素的个数。 例如,若labels是一个形状为[10, 5, 7]的张量,其中10是第一个维度的大小,那么labels.size(0)返回的值就是10。 labels.size(0)常用于获取张量在第一个维度上的大小,并根据该大小进行操作。它可以用来判断张量的批处理大小,或根据批处理大小对数据进行归一化等操作。同样,它也可以用于遍历第一个维度上的元素,在训练过程中对每个批次进行操作。 总之,labels.size(0)是一个用于获取labels张量在第一个维度上大小的属性,通过它可以方便地获得labels的批处理大小以及进行相应的操作。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值