However fear not, we are going to use an API from GCP referred to as App Engine. It’s a absolutely managed serverless platform by Google. This implies you solely have to fret concerning the code, not the infrastructure. App Engine helps (Node.js, Java, Ruby, C#, Go, Python, or PHP) and it scales up and down upon demand and also you pay for what you utilize. I KNOW!
Okay, for the sake of this train, we are going to put together our knowledge utilizing the straight-line equation Y = Mx + C. X would be the enter to the mannequin and Y would be the output. We’ll create 5000 knowledge factors in a single file and save them as .npy recordsdata in a separate folder. I may have performed this within the coaching file as effectively however I would like you to grasp how one can add and cargo totally different recordsdata inside the App Engine atmosphere.
import numpy as np
import os# Parameters for the straight line equation
m = 2.5 # Slope
c = 1.0 # Intercept
# Generate x values
x = np.linspace(0, 1000, 5000)
print(len(x))
# Generate y values utilizing the straight line equation
y = m * x + c
# Save the info to .npy recordsdata
np.save(os.path.be a part of(os.path.dirname(__file__),'Knowledge','x.npy'),x)
np.save(os.path.be a part of(os.path.dirname(__file__),'Knowledge','y.npy'),y)
Within the subsequent file, you’ll load this knowledge and prepare a TensorFlow mannequin (Pytorch fashions can be hosted equally) that may predict the output quantity given an enter quantity and can attempt to mimic the habits of a straight-line equation.
I do know,
- We’re not to make use of ML for duties whose precise options are identified however that is simply to maintain the mannequin easy.
- To make use of ML for this activity is like utilizing a Jackhammer to crack a nut however please…
Within the coaching file, you’ll load the info, outline a mannequin, compile it, after which put it aside after coaching. Right here is the code to try this,
import tensorflow as tf
from tensorflow.keras.fashions import Sequential
from tensorflow.keras.layers import Dense
import numpy as np
import os# Load the info
x = np.load(os.path.be a part of(os.path.dirname(__file__),'Knowledge','x.npy'))
y = np.load(os.path.be a part of(os.path.dirname(__file__),'Knowledge','y.npy'))
# Outline the neural community mannequin
mannequin = Sequential([
Dense(2, activation='relu', input_shape=(1,)),
Dense(4, activation='relu'),
Dense(1)
])
# Compile the mannequin
mannequin.compile(optimizer='adam', loss='mse')
# Prepare the mannequin
mannequin.match(x, y, epochs=10)
# make a pattern request to see the specified outcomes are being achieved
req = 10
print('mannequin prediction:',mannequin.predict(np.array([[float(req)]])))
print('Actual answer:',2.5*req+1.0)
# Save the mannequin
mannequin.save(os.path.be a part of(os.path.dirname(__file__),'linear_model.h5'))
After working the above code, the next outcomes are obtained.
In a brand new file, we are going to load the saved mannequin, make predictions, and outline the URLs for serving by way of our app. We’ll use Flask for this software (a framework to construct and deploy Python apps). A URL will be set within the Flask app, which we are going to hit utilizing CURL, and the mannequin’s prediction shall be obtained within the type of a JSON object. Be certain that to obtain Flask utilizing pip or conda, nonetheless, you utilize and handle your environments.
It’s essential to identify this file app.py to work with Flask.
from flask import Flask, request, jsonify
import tensorflow as tf
import numpy as np
import osapp = Flask(__name__)
# Load the skilled mannequin
mannequin = tf.keras.fashions.load_model(os.path.be a part of(os.path.dirname(__file__),
'linear_model.h5'))
@app.route('/predict', strategies=['GET'])
def predict():
attempt:
# Get the x worth from the request
x_value = float(request.args.get('x'))
# Reshape the enter for the mannequin
x_input = np.array([[x_value]])
# Predict utilizing the mannequin
prediction = mannequin.predict(x_input)
# Return the prediction as a JSON response
return jsonify({'y_intercept': float(prediction[0][0])})
besides Exception as e:
return jsonify({'error': str(e)})
if __name__ == '__main__':
app.run(debug=True)