Welcome back! Today, we’re going to explore how to easily build machine learning applications using Streamlit. With Streamlit, you can create a user-friendly front-end for your machine learning application without the need for HTML, CSS, or JavaScript coding. Let’s dive right in!
![Modern Machine Learning Apps with Streamlit - No HTML, CSS, JS](https://img.youtube.com/vi/_Syn5SpWgZ0/hq720.jpg)
Building a Machine Learning Application with Streamlit
In this tutorial, we’ll learn how to build a machine learning application in Python using Streamlit. We’ll train a simple image recognition model on the CIFAR-10 dataset and then create a web application around this model where we can upload images and classify them without any prior HTML, CSS, or JavaScript knowledge.
To get started, we need to install a few packages. Run the following commands in your Python environment:
pip install numpy matplotlib pillow tensorflow streamlit
Once the packages are installed, import the necessary libraries:
import numpy as np
import matplotlib.pyplot as plt
import streamlit as st
from PIL import Image
from tensorflow.keras.datasets import cifar10
from tensorflow.keras.models import load_model
from tensorflow.keras.layers import Flatten, Dense
from tensorflow.keras.utils import to_categorical
Now, let’s define a script that will train the CIFAR-10 image recognition model using TensorFlow. After training the model, we’ll use Streamlit to create the user interface around it.
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
x_train = x_train / 255.0
x_test = x_test / 255.0
y_train = to_categorical(y_train, num_classes=10)
y_test = to_categorical(y_test, num_classes=10)
model = Sequential([
Flatten(input_shape=(32, 32, 3)),
Dense(1000, activation='relu'),
Dense(10, activation='softmax')
])
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
model.fit(x_train, y_train, batch_size=64, epochs=10, validation_data=(x_test, y_test))
model.save('cifar10_model.h5')
With the model trained and saved, we can now build the Streamlit application.
def main():
st.title("CIFAR-10 Web Classifier")
st.write("Upload any image that you think belongs to one of the classes and see if the prediction is correct.")
file = st.file_uploader("Please upload an image", type=["jpeg", "jpg", "png"])
if file is None:
st.text("You have not uploaded an image yet.")
else:
image = Image.open(file)
st.image(image, use_column_width=True)
resized_image = image.resize((32, 32))
image_array = np.array(resized_image) / 255.0
image_array = image_array.reshape(1, 32, 32, 3)
model = load_model('cifar10_model.h5')
predictions = model.predict(image_array)[0]
cifar10_classes = ["airplane", "automobile", "bird", "cat", "deer", "dog", "frog", "horse", "ship", "truck"]
class_index = np.argmax(predictions)
fig, ax = plt.subplots()
y_positions = np.arange(len(cifar10_classes))
ax.barh(y_positions, predictions, align='center')
ax.set_yticks(y_positions)
ax.set_yticklabels(cifar10_classes)
ax.invert_yaxis()
ax.set_xlabel("Probability")
ax.set_title("CIFAR-10 Predictions")
st.pyplot(fig)
if __name__ == '__main__':
main()
In the code above, we define a main()
function that serves as the entry point for our Streamlit application. We set the title and write some introductory text. Then, if a file is uploaded, we process the image by resizing it to 32×32 pixels, normalizing it, and reshaping it to match the input shape of our model. We load the trained model, make a prediction on the image, and display the results using a horizontal bar plot.
To run the application, open a terminal, navigate to the directory where your code is located, and run the following command:
streamlit run filename.py
Replace filename.py
with the name of your Python script.
Now, open your web browser and visit http://localhost:8501
. You should see the Streamlit application with the option to upload an image and view the classification results.
FAQs
Q: Can I use this method with different machine learning models?
A: Yes, you can use Streamlit to build user interfaces for various machine learning models, not just for image recognition. Streamlit offers a simple and intuitive way to create interactive applications without the need for HTML, CSS, or JavaScript.
Q: How accurate is the model in this example?
A: The model used in this example is a simple multi-layer perceptron and may not achieve high accuracy. The focus of this tutorial is to demonstrate how to integrate a trained model into a web application using Streamlit. For more accurate results, consider using more advanced models like convolutional neural networks.
Q: Can I deploy this application to a production environment?
A: Yes, Streamlit allows you to deploy your applications to various platforms, including cloud-based services, using tools like Heroku, AWS, or Google Cloud. Refer to the Streamlit documentation for more information on deployment options.
Conclusion
In this tutorial, we explored how to build a modern machine learning application using Streamlit. We trained a simple image recognition model on the CIFAR-10 dataset and created a user interface around it without writing any HTML, CSS, or JavaScript code. Streamlit empowers developers to quickly and easily build interactive applications that can be used by anyone without a deep understanding of web technologies. Give it a try, and have fun building your own applications!
For more insightful analysis and comprehensive guides on the ever-evolving world of technology, visit Techal.