Код: Выделить всё
import os
os.environ['TF_ENABLE_ONEDNN_OPTS'] = '0'
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '1'
import sys
import numpy as np
import warnings
from tensorflow.keras.models import load_model
import joblib
warnings.filterwarnings("ignore", category=UserWarning, message="Compiled the loaded model, but the compiled metrics have yet to be built.")
current_dir = os.path.dirname(os.path.abspath(__file__))
model_path = os.path.join(current_dir, 'lstm_model.h5')
scaler_path = os.path.join(current_dir, 'minmax_scaler.pkl')
def mse(y_true, y_pred):
return np.mean(np.square(y_true - y_pred))
def predict_lstm(input_sequence):
# Load the trained LSTM model
model = load_model(model_path, custom_objects={'mse': mse})
# Load the fitted scaler
scaler = joblib.load(scaler_path)
input_sequence_scaled = scaler.transform(np.array(input_sequence).reshape(-1, 1))
input_sequence_scaled = input_sequence_scaled.reshape(1, len(input_sequence_scaled), 1)
prediction_scaled = model.predict(input_sequence_scaled)
prediction = scaler.inverse_transform(prediction_scaled)
return prediction[0][0]
if __name__ == "__main__":
input_sequence = [float(arg) for arg in sys.argv[1:]]
if len(input_sequence) < 10:
print("Error: Need at least 10 past timestamps for LSTM prediction.")
else:
try:
predicted_value = predict_lstm(input_sequence)
print(f"Predicted Value: {predicted_value:.6f}")
except Exception as e:
print(f"An error occurred: {str(e)}")
Код: Выделить всё
python predict_lstm.py 10 20 30 40 50 60 70 80 90 100
Код: Выделить всё
Error: WARNING:absl:Compiled the loaded model, but the compiled metrics have yet to be built. model.compile_metrics will be empty until you train or evaluate the model.
Код: Выделить всё
[HttpGet("lstm")]
public IActionResult PredictLstm([FromQuery] LstmInputModel model)
{
if (model == null || model.Timestamps == null || model.Timestamps.Length == 0)
{
return BadRequest("Invalid input. An array of timestamps is required.");
}
string scriptPath = "Solutions/predict_lstm.py";
string result = RunPythonScript(scriptPath, model.Timestamps);
if (!string.IsNullOrEmpty(result))
{
return Ok(result);
}
else
{
return BadRequest("Error executing the prediction script.");
}
}
private string RunPythonScript(string scriptPath, double[] features)
{
try
{
string featuresString = string.Join(" ", features.Select(f => f.ToString()));
ProcessStartInfo psi = new ProcessStartInfo
{
FileName = "python",
Arguments = $"\"{scriptPath}\" {featuresString}",
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true
};
using (Process process = Process.Start(psi))
{
process.WaitForExit();
string output = process.StandardOutput.ReadToEnd();
string errors = process.StandardError.ReadToEnd();
return !string.IsNullOrEmpty(errors) ? $"Error: {errors}" : output;
}
}
catch (System.Exception ex)
{
return $"Exception occurred: {ex.Message}";
}
}
Подробнее здесь: https://stackoverflow.com/questions/790 ... el-metrics
Мобильная версия