import tensorflow as tf from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Conv2D, MaxPooling2D, Flatten <h1>Build the model</h1> <p>model = Sequential()<br> model.add(Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)))<br> model.add(MaxPooling2D((2, 2)))<br> model.add(Flatten())<br> model.add(Dense(10, activation='softmax'))</p> <h1>Compile the model</h1> <p>model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])</p> <h1>Train the model</h1> <p>...</p> <h1>Save the model</h1> <p>model.save('model.h5')<br>
First, install the TensorFlow Serving PHP extension. It can be easily done via composer:
composer require tensorflow-serving-api-php
Next, you can write a simple PHP script to load the model and make predictions:
<?php require 'vendor/autoload.php'; <p>use TensorFlowServingPredictRequest;<br> use TensorFlowServingPredictResponse;<br> use GuzzleHttp\Client;</p> <p>// Define the request data<br> $request = new PredictRequest();<br> $request->setModelSpecName('model');<br> $request->setModelSpecSignatureName('serving_default');</p> <p>// Convert the input data<br> $input = [<br> 'image' => [<br> 'b64' => base64_encode(file_get_contents('image.jpg'))<br> ]<br> ];<br> $request->setInputs($input);</p> <p>// Send the request<br> $client = new Client(['base_uri' => 'http://localhost:8501']);<br> $response = $client->post('/v1/models/model:predict', [<br> 'headers' => ['Content-Type' => 'application/json'],<br> 'body' => $request->serializeToString()<br> ]);</p> <p>$response = new PredictResponse($response->getBody()->getContents());</p> <p>// Get the prediction result<br> $outputs = $response->getOutputs();<br> $prediction = reset($outputs)['floatVal'][0];<br>
In the code above, we define a PredictRequest object and set the model name and signature. Then, we convert the input data into the required format and send the request to the TensorFlow Serving REST API. Finally, we extract the prediction result from the returned data.
Here is an example of installing and starting Apache on an Ubuntu server:
sudo apt-get install apache2 sudo service apache2 start
Save the PHP script as a .php file and place it in Apache's web root directory. After that, you can access the corresponding URL to use the machine learning model online.