Create A TensorFlow Model
For illustration purposes, we will show a basic TensorFlow model applicable to the digital twin model we defined (3 properties) and the training data we created.
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Layer, Input
import pandas as pd
from sklearn.model_selection import train_test_split
import numpy as np
# Load the data
data = pd.read_csv('SupervisedLearningDataSet.csv')
# Split the dataset into features (X) and target (y)
X = data[['Temperature', 'RPM', 'Friction']]
y = data['Anomaly']
# Split the data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Calculate the mean and standard deviation for each feature from the training data
mean = X_train.mean().values
std = X_train.std().values
# Define a custom layer for scaling
class CustomStandardScalerLayer(Layer):
def __init__(self, mean, std):
super(CustomStandardScalerLayer, self).__init__()
self.mean = tf.constant(mean, dtype=tf.float32)
self.std = tf.constant(std, dtype=tf.float32)
def call(self, inputs):
return (inputs - self.mean) / self.std
# Define the model
model = Sequential()
# Input layer with 3 input dimensions corresponding to Temperature, RPM, and Friction.
# Make sure that the input is named correctly
model.add(Input(shape=(3,), name='input_vector'))
# Custom scaling layer as the first layer
model.add(CustomStandardScalerLayer(mean, std))
model.add(Dense(16, activation='relu'))
# Hidden layer
model.add(Dense(8, activation='relu'))
# Output layer with a single neuron for binary classification
model.add(Dense(1, activation='sigmoid', name='output_vector'))
# Compile the model
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
# Train the model
model.fit(X_train, y_train, epochs=50, batch_size=10, validation_split=0.2)
# save the model as a pb file in a folder
model.export('Overheating')
# Evaluate the model
loss, accuracy = model.evaluate(X_test, y_test)
print(f'Test Accuracy: {accuracy:.4f}')
# Predict on new data (raw input, no need to scale manually)
new_data = np.array([[230, 44000, 2.3]]) # Example input
prediction = model.predict(new_data)
print(prediction)
# Interpret the prediction
anomaly = (prediction > 0.5).astype(int)
print(anomaly)
print(f'Anomaly detected: {bool(anomaly[0][0])}')
Running this Python script will create a Tensorflow model called Overheating.
Converting a TensorFlow model to an ONNX file
This script created the model as a pb file in a folder named Overheating.
To convert your model to ONNX, first install the tf2onnx tool.
pip install tf2onnx
Once installed, run the conversion command:
python -m tf2onnx.convert --saved-model Overheating --output Overheating.onnx --opset 15
Note
To get more details about converting TensorFlow to ONNX, please refer to Getting started… on onnxruntime.ai.