保存keras模型和StandartScaller到TensorflowJS

mrphzbgm  于 2023-10-19  发布在  其他
关注(0)|答案(1)|浏览(97)

我有以下模型,我想以tensorflowjs格式保存,以便以后在nodejs中使用。

X = df.drop(columns=['Age'])
y = df['Age']

X_train, X_test, y_train, y_test = train_test_split(X, y,
                                                    test_size=0.1,
                                                    random_state=42)

scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)

model_00 = keras.Sequential([
    layers.Dense(20, input_shape=(X_train_scaled.shape[1],)),
    layers.Activation('selu'),
    layers.Dropout(0.1),
    layers.Dense(40),
    layers.Activation('selu'),
    layers.Dropout(0.2),
    layers.Dense(40),
    layers.Activation('selu'),
    layers.Dropout(0.2),
    layers.Dense(40),
    layers.Activation('selu'),
    layers.Dropout(0.1),
    layers.Dense(20),
    layers.Activation('selu'),
    layers.Dense(10),
    layers.Activation('selu'),
    layers.Dense(1),
])

optimizer = optimizers.Adagrad(learning_rate=0.01)

model_00._name = "BA_model_male_00"

model_00.compile(loss='mean_squared_error',
                 optimizer=optimizer,
                 metrics=[metrics.MeanSquaredError(),
                          metrics.MeanAbsoluteError()])

history = model_00.fit(X_train_scaled, y_train,
                       epochs=500,
                       batch_size=200,
                       validation_data=(X_test_scaled, y_test),
                       verbose=0)

prediction = model_00.predict(X_test_scaled)

保存模型并不难,就像这样:

tfjs.converters.save_keras_model(model, tfjs_target_dir)

但我还得保存洁牙机,我不知道该怎么做。

l7wslrjt

l7wslrjt1#

一种解决方案是保存缩放器的参数到Python中的JSON文件中,然后在Node.js中加载这些参数。

import json

# Save the scaler's parameters to a JSON file
scaler_params = {
    'mean': scaler.mean_.tolist(),
    'scale': scaler.scale_.tolist()
}

with open('scaler_params.json', 'w') as json_file:
    json.dump(scaler_params, json_file)

在Node.js中,加载JSON文件,并使用保存的参数重建Scaler:

const tf = require('@tensorflow/tfjs-node');
const fs = require('fs');

// Load the JSON file containing the scaler parameters
const scalerParamsJson = fs.readFileSync('scaler_params.json', 'utf8');
const scalerParams = JSON.parse(scalerParamsJson);

// Create tensors from your data
const dataTensor = tf.tensor(newDataArray);

// Apply manual normalization using the loaded mean and scale
const normalizedData = dataTensor.sub(scalerParams.mean).div(scalerParams.scale);

相关问题