C++ 和機器學習:使用 C++ 執行 ML 任務的簡介

2023-05-31 18:40:10    編輯: robot
導讀 C++ 和機器學習:使用 C++ 執行 ML 任務的簡介 介紹 C++ 是一種高性能編程語言,非常適合機器學習( ML ) 任務。盡管它在 ML 中可能不像 Python 或 R 那樣流行,但它在速...

C++ 和機器學習:使用 C++ 執行 ML 任務的簡介

介紹

C++ 是一種高性能編程語言,非常適合機器學習( ML ) 任務。盡管它在 ML 中可能不像 Python 或 R 那樣流行,但它在速度和內存效率方面具有優勢。

在本文中,我們將概述使用 C++ 執行 ML 任務。

C++ 中的 ML 庫

C++ 中有幾個用於機器學習的庫,包括:

TensorFlow:TensorFlow 是由 Google 开發的一個流行的 ML 庫,用 C++ 和 Python 編寫。TensorFlow 提供了一套廣泛的工具來構建和部署 ML 模型,包括對深度學習和神經網絡的支持。OpenCV:OpenCV 是一個用 C++ 編寫的开源計算機視覺庫。OpenCV 提供了廣泛的圖像和視頻處理工具,包括特徵檢測、對象識別和人臉檢測。Dlib:Dlib 是一個用於機器學習的 C++ 庫,由 Davis King 开發。Dlib 提供了對象檢測、人臉識別和圖像處理等工具。LightGBM:LightGBM 是一個用 C++ 編寫的快速且高性能的梯度提升庫。它爲使用梯度提升算法構建 ML 模型提供了可擴展且高效的解決方案。XGBoost:XGBoost 是另一個用 C++ 編寫的梯度提升庫。XGBoost 提供了用於構建決策樹和樹集合的工具,使其成爲解決復雜 ML 問題的熱門選擇。Eigen:一個用於线性代數運算的 C++ 庫,通常在 ML 中用於矩陣計算。使用 C++ 進行 ML 的優勢

將 C++ 用於 ML 任務的一些優勢包括:

速度:C++ 是一種編譯型語言,這意味着它可以比 Python 等解釋型語言更快地執行代碼。內存效率:C++ 是一種低級語言,可直接控制內存使用,這在處理大型數據集時非常重要。可移植性:C++ 代碼可以在廣泛的平台上編譯和運行,使其成爲構建需要在不同操作系統上運行的 ML 應用程序的不錯選擇。與現有代碼集成:C++ 通常用於金融和工程等行業,其中可能存在需要與 ML 模型集成的現有代碼庫。將 C++ 用於 ML 的挑战將 C++ 用於 ML 任務也會帶來一些挑战,包括:陡峭的學習曲线:C++ 是一種復雜的語言,需要大量的經驗和技能才能有效使用。缺乏庫:雖然 C++ 中有幾個可用於 ML 的庫,但生態系統不如 Python 豐富。缺乏靈活性:C++ 可能不如解釋型語言靈活,這使得嘗試不同的 ML 技術變得更加困難。調試:C++ 比解釋語言更難調試,因爲它是一種編譯語言。代碼復雜性:用 C++ 編寫代碼可能比用解釋型語言編寫代碼更復雜,因爲 C++ 提供了對硬件的更多低級控制。使用 C++ 進行機器學習的基本步驟

要將 C++ 用於 ML 任務,你需要遵循以下基本步驟:

數據預處理:在此步驟中,你將通過清理、轉換和規範化數據來爲機器學習任務准備數據。模型構建:接下來,你將使用 TensorFlow 或 OpenCV 等 C++ 機器學習庫來構建你的 ML 模型。你將定義模型的架構,指定優化算法和損失函數,並使用預處理數據訓練模型。模型評估:訓練模型後,你需要在單獨的測試集上評估其性能。此步驟可幫助你確定模型是否過度擬合或欠擬合訓練數據。部署:一旦你有了一個在測試集上表現良好的模型,你就可以將它部署到生產環境中,它可以用來對新數據進行預測。機器學習中的 C++ 示例

有幾個 C++ 用於機器學習任務的示例,包括:

圖像識別:OpenCV 是一個流行的 C++ 庫,用於計算機視覺任務,包括圖像識別。它可用於爲對象檢測、人臉識別和其他圖像識別任務構建深度學習模型。自然語言處理( NLP ):C++ 可用於爲文本分類、情感分析和語言翻譯等任務構建 NLP 模型。TensorFlow 等庫可用於爲 NLP 任務構建神經網絡模型。金融建模:C++ 通常用於金融領域,以構建預測股票價格、信用風險和其他金融指標的模型。像 Dlib 這樣的庫可用於爲金融應用程序構建機器學習模型。使用 C++ 進行機器學習的技巧

以下是一些可幫助你开始使用 C++ 執行 ML 任務的提示:

從一個庫开始:C++ 中有幾個可用的機器學習庫,例如 TensorFlow、OpenCV 和 Dlib。選擇一個最適合你需求的庫,然後开始使用該庫構建你的 ML 模型。學習 C++ 的基礎知識:在深入學習 ML 任務之前,請確保你對 C++ 語言的基礎知識有很好的理解,例如數據類型、控制結構和函數。使用可用資源:有多種資源可用於學習 C++ 並將其用於 ML 任務。你可以參加在线課程、閱讀書籍或加入在线社區以獲得幫助和指導。試驗不同的 ML 技術:C++ 可能不如解釋型語言靈活,但它仍然允許你試驗不同的 ML 技術。嘗試不同的優化算法、損失函數和模型架構,以找到解決問題的最佳方法。優化代碼:C++ 提供對內存使用的直接控制,因此請確保優化代碼以減少內存使用並提高性能。使用動態內存分配和指針等技術來減少內存使用。不斷學習:機器學習領域在不斷發展,新的技術和庫也在不斷發展。不斷學習並緊跟最新趨勢,以保持該領域的競爭力。

C++ 已經存在了幾十年,並在遊戲、金融和電信等多個行業證明了它的價值。近年來,隨着 AI 和 ML 的出現,C++ 被更頻繁地用於構建高性能 ML 模型。隨着對能夠處理大量數據並提供實時預測的 ML 模型的需求不斷增加,C++ 有望在 ML 的未來發揮重要作用。

下面是一個使用 Tensorflow 創建和運行簡單神經網絡的 C++ 代碼的簡單示例:

#include 

#include "tensorflow/core/public/session.h"

#include "tensorflow/core/platform/env.h"

using namespace std;

using namespace tensorflow;

int main()

{

  // Create a graph for the neural network

  GraphDef graph_def;

  Status status = ReadBinaryProto(Env::Default(), "model.pb", &graph_def);

  if (!status.ok()) {

    cerr << "Error reading graph definition: " << status.ToString() << endl;

    return 1;

  }

  // Create a new Tensorflow session and load the graph

  SessionOptions session_options;

  Session* session = NewSession(session_options);

  status = session->Create(graph_def);

  if (!status.ok()) {

    cerr << "Error creating Tensorflow session: " << status.ToString() << endl;

    return 1;

  }

  // Define the input and output tensors

  Tensor input_tensor(DT_FLOAT, TensorShape({1, 2}));

  input_tensor.flat().data()[0] = 1.0;

  input_tensor.flat().data()[1] = 2.0;

  vector<pair<string, Tensor>> inputs = {

    {"input_tensor", input_tensor},

  };

  vector output_names = {"output_tensor"};

  // Run the graph

  vector outputs;

  status = session->Run(inputs, output_names, {}, &outputs);

  if (!status.ok()) {

    cerr << "Error running session: " << status.ToString() << endl;

    return 1;

  }

  // Print the output tensor value

  const auto& output_tensor = outputs[0];

  cout << "Output tensor value: " << output_tensor.flat()(0) << endl;

  // Clean up

  session->Close();

  delete session;

  return 0;

}

此代碼假定你已經創建了 Tensorflow 模型並將其保存爲 protobuf 文件(例如,model.pb)。代碼從此文件加載圖形定義,創建新的 Tensorflow 會話,並使用指定的輸入張量運行圖形。最後,代碼打印輸出張量的值。

請注意,編譯時需要將 C++ 代碼與 Tensorflow 庫鏈接起來。例如,如果你已經使用安裝了Tensorflow pip,你可以使用下面的命令來編譯上面的代碼:

g++ -std=c++11 -I/usr/local/lib/python3.9/dist-packages/tensorflow/include -L/usr/local/lib/python3.9/dist-packages/tensorflow -ltensorflow_cc -ltensorflow_framework example.cpp -o example

注意上面的編譯命令假設你已經安裝了Tensorflow using pip並且正在使用Linux系統。該命令可能需要根據你的安裝和系統進行調整。

爲了在 C++ 中使用 Tensorflow 創建你自己的神經網絡,你需要使用 Tensorflow 的 C++ API 定義網絡圖。

下面是一個示例,說明如何定義具有一個隱藏層的簡單全連接神經網絡:

#include 

#include "tensorflow/core/framework/tensor.h"

#include "tensorflow/core/framework/tensor_shape.h"

#include "tensorflow/core/framework/types.pb.h"

#include "tensorflow/core/graph/default_device.h"

#include "tensorflow/core/graph/graph_def_builder.h"

#include "tensorflow/core/graph/node_builder.h"

#include "tensorflow/core/lib/core/errors.h"

#include "tensorflow/core/lib/core/stringpiece.h"

#include "tensorflow/core/lib/core/threadpool.h"

#include "tensorflow/core/lib/gtl/array_slice.h"

#include "tensorflow/core/lib/gtl/inlined_vector.h"

#include "tensorflow/core/platform/init_main.h"

#include "tensorflow/core/platform/logging.h"

#include "tensorflow/core/platform/types.h"

#include "tensorflow/core/public/session.h"

using namespace std;

using namespace tensorflow;

int main()

{

  // Create a graph for the neural network

  GraphDef graph_def;

  auto options = SessionOptions();

  options.config.mutable_gpu_options()->set_allow_growth(true);

  auto session = NewSession(options);

  

  auto root = tensorflow::Scope::NewRootScope();

  auto input_tensor = Placeholder(root.WithOpName("input_tensor"), DT_FLOAT, Placeholder::Shape({1, 2}));

  

  auto w1_tensor = Variable(root.WithOpName("w1"), {2, 4}, DT_FLOAT);

  auto b1_tensor = Variable(root.WithOpName("b1"), {1, 4}, DT_FLOAT);

  auto hidden_tensor = Add(root.WithOpName("hidden"), MatMul(root.WithOpName("matmul"), input_tensor, w1_tensor), b1_tensor);

  

  auto w2_tensor = Variable(root.WithOpName("w2"), {4, 1}, DT_FLOAT);

  auto b2_tensor = Variable(root.WithOpName("b2"), {1, 1}, DT_FLOAT);

  auto output_tensor = Add(root.WithOpName("output"), MatMul(root.WithOpName("matmul2"), hidden_tensor, w2_tensor), b2_tensor);

  

  auto graph_status = root.ToGraphDef(&graph_def);

  if (!graph_status.ok()) {

    cerr << "Error creating graph definition: " << graph_status.ToString() << endl;

    return 1;

  }

  

  auto session_status = session->Create(graph_def);

  if (!session_status.ok()) {

    cerr << "Error creating Tensorflow session: " << session_status.ToString() << endl;

    return 1;

  }

  // Define the input tensor and run the graph

  Tensor input_data(DT_FLOAT, TensorShape({1, 2}));

  input_data.flat().data()[0] = 1.0;

  input_data.flat().data()[1] = 2.0;

  vector<pair<string, Tensor>> inputs = {

    {"input_tensor", input_data},

  };

  vector output_names = {"output"};

  vector outputs;

  auto run_status = session->Run(inputs, output_names, {}, &outputs);

  if (!run_status.ok()) {

    cerr << "Error running session: " << run_status.ToString() << endl;

    return 1;

  }

  // Print the output tensor value

  const auto& output_tensor = outputs[0];

  cout << "Output tensor value: " << output_tensor.flat()(0) << endl;

  return 0;

}

上面的代碼是使用Tensorflow C++ API 定義的帶有一個隱藏層的全連接神經網絡示例。網絡的輸入張量形狀爲 (1, 2),輸出張量形狀爲 (1, 1)。網絡的隱藏層有四個單元,使用 ReLU 激活函數。網絡是使用各種 Tensorflow 操作定義的,例如Add、MatMul和Placeholder。

定義神經網絡圖後,代碼會創建一個 Tensorflow 會話來運行該圖。然後將輸入數據輸入到圖中,並執行該圖以檢索輸出張量。

要使用此代碼,你需要安裝Tensorflow C++ 庫並將相關的頭文件包含在你的 C++ 代碼中。編譯代碼時,還需要鏈接到 Tensorflow C++ 庫。

結論總之,將 C++ 用於機器學習任務可能是一種具有挑战性但有益的體驗。C++ 提供對內存使用的直接控制,使其比解釋型語言的內存效率更高,並且它提供速度和可移植性,使其成爲構建高性能 ML 模型的合適選擇。但是,將 C++ 用於 ML 任務需要在學習語言和使用可用庫方面進行大量投資。

如果你是一名希望學習 C++ 來完成 ML 任務的程序員,我們建議你從 TensorFlow 或 OpenCV 等庫开始,並學習該語言的基礎知識。試驗不同的 ML 技術並優化你的代碼以減少內存使用並提高性能。隨着 ML 領域的不斷發展,C++ 有望在高性能 ML 模型的开發中發揮重要作用。

       原文標題 : C++ 和機器學習:使用 C++ 執行 ML 任務的簡介



標題:C++ 和機器學習:使用 C++ 執行 ML 任務的簡介

地址:https://www.utechfun.com/post/220258.html

鄭重聲明:本文版權歸原作者所有,轉載文章僅為傳播信息之目的,不構成任何投資建議,如有侵權行為,請第一時間聯絡我們修改或刪除,多謝。

猜你喜歡