Auto Byte

专注未来出行及智能汽车科技

微信扫一扫获取更多资讯

Science AI

关注人工智能与其他前沿技术、基础学科的交叉研究与融合发展

微信扫一扫获取更多资讯

如何用C++在TensorFlow中训练深度神经网络

目前流行的深度学习框架 TensorFlow 是以 C++为底层构建的,但绝大多数人都在 Python 上使用 TensorFlow 来开发自己的模型。随着 C++ API 的完善,直接使用 C++来搭建神经网络已经成为可能,本文将向你介绍一种简单的实现方法。

很多人都知道 TensorFlow 的核心是构建在 C++之上的,但是这种深度学习框架的大多数功能只在 Python API 上才方便使用。

当我写上一篇文章的时候,我的目标是仅使用 TensorFlow 中的 C++ API 和 CuDNN 来实现基本的深度神经网络(DNN)。在实践中,我意识到在这个过程中我们忽略了很多东西。

注意,使用外部操作(exotic operations)训练神经网络是不可能的,你面临的错误最有可能就是缺少梯度运算。目前我正在试图将 Python 上的梯度运算迁移到 C++上。

在本文中,我将展示如何使用 TensorFlow 在 C++上构建深度神经网络,并通过车龄、公里数和使用油品等条件为宝马 1 系汽车进行估价。目前,我们还没有可用的 C++优化器,所以你会看到训练代码看起来不那么吸引人,但是我们会在未来加入的。

  • 本文章遵从 TensorFlow 1.4 C++ API 官方指南:https://www.tensorflow.org/api_guides/cc/guide
  • 代码 GitHub:https://github.com/theflofly/dnn_tensorflow_cpp

安装

我们会在 C++中运行 TensorFlow 框架,我们需要尝试使用已编译的库,但肯定有些人会因为环境的特殊性而遇到麻烦。从头开始构建 TensorFlow 将避免这些问题,同时确保使用的是最新版本的 API。

首先,你需要安装 bazel 构建工具,这里有安装方法:https://docs.bazel.build/versions/master/install.html

在 OSX 上 brew 就足够了:

  1. brew install bazel

你需要从 TensorFlow 源文件开始构建:

  1. mkdir /path/tensorflow

  2. cd /path/tensorflow

  3. git clone https://github.com/tensorflow/tensorflow.git

随后你需要进行配置,如选择是否使用 GPU,你需要这样运行配置脚本:

  1. cd /path/tensorflow

  2. ./configure

现在我们要创建接收 TensorFlow 模型代码的文件。请注意,第一次构建需要花费很长一段时间(10-15 分钟)。非核心的 C++ TF 代码在/tensorflow/cc 中,这是我们创建模型文件的位置,我们也需要 BUILD 文件让 bazel 可以构建模型。

  1. mkdir /path/tensorflow/model

  2. cd /path/tensorflow/model

  3. touch model.cc

  4. touch BUILD

我们在 BUILD 文件中加入 bazel 指令:

  1. load("//tensorflow:tensorflow.bzl", "tf_cc_binary")

  2. tf_cc_binary(

  3.    name = "model",

  4.    srcs = [

  5.        "model.cc",

  6.    ],

  7.    deps = [

  8.        "//tensorflow/cc:gradients",

  9.        "//tensorflow/cc:grad_ops",

  10.        "//tensorflow/cc:cc_ops",

  11.        "//tensorflow/cc:client_session",

  12.        "//tensorflow/core:tensorflow"

  13.    ],

  14. )

基本上,它会使用 model.cc 构建一个二进制文件。现在,我们可以开始编写自己的模型了。

读取数据

这些数据从法国网站 leboncoin.fr 上摘取,随后被清理和归一化,并被存储于 CSV 文件中。我们的目标是读取这些数据。经归一化的源数据被存储在 CSV 文件的第一行,我们需要使用它们重构神经网络输出的价格。所以,我们创建 data_set.h 和 data_set.cc 文件来保持代码清洁。它们从 CSV 文件中生成一个浮点型的二维数组,并用于馈送到神经网络。

  1. using namespace std;

  2. // Meta data used to normalize the data set. Useful to

  3. // go back and forth between normalized data.

  4. class DataSetMetaData {

  5. friend class DataSet;

  6. private:

  7.  float mean_km;

  8.  float std_km;

  9.  float mean_age;

  10.  float std_age;

  11.  float min_price;

  12.  float max_price;

  13. };

  14. enum class Fuel {

  15.    DIESEL,

  16.    GAZOLINE

  17. };

  18. class DataSet {

  19. public:

  20.  // Construct a data set from the given csv file path.

  21.  DataSet(string path) {

  22.    ReadCSVFile(path);

  23.  }

  24.  // getters

  25.  vector<float>& x() { return x_; }

  26.  vector<float>& y() { return y_; }

  27.  // read the given csv file and complete x_ and y_

  28.  void ReadCSVFile(string path);

  29.  // convert one csv line to a vector of float

  30.  vector<float> ReadCSVLine(string line);

  31.  // normalize a human input using the data set metadata

  32.  initializer_list<float> input(float km, Fuel fuel, float age);

  33.  // convert a price outputted by the DNN to a human price

  34.  float output(float price);

  35. private:

  36.  DataSetMetaData data_set_metadata;

  37.  vector<float> x_;

  38.  vector<float> y_;

  39. };

data_set.cc

  1. #include <vector>

  2. #include <fstream>

  3. #include <sstream>

  4. #include <iostream>

  5. #include "data_set.h"

  6. using namespace std;

  7. void DataSet::ReadCSVFile(string path) {

  8.  ifstream file(path);

  9.  stringstream buffer;

  10.  buffer << file.rdbuf();

  11.  string line;

  12.  vector<string> lines;

  13.  while(getline(buffer, line, '\n')) {

  14.    lines.push_back(line);

  15.  }

  16.  // the first line contains the metadata

  17.  vector<float> metadata = ReadCSVLine(lines[0]);

  18.  data_set_metadata.mean_km = metadata[0];

  19.  data_set_metadata.std_km = metadata[1];

  20.  data_set_metadata.mean_age = metadata[2];

  21.  data_set_metadata.std_age = metadata[3];

  22.  data_set_metadata.min_price = metadata[4];

  23.  data_set_metadata.max_price = metadata[5];

  24.  // the other lines contain the features for each car

  25.  for (int i = 2; i < lines.size(); ++i) {

  26.    vector<float> features = ReadCSVLine(lines[i]);

  27.    x_.insert(x_.end(), features.begin(), features.begin() + 3);

  28.    y_.push_back(features[3]);

  29.  }

  30. }

  31. vector<float> DataSet::ReadCSVLine(string line) {

  32.  vector<float> line_data;

  33.  std::stringstream lineStream(line);

  34.  std::string cell;

  35.  while(std::getline(lineStream, cell, ','))

  36.  {

  37.    line_data.push_back(stod(cell));

  38.  }

  39.  return line_data;

  40. }

  41. initializer_list<float> DataSet::input(float km, Fuel fuel, float age) {

  42.  km = (km - data_set_metadata.mean_km) / data_set_metadata.std_km;

  43.  age = (age - data_set_metadata.mean_age) / data_set_metadata.std_age;

  44.  float f = fuel == Fuel::DIESEL ? -1.f : 1.f;

  45.  return {km, f, age};

  46. }

  47. float DataSet::output(float price) {

  48.  return price * (data_set_metadata.max_price - data_set_metadata.min_price) + data_set_metadata.min_price;

  49. }

我们必须在 bazel BUILD 文件中添加这两个文件。

  1. load("//tensorflow:tensorflow.bzl", "tf_cc_binary")

  2. tf_cc_binary(

  3.    name = "model",

  4.    srcs = [

  5.        "model.cc",

  6.        "data_set.h",

  7.        "data_set.cc"

  8.    ],

  9.    deps = [

  10.        "//tensorflow/cc:gradients",

  11.        "//tensorflow/cc:grad_ops",

  12.        "//tensorflow/cc:cc_ops",

  13.        "//tensorflow/cc:client_session",

  14.        "//tensorflow/core:tensorflow"

  15.    ],

  16. )

构建模型

第一步是读取 CSV 文件,并提取出两个张量,其中 x 是输入,y 为预期的真实结果。我们使用之前定义的 DataSet 类。

CSV 数据集下载链接:https://github.com/theflofly/dnn_tensorflow_cpp/blob/master/normalized_car_features.csv

  1. DataSet data_set("/path/normalized_car_features.csv");

  2. Tensor x_data(DataTypeToEnum<float>::v(),

  3.              TensorShape{static_cast<int>(data_set.x().size())/3, 3});

  4. copy_n(data_set.x().begin(), data_set.x().size(),

  5.       x_data.flat<float>().data());

  6. Tensor y_data(DataTypeToEnum<float>::v(),

  7.              TensorShape{static_cast<int>(data_set.y().size()), 1});

  8. copy_n(data_set.y().begin(), data_set.y().size(),

  9.       y_data.flat<float>().data());

要定义一个张量,我们需要知道它的类型和形状。在 data_set 对象中,x 数据以向量的方式保存,所以我们将尺寸缩减为 3(每个保存三个特征)。随后我们使用 std::copy_n 来从 data_set 对象中复制数据到 Tensor(一个 Eigen::TensorMap)的底层数据结构中。现在,我们有了数据和 TensorFlow 数据结构,是时候构建模型了。

你可以轻易地 debug 一个张量:

  1. LOG(INFO) << x_data.DebugString();

C ++ API 的独特之处在于,您需要一个 Scope 对象来保持构建静态计算图的状态,并将该对象传递给每个操作。

  1. Scope scope = Scope::NewRootScope();

我们需要两个占位符,x 包含特征,y 代表每辆车相应的价格。

  1. auto x = Placeholder(scope, DT_FLOAT);

  2. auto y = Placeholder(scope, DT_FLOAT);

我们的网络有两个隐藏层,因此我们会有三个权重矩阵和三个偏置项向量。在 Python 中,它是由底层直接完成的,在 C++中你必须定义一个变量,随后定义一个 Assign 节点以为该变量分配一个默认值。我们使用 RandomNormal 来初始化我们的变量,这会给我们一个服从正态分布的随机值。

  1. // weights init

  2. auto w1 = Variable(scope, {3, 3}, DT_FLOAT);

  3. auto assign_w1 = Assign(scope, w1, RandomNormal(scope, {3, 3}, DT_FLOAT));

  4. auto w2 = Variable(scope, {3, 2}, DT_FLOAT);

  5. auto assign_w2 = Assign(scope, w2, RandomNormal(scope, {3, 2}, DT_FLOAT));

  6. auto w3 = Variable(scope, {2, 1}, DT_FLOAT);

  7. auto assign_w3 = Assign(scope, w3, RandomNormal(scope, {2, 1}, DT_FLOAT));

  8. // bias init

  9. auto b1 = Variable(scope, {1, 3}, DT_FLOAT);

  10. auto assign_b1 = Assign(scope, b1, RandomNormal(scope, {1, 3}, DT_FLOAT));

  11. auto b2 = Variable(scope, {1, 2}, DT_FLOAT);

  12. auto assign_b2 = Assign(scope, b2, RandomNormal(scope, {1, 2}, DT_FLOAT));

  13. auto b3 = Variable(scope, {1, 1}, DT_FLOAT);

  14. auto assign_b3 = Assign(scope, b3, RandomNormal(scope, {1, 1}, DT_FLOAT));

随后我们使用 Tanh 作为激活函数来构建三个层。

  1. // layers

  2. auto layer_1 = Tanh(scope, Add(scope, MatMul(scope, x, w1), b1));

  3. auto layer_2 = Tanh(scope, Add(scope, MatMul(scope, layer_1, w2), b2));

  4. auto layer_3 = Tanh(scope, Add(scope, MatMul(scope, layer_2, w3), b3));

加入 L2 正则化。

  1. // regularization

  2. auto regularization = AddN(scope,

  3.                         initializer_list<Input>{L2Loss(scope, w1),

  4.                                                 L2Loss(scope, w2),

  5.                                                 L2Loss(scope, w3)});

最后计算损失函数,即计算预测价格和实际价格 y 之间的差异,并增加正则化到损失函数中。

  1. // loss calculation

  2. auto loss = Add(scope,

  3.                ReduceMean(scope, Square(scope, Sub(scope, layer_3, y)), {0, 1}),

  4.                Mul(scope, Cast(scope, 0.01,  DT_FLOAT), regularization));

在这里,我们完成了前向传播,现在该进行反向传播了。第一步是使用函数调用,以在前向传播操作的图中加入梯度运算。

  1. // add the gradients operations to the graph

  2. std::vector<Output> grad_outputs;

  3. TF_CHECK_OK(AddSymbolicGradients(scope, {loss}, {w1, w2, w3, b1, b2, b3}, &grad_outputs));

所有的运算都需要计算损失函数对每一个变量的导数并添加到计算图中,我们初始化 grad_outputs 空向量,它在 TensorFlow 会话被使用时将梯度传入节点,grad_outputs[0] 会提供损失函数对 w1 的导数,grad_outputs[1] 提供损失函数对 w2 的导数,这一过程会根据 {w1, w2, w3, b1,b2, b3} 的顺序,也是变量被传递到 AddSymbolicGradients 的顺序进行。

现在我们在 grad_outputs 有一系列节点,当在 TensorFlow 会话中使用时,每个节点计算损失函数对一个变量的梯度。我们需要使用它来更新变量。所以,我们在每行放一个变量,使用梯度下降这个最简单的方法来更新。

  1. // update the weights and bias using gradient descent

  2. auto apply_w1 = ApplyGradientDescent(scope, w1, Cast(scope, 0.01,  DT_FLOAT), {grad_outputs[0]});

  3. auto apply_w2 = ApplyGradientDescent(scope, w2, Cast(scope, 0.01,  DT_FLOAT), {grad_outputs[1]});

  4. auto apply_w3 = ApplyGradientDescent(scope, w3, Cast(scope, 0.01,  DT_FLOAT), {grad_outputs[2]});

  5. auto apply_b1 = ApplyGradientDescent(scope, b1, Cast(scope, 0.01,  DT_FLOAT), {grad_outputs[3]});

  6. auto apply_b2 = ApplyGradientDescent(scope, b2, Cast(scope, 0.01,  DT_FLOAT), {grad_outputs[4]});

  7. auto apply_b3 = ApplyGradientDescent(scope, b3, Cast(scope, 0.01,  DT_FLOAT), {grad_outputs[5]});

Cast 操作实际上是学习速率的参数,在这里是 0.01。

我们的网络已经准备好在会话中启动,基于 Python 的 Optimizers API 基本封装了计算和应用过程中的损失函数最小化方法。当 Optimizer API 可以接入 C++时我们就可以在这里使用它了。

我们初始化一个以 ClientSession 和一个以 Tensor 命名的输出向量,用来接收网络的输出。

  1. ClientSession session(scope);

  2. std::vector<Tensor> outputs;

随后初始化变量,在 Python 中调用 tf.global_variables_initializer() 就可以,因为在构建计算图时,所有变量的列表都是保留的。在 C++中,我们必须列出变量。每个 RandomNormal 输出会分配给 Assign 节点中定义的变量。

  1. // init the weights and biases by running the assigns nodes once

  2. TF_CHECK_OK(session.Run({assign_w1, assign_w2, assign_w3, assign_b1, assign_b2, assign_b3}, nullptr));

在这一点上,我们可以在训练步骤的数量内循环地更新参数,在我们的例子中是 5000 步。第一步是使用 loss 节点运行前向传播部分,输出是网络的损失。每 100 步我们都会记录一次损失值,损失的减少是网络成功运行的标志。随后我们必须计算梯度节点并更新变量。我们的梯度节点是 ApplyGradientDescent 节点的输入,所以运行 apply_nodes 会首先计算梯度,随后将其应用到正确的变量上。

  1. // training steps

  2. for (int i = 0; i < 5000; ++i) {

  3.  TF_CHECK_OK(session.Run({{x, x_data}, {y, y_data}}, {loss}, &outputs));

  4.  if (i % 100 == 0) {

  5.    std::cout << "Loss after " << i << " steps " << outputs[0].scalar<float>() << std::endl;

  6.  }

  7.  // nullptr because the output from the run is useless

  8.  TF_CHECK_OK(session.Run({{x, x_data}, {y, y_data}}, {apply_w1, apply_w2, apply_w3, apply_b1, apply_b2, apply_b3, layer_3}, nullptr));

  9. }

在网络训练到这种程度后,我们可以尝试预测汽车的价格了——进行推断。让我们来尝试预测一辆车龄为 7 年,里程 11 万公里,柴油发动机的宝马 1 系轿车。为了这样做我们需要运行 layer_3 节点,将汽车的数据输入 x,这是一个前向传播的步骤。因为我们之前运行了 5000 步的训练,权重已经得到了学习,所以输出的结果将不是随机的。

我们不能直接使用汽车的属性,因为我们的神经网络是从归一化属性中学习的,所以数据必须经过同样的归一化过程。DataSet 类有一个 input 方法在 CSV 读取器件处理数据集中的元数据。

  1. // prediction using the trained neural net

  2. TF_CHECK_OK(session.Run({{x, {data_set.input(110000.f, Fuel::DIESEL, 7.f)}}}, {layer_3}, &outputs));

  3. cout << "DNN output: " << *outputs[0].scalar<float>().data() << endl;

  4. std::cout << "Price predicted " << data_set.output(*outputs[0].scalar<float>().data()) << " euros" << std::endl;

网络的输出值在 0 到 1 之间,data_set 的 output 方法还负责将数值从元数据转换回人类可读的数字。模型可以使用 bazel run -c opt //tensorflow/cc/models:model 命令来运行,如果 TensorFlow 刚刚被编译,你可以看到这样形式的输出:

  1. Loss after 0 steps 0.317394

  2. Loss after 100 steps 0.0503757

  3. Loss after 200 steps 0.0487724

  4. Loss after 300 steps 0.047366

  5. Loss after 400 steps 0.0460944

  6. Loss after 500 steps 0.0449263

  7. Loss after 600 steps 0.0438395

  8. Loss after 700 steps 0.0428183

  9. Loss after 800 steps 0.041851

  10. Loss after 900 steps 0.040929

  11. Loss after 1000 steps 0.0400459

  12. Loss after 1100 steps 0.0391964

  13. Loss after 1200 steps 0.0383768

  14. Loss after 1300 steps 0.0375839

  15. Loss after 1400 steps 0.0368152

  16. Loss after 1500 steps 0.0360687

  17. Loss after 1600 steps 0.0353427

  18. Loss after 1700 steps 0.0346358

  19. Loss after 1800 steps 0.0339468

  20. Loss after 1900 steps 0.0332748

  21. Loss after 2000 steps 0.0326189

  22. Loss after 2100 steps 0.0319783

  23. Loss after 2200 steps 0.0313524

  24. Loss after 2300 steps 0.0307407

  25. Loss after 2400 steps 0.0301426

  26. Loss after 2500 steps 0.0295577

  27. Loss after 2600 steps 0.0289855

  28. Loss after 2700 steps 0.0284258

  29. Loss after 2800 steps 0.0278781

  30. Loss after 2900 steps 0.0273422

  31. Loss after 3000 steps 0.0268178

  32. Loss after 3100 steps 0.0263046

  33. Loss after 3200 steps 0.0258023

  34. Loss after 3300 steps 0.0253108

  35. Loss after 3400 steps 0.0248298

  36. Loss after 3500 steps 0.0243591

  37. Loss after 3600 steps 0.0238985

  38. Loss after 3700 steps 0.0234478

  39. Loss after 3800 steps 0.0230068

  40. Loss after 3900 steps 0.0225755

  41. Loss after 4000 steps 0.0221534

  42. Loss after 4100 steps 0.0217407

  43. Loss after 4200 steps 0.0213369

  44. Loss after 4300 steps 0.0209421

  45. Loss after 4400 steps 0.020556

  46. Loss after 4500 steps 0.0201784

  47. Loss after 4600 steps 0.0198093

  48. Loss after 4700 steps 0.0194484

  49. Loss after 4800 steps 0.0190956

  50. Loss after 4900 steps 0.0187508

  51. DNN output: 0.0969611

  52. Price predicted 13377.7 euros

这里的预测车价是 13377.7 欧元。每次预测的到的车价都不相同,甚至会介于 8000-17000 之间。这是因为我们只使用了三个属性来描述汽车,而我们的的模型架构也相对比较简单。

正如之前所说的,C++ API 的开发仍在进行中,我们希望在不久的将来,更多的功能可以加入进来。

工程TensorFlowC++工程神经网络
2
暂无评论
暂无评论~