網站搜尋

如何從 TypeScript 使用 TensorFlow JS (tfjs)?


我已經嘗試安裝型別定義:

npm install --save @type/tfjs
npm install --save @type/tenforflowjs
npm install --save @type/tensorflow

但是它並不存在。在 TensorFlow JS 的 GitHub 倉庫中,我可以看到它是使用 TypeScript 開發的,但似乎他們沒有發佈定義。如果真的沒有定義發佈(希望我錯了),我如何使用他們的 GitHub 倉庫來獲取它,同時仍然能從他們未來的版本中受益?

答案#1

請注意,不幸的是,沒有簡單的方法可以判斷一個庫中是否提供類型,因為類型定義可以通過多種方式導出。

如果你執行 npm install --save @tensorflow/tfjs,你會看到有一個 node_modules/@tensorflow/tfjs/dist/index.d.ts。此外,在專案的 package.json 中,有 "types": "dist/index.d.ts"。

也就是說,此庫提供型別。

如果套件中未包含型別,您可以查看 DefinitelyTyped,看看是否有第三方定義可在 @types/{package} 使用。否則,您將需要自行處理強型別。

答案#2

要安裝 tensorflow.js,請執行:

npm install --save @tensorflow/tfjs

要匯入到你的 *.ts 檔案,請執行:

import * as tf from '@tensorflow/tfjs';

仍然有麻煩嗎?

確保 tsconfig.json 包含 "compilerOptions" 並設有 "moduleResolution": "node"