Node.js 如何部署机器学习模型

Node.js 如何部署机器学习模型

在本文中,我们将学习如何使用 Node.js 部署机器学习模型。在此过程中,我们将使用 Node.jstensorflow.js 创建一个简单的手写数字识别器

Tensorflow.js 是用于JavaScript的机器学习库。它可以将机器学习模型直接部署到Node.js或Web浏览器中。

模型训练: 为了训练模型,我们将使用Google Colab。它是一个允许我们运行所有Python代码的平台,并且已经加载了大部分常用的机器学习库。

以下是我们将创建的最终模型的代码。

# Importing Libraries 
from tensorflow.keras.datasets import mnist 
import matplotlib.pyplot as plt 
from keras.utils import np_utils 
from keras import Sequential 
from keras.layers import Dense 
import tensorflowjs as tfjs 
  
# Loading data 
(X_train, y_train), (X_test, y_test) = mnist.load_data() 
print ("X_train.shape: {}".format(X_train.shape)) 
print ("y_train.shape: {}".format(y_train.shape)) 
print ("X_test.shape: {}".format(X_test.shape)) 
print ("y_test.shape: {}".format(y_test.shape)) 
  
# Visualizing Data 
plt.subplot(161) 
plt.imshow(X_train[3], cmap=plt.get_cmap('gray')) 
plt.subplot(162) 
plt.imshow(X_train[5], cmap=plt.get_cmap('gray')) 
plt.subplot(163) 
plt.imshow(X_train[7], cmap=plt.get_cmap('gray')) 
plt.subplot(164) 
plt.imshow(X_train[2], cmap=plt.get_cmap('gray')) 
plt.subplot(165) 
plt.imshow(X_train[0], cmap=plt.get_cmap('gray')) 
plt.subplot(166) 
plt.imshow(X_train[13], cmap=plt.get_cmap('gray')) 
  
plt.show() 
  
# Normalize Inputs from 0–255 to 0–1 
X_train = X_train / 255
X_test = X_test / 255
# One-Hot Encode outputs 
y_train = np_utils.to_categorical(y_train) 
y_test = np_utils.to_categorical(y_test) 
num_classes = 10
  
# Training model 
x_train_simple = X_train.reshape(60000, 28 * 28).astype('float32') 
x_test_simple = X_test.reshape(10000, 28 * 28).astype('float32') 
model = Sequential() 
model.add(Dense(28 * 28, input_dim=28 * 28, activation='relu')) 
model.add(Dense(num_classes, activation='softmax')) 
model.compile(loss='categorical_crossentropy',  
        optimizer='adam', metrics=['accuracy']) 
model.fit(x_train_simple, y_train,  
        validation_data=(x_test_simple, y_test))

步骤1:训练数据

为了训练模型,我们将使用MNIST数据库。这是一个大型的手写数字数据库,可以免费使用。在这个数据集中,有60000个图像,它们都是灰度图像,尺寸为28 x 28像素,像素值从0到255。

步骤2:数据预处理

我们按照以下步骤处理数据:

  1. 归一化输入:输入值的范围是0-255。我们需要将它们缩放到0-1范围内。
  2. 将输出进行独热编码

步骤3:机器学习

为了训练模型,我们使用一个简单的具有一个隐藏层的神经网络,这足以达到大约98%的准确率。

步骤4:使用tensorflow.js转换模型

首先,使用以下命令保存模型:

model.save(“model.h5”)

然后安装tensorflow.js并使用以下命令转换模型:

!pip install tensorflowjs
!tensorflowjs_converter --input_format keras 
‘/content/model.h5’ ‘/content/mnist-model’

在运行上述命令后,现在刷新文件。您的内容应该如下所示。
Node.js 如何部署机器学习模型

注意: 下载 mnist-model 文件夹,我们以后会使用它。

创建 Express 应用并安装模块:

步骤1: 使用以下命令创建 package.json 文件:

npm init

步骤2: 现在按照以下命令安装依赖项。我们将使用Express作为服务器和EJS作为模板引擎。

npm install express ejs

项目结构: 现在确保您具有以下文件结构。将从Colab下载的文件复制到model文件夹中。

Node.js 如何部署机器学习模型

现在将下面的代码写入你的 index.js 文件中。

index.js

// Requiring module 
const express = require("express"); 
const app = express(); 
const path = require("path") 
  
// Set public as static directory 
app.use(express.static('public')); 
  
app.set('views', path.join(__dirname, '/views')) 
  
// Use ejs as template engine 
app.set('view engine', 'ejs'); 
app.use(express.json()); 
app.use(express.urlencoded({ extended: false })); 
  
// Render main template 
app.get('/',(req,res)=>{ 
    res.render('main') 
}) 
  
// Server setup 
app.listen(3000, () => { 
  console.log("The server started running on port 3000")  
});

main.ejs

<!DOCTYPE html> 
<html lang="en"> 
  
<head> 
    <script src= 
"https://code.jquery.com/jquery-2.2.4.min.js"> 
    </script> 
    <script src= 
"https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@1.5.2/dist/tf.min.js"> 
    </script> 
    <link rel="stylesheet" href="style.css" /> 
</head> 
  
<body> 
    <h1>Digit Recognition WebApp</h1> 
  
    <div id="paint"> 
        <canvas id="myCanvas"></canvas> 
    </div> 
  
    <div id="predicted"> 
        Recognized digit 
        <div id="number"></div> 
        <button id="clear">Clear</button> 
    </div> 
      
    <script src="script.js"></script> 
</body> 
  
</html> 

style.css

body { 
    touch-action: none;  
    font-family: "Roboto"; 
} 
h1 { 
    margin: 50px; 
    font-size: 70px; 
    text-align: center; 
} 
#paint { 
    border:3px solid red; 
    margin: auto; 
} 
#predicted {  
    font-size: 60px; 
    margin-top: 60px; 
    text-align: center; 
} 
#number { 
    border: 3px solid black; 
    margin: auto; 
    margin-top: 30px; 
    text-align: center; 
    vertical-align: middle; 
} 
#clear { 
    margin: auto; 
    margin-top: 70px; 
    padding: 30px; 
    text-align: center; 
} 

编写脚本: 使用HTML5 canvas定义鼠标事件。然后我们在鼠标弹起时捕获图像,并将其缩放为28×28像素,以使其与我们的模型相匹配,然后将其传递给我们的预测函数。

script.js

canvas.addEventListener('mousedown', function (e) { 
    context.moveTo(mouse.x, mouse.y); 
    context.beginPath(); 
    canvas.addEventListener('mousemove', onPaint, false); 
}, false); var onPaint = function () { 
    context.lineTo(mouse.x, mouse.y); 
    context.stroke(); 
}; 
  
canvas.addEventListener('mouseup', function () { 
    ('#number').html('<img id="spinner" src="spinner.gif"/>'); 
    canvas.removeEventListener('mousemove', onPaint, false); 
    var img = new Image(); 
    img.onload = function () { 
        context.drawImage(img, 0, 0, 28, 28); 
        data = context.getImageData(0, 0, 28, 28).data; 
        var input = []; 
        for (var i = 0; i('#number').html(predicted); 
            }); 
    } else { 
  
        // The model takes a bit to load,  
        // if we are too fast, wait 
        setTimeout(function () { predict(input) }, 50); 
    } 
} 

运行应用的步骤: 使用以下命令运行 index.js 文件。

node index.js

输出: 打开浏览器并且前往 http://localhost:3000 ,我们将会看到下面的输出。

Node.js 如何部署机器学习模型

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程