9 Things You Should Know About TensorFlow
This morning I found myself summarizing my favorite bits from a talk that I enjoyed at Google Cloud Next in San Francisco, What’s New with TensorFlow?
Then I thought about it for a moment and couldn’t see a reason not to share my super-short summary with you (except maybe that you might not watch the video — you totally should check it out, the speaker is awesome) so here goes…
I made a video version of this article that’s even shorter, in case you’re in a hurry and/or you prefer information to be injected into your brain via your ears.1 It’s a powerful machine learning framework
TensorFlow is a machine learning framework that might be your new best friend if you have a lot of data and/or you’re after the state-of-the-art in AI: deep learning. Neural networks. Big ones. It’s not a data science Swiss Army Knife, it’s the industrial lathe… which means you can probably stop reading if all you want to do is put a regression line through 20-by-2 spreadsheet.
But if big is what you’re after, get excited. TensorFlow has been used to go hunting for new planets, prevent blindness by helping doctors screen for diabetic retinopathy, and help save forests by alerting authorities to signs of illegal deforestation activity. It’s what AlphaGo and Google Cloud Vision are built on top of and it’s yours to play with. TensorFlow is open source, you can download it for free and get started immediately.
Discovered with the help of TensorFlow,
the planet Kepler-90i makes the Kepler-90 system the only other system
we know of that has eight planets in orbit around a single star. No
system has been found with more than eight planets, so I guess that
means we’re tied with Kepler-90 for first place (for now). Learn
more here.](https://www.nbcnews.com/mach/video/nasa-s-kepler-telescope-discovered-a-new-exoplanet-with-google-s-help-1121785923978). "https://www.nbcnews.com/mach/video/nasa-s-kepler-telescope-discovered-a-new-exoplanet-with-google-s-help-1121785923978).")2 The bizarre approach is optional
I’m head over heels for TensorFlow Eager.
If you tried TensorFlow in the old days and ran away screaming because it forced you to code like an academic/alien instead of like a developer, come baaaack!
TensorFlow eager execution lets you interact with it like a pure Python programmer: all the immediacy of writing and debugging line-by-line instead of holding your breath while you build those huge graphs. I’m a recovering academic myself (and quite possibly an alien), but I’ve been in love with TF eager execution since it came out. So eager to please!3 You can build neural networks line-by-line
Keras + TensorFlow = easier neural network construction!
Keras is all about user-friendliness and easy prototyping, something old TensorFlow sorely craved more of. If you like object oriented thinking and you like building neural networks one layer at a time, you’ll love tf.keras. In just the few lines of code below, we’ve created a sequential neural network with the standard bells and whistles like dropout (remind me to wax lyrical about my metaphors for dropout sometime, they involve staplers and the flu).
Oh, you like puzzles, do you? Patience. Don’t think too much about staplers.4 It’s not only Python
Got a clunker desktop from a museum? Toaster? (Same thing?) TensorFlow Lite brings model execution to a variety of devices, including mobile and IoT, giving you more than a 3x boost in inference speedup over original TensorFlow. Yes, now you can get machine learning on your Raspberry Pi or your phone. In the talk, Laurence does a brave thing by live-demoing image classification on an Android emulator in front of thousands… and it works.
1.6 seconds to compute? Check! Banana with over 97% probability? Check! Toilet tissue? Well, I’ve been to a few countries where I suppose a sheet of paper like the one Laurence is holding up counts.7 Specialized hardware just got better
If you’re tired of waiting for your CPU to finish churning through your data to train your neural network, you can now get your hands on hardware specially designed for the job with Cloud TPUs. The T is for tensor. Just like TensorFlow… coincidence? I think not! A few weeks ago, Google announced version 3 TPUs in alpha.8 The new data pipelines are much improved
What’s that you’re doing with numpy over there? In case you wanted to do it in TensorFlow but then rage-quit, the tf.data namespace now makes your input processing in TensorFlow more expressive and efficient. tf.data gives you fast, flexible, and easy-to-use data pipelines synchronized with training.9 You don’t need to start from scratch
You know what’s not a fun way to get started with machine learning? A blank new page in your editor and no example code for miles. With TensorFlow Hub, you can engage in a more efficient version of the time-honored tradition of helping yourself to someone else’s code and calling it your own (otherwise known as professional software engineering).
TensorFlow Hub is a repository for reusable pre-trained machine learning model components, packaged for one-line reuse. Help yourself!
Update! As of March 2019, there’s a 10th thing you should know…10 TensorFlow just got user friendly!
Now that we’re done with last year’s news, it’s time for the one thing you need to know above all others: TensorFlow 2.0 is finally here! It’s a radical makeover that’s all about making TF super easy to use. The consequences are going to have major ripple effects on every industry, just you wait. Read my update about it here.
That concludes my summary, so here’s the full talk to entertain you for the next 42 minutes.
Machine Learning With Python, Jupyter, KSQL, and TensorFlow. This post focuses on how the Kafka ecosystem can help solve the impedance mismatch between data scientists, data engineers and production engineers.
Machine Learning With Python, Jupyter, KSQL, and TensorFlow. This post focuses on how the Kafka ecosystem can help solve the impedance mismatch between data scientists, data engineers and production engineers.
Building a scalable, reliable, and performant machine learning (ML) infrastructure is not easy. It takes much more effort than just building an analytic model with Python and your favorite machine learning framework.
Uber, which already runs their scalable and framework-independent machine learning platform Michelangelo for many use cases in production, wrote a good summary:
When Michelangelo started, the most urgent and highest impact use cases were some very high scale problems, which led us to build around Apache Spark (for large-scale data processing and model training) and Java (for low latency, high throughput online serving). This structure worked well for production training and deployment of many models but left a lot to be desired in terms of overhead, flexibility, and ease of use, especially during early prototyping and experimentation [where Notebooks and Python shine].
Uber expanded Michelangelo “to serve any kind of Python model from any source to support other Machine Learning and Deep Learning frameworks like PyTorch and TensorFlow [instead of just using Spark for everything].”
So why did Uber (and many other tech companies) build its own platform and framework-independent machine learning infrastructure?
The posts How to Build and Deploy Scalable Machine Learning in Production with Apache Kafka and Using Apache Kafka to Drive Cutting-Edge Machine Learning describe the benefits of leveraging the Apache Kafka ® ecosystem as a central, scalable, and mission-critical nervous system. It allows real-time data ingestion, processing, model deployment, and monitoring in a reliable and scalable way.
This post focuses on how the Kafka ecosystem can help solve the impedance mismatch between data scientists, data engineers, and production engineers. By leveraging it to build your own scalable machine learning infrastructure and also make your data scientists happy, you can solve the same problems for which Uber built its own ML platform, Michelangelo.
You may also like:A Complete Machine Learning Project Walk-Through in Python
Based on what I’ve seen in the field, an impedance mismatch between data scientists, data engineers, and production engineers is the main reason why companies struggle to bring analytic models into production to add business value.
The following diagram illustrates the different required steps and corresponding roles as part of the impedance mismatch in a machine learning lifecycle:
Data scientists love
Python, period. Therefore, the majority of machine learning/deep learning frameworks focus on Python APIs. Both the stablest and most cutting edge APIs, as well as the majority of examples and tutorials, use
There is an impedance mismatch between model development using Python, its tool stack and a scalable, reliable data platform with low latency, high throughput, zero data loss and 24/7 availability requirements needed for data ingestion, preprocessing, model deployment and monitoring at scale. Python, in practice, is not the most well-known technology for these requirements. However, it is a great client for a data platform like Apache Kafka.
The problem is that writing the machine learning source code to train an analytic model with
Python and the machine learning framework of your choice is just a very small part of a real-world machine learning infrastructure. You need to think about the whole model lifecycle. The following image represents this hidden technical debt in machine learning systems (showing how small the “ML code” part is):
Thus, you need to train and deploy the model built to a scalable production environment in order to reliably make use of it. This can either be built natively around the Kafka ecosystem, or you could use Kafka just for ingestion into another storage and processing cluster such as HDFS or AWS S3 with Spark. There are many tradeoffs between Kafka, Spark, and several other scalable infrastructures, but that discussion is out of scope for this post. For now, we’ll focus on Kafka.
Different solutions in the industry solve certain parts of the impedance mismatch between data scientists, data engineers, and production engineers. Let’s take a look at some of these options:
TensorFlowmodel. Depending on the framework, the output can be text files, Java source code, or binary files. For example, TensorFlow generates a model artifact with Protobuf,
JSON, and other files. No matter what format the output of your machine learning framework is, it can be embedded into applications to use for predictions via the framework’s API (e.g., you can load a TensorFlow model from a Java application through
While all these solutions help data scientists, data engineers, and production engineers to work better together, there are underlying challenges within the hidden debts:
Data collection (i.e., integration) and preprocessing need to run at scale
Configuration needs to be shared and automated for continuous builds and integration tests
The serving and monitoring infrastructure need to fit into your overall enterprise architecture and tool stack
So how can the
Kafka ecosystem help here?
In many cases, it is best to provide experts with the tools they like and know well. The challenge is to combine the different toolsets and still build an integrated system, as well as a continuous,
scalable, machine learning workflow. Therefore,
Kafka is not competitive but complementary to the discussed alternatives when it comes to solving the impedance mismatch between the data scientist and developer.
The data engineer builds a scalable integration pipeline using Kafka as infrastructure and Python for integration and preprocessing statements. The data scientist can build their model with Python or any other preferred tool. The production engineer gets the analytic models (either manually or through any automated, continuous integration setup) from the data scientist and embeds them into their Kafka application to deploy it in production. Or, the team works together and builds everything with Java and a framework like Deeplearning4j.
Any option can pair well with Apache Kafka. Pick the pieces you need, whether it’s Kafka core for data transportation, Kafka Connect for data integration, or Kafka Streams/KSQL for data preprocessing. Many components can be used for both model training and model inference. Write once and use in both scenarios as shown in the following diagram:
Leveraging the Apache Kafka ecosystem for a machine learning infrastructure
Monitoring the complete environment in real time and at scale is also a common task for Kafka. A huge benefit is that you only build a highly reliable and scalable pipeline once but use it for both parts of a machine learning infrastructure. And you can use it in any environment: in the cloud, in on-prem datacenters, or at the edges where IoT devices are.
Say you wanted to build one integration pipeline from MQTT to Kafka with KSQL for data preprocessing and use Kafka Connect for data ingestion into HDFS, AWS S3, or Google Cloud Storage, where you do the model training. The same integration pipeline, or at least parts of it, can be reused for model inference. New MQTT input data can directly be used in real time to make predictions.
We just explained various alternatives to solving the impedance mismatch between data scientists and software engineers in Kafka environments. Now, let’s discuss one specific option in the next section, which is probably the most convenient for data scientists: leveraging Kafka from a Jupyter Notebook with KSQL statements and combining it with
Keras to train a neural network.
Data scientists use tools like Jupyter Notebooks to analyze, transform, enrich, filter, and process data. The preprocessed data is then used to train analytic models with machine learning/deep learning frameworks like TensorFlow.
However, some data scientists do not even know “bread-and-butter” concepts of software engineers, such as version control systems like GitHub or continuous integration tools like Jenkins.
This raises the question of how to combine the Python experience of data scientists with the benefits of Apache Kafka as a battle-tested, highly scalable data processing and streaming platform.Apache Kafka and KSQL for Data Scientists and Data Engineers
Kafka offers integration options that can be used with Python, like Confluent’s Python Client for Apache Kafka or Confluent REST Proxy for HTTP integration. But this is not really a convenient way for data scientists who are used to quickly and interactively analyzing and preprocessing data before model training and evaluation. Rapid prototyping is typically used here.
KSQL enables data scientists to take a look at Kafka event streams and implement continuous stream processing from their well-known and loved Python environments like Jupyter by writing simple SQL-like statements for interactive analysis and data preprocessing.
The following Python example executes an interactive query from a Kafka stream leveraging the open source framework ksql-python, which adds a Python layer on top of KSQL’s REST interface. Here are a few lines of the Python code using KSQL from a
The result of such a KSQL query is a Python generator object, which you can easily process with other Python libraries. This feels much more Python native and is analogous to NumPy, pandas, scikit-learn and other widespread Python libraries.
Similarly to rapid prototyping with these libraries, you can do interactive queries and data preprocessing with ksql-python. Check out the KSQL quick start and KSQL recipes to understand how to write a KSQL query to easily filter, transform, enrich, or aggregate data. While KSQL is running continuous queries, you can also use it for interactive analysis and use the
LIMIT keyword like in ANSI SQL if you just want to get a specific number of rows.
So what’s the big deal? You understand that KSQL can feel Python-native with the ksql-python library, but why use KSQL instead of or in addition to your well-known and favorite Python libraries for analyzing and processing data?
The key difference is that these KSQL queries can also be deployed in production afterwards. KSQL offers you all the features from Kafka under the hood like high scalability, reliability, and failover handling. The same KSQL statement that you use in your Jupyter Notebook for interactive analysis and preprocessing can scale to millions of messages per second. Fault tolerant. With zero data loss and exactly once semantics. This is very important and valuable for bringing together the Python-loving data scientist with the highly scalable and reliable production infrastructure.
Just to be clear: KSQL + Python is not the all-rounder for every data engineering task, and it does not replace the existing Python toolset. But it is a great option in the toolbox of data scientists and data engineers, and it adds new possibilities like getting real-time updates of incoming information as the source data changes or updating a deployed model with a new and improved version.Jupyter Notebook for Fraud Detection With Python KSQL and TensorFlow/Keras
Let’s now take a look at a detailed example using the combination of KSQL and Python. It involves advanced code examples using ksql-python and other widespread components from Python’s machine learning ecosystem, like NumPy, pandas, TensorFlow, and Keras.
The use case is fraud detection for credit card payments. We use a test dataset from Kaggle as a foundation to train an unsupervised autoencoder to detect anomalies and potential fraud in payments. The focus of this example is not just model training, but the whole machine learning infrastructure, including data ingestion, data preprocessing, model training, model deployment, and monitoring. All of this needs to be scalable, reliable, and performant.
For the full running example and more details, see the documentation.
Let’s take a look at a few snippets of the Jupyter Notebook.
Connection to KSQL server and creation of a KSQL stream using Python:
from ksql import KSQLAPI client = KSQLAPI('http://localhost:8088') client.create_stream(table_name='creditcardfraud_source', columns_type=['Id bigint', 'Timestamp varchar', 'User varchar', 'Time int', 'V1 double', 'V2 double', 'V3 double', 'V4 double', 'V5 double', 'V6 double', 'V7 double', 'V8 double', 'V9 double', 'V10 double', 'V11 double', 'V12 double', 'V13 double', 'V14 double', 'V15 double', 'V16 double', 'V17 double', 'V18 double', 'V19 double', 'V20 double', 'V21 double', 'V22 double', 'V23 double', 'V24 double', 'V25 double', 'V26 double', 'V27 double', 'V28 double', 'Amount double', 'Class string'], topic='creditcardfraud_source', value_format='DELIMITED')
Preprocessing incoming payment information using Python:
Filter columns that are not needed
Filter messages where column "class" is empty
Change data format to Avro for convenient and further processing
client.create_stream_as(table_name='creditcardfraud_preprocessed_avro', select_columns=['Time', 'V1', 'V2', 'V3', 'V4', 'V5', 'V6', 'V7', 'V8', 'V9', 'V10', 'V11', 'V12', 'V13', 'V14', 'V15', 'V16', 'V17', 'V18', 'V19', 'V20', 'V21', 'V22', 'V23', 'V24', 'V25', 'V26', 'V27', 'V28', 'Amount', 'Class'], src_table='creditcardfraud_source', conditions='Class IS NOT NULL', kafka_topic='creditcardfraud_preprocessed_avro', value_format='AVRO')
Some more examples for possible data wrangling and preprocessing with KSQL:
CREATE STREAM creditcardfraud_preprocessed_avro WITH (VALUE_FORMAT='AVRO', KAFKA_TOPIC='creditcardfraud_preprocessed_avro') AS SELECT Time, V1 , V2 , V3 , V4 , V5 , V6 , V7 , V8 , V9 , V10 , V11 , V12 , V13 , V14 , V15 , V16 , V17 , V18 , V19 , V20 , V21 , V22 , V23 , V24 , V25 , V26 , V27 , V28 , Amount , Class FROM creditcardfraud_source WHERE Class IS NOT NULL;
SELECT Id, MASK_LEFT(User, 2) FROM creditcardfraud_source;
SELECT Id, IFNULL(Class, -1) FROM creditcardfraud_source;
CREATE STREAM creditcardfraud_per_user WITH (VALUE_FORMAT='AVRO', KAFKA_TOPIC='creditcardfraud_preprocessed_avro') AS SELECT Time, V1 , V2 , V3 , V4 , V5 , V6 , V7 , V8 , V9 , V10 , V11 , V12 , V13 , V14 , V15 , V16 , V17 , V18 , V19 , V20 , V21 , V22 , V23 , V24 , V25 , V26 , V27 , V28 , Amount , Class FROM creditcardfraud_enahnced c INNER JOIN USERS u on c.userid = u.userid WHERE V1 > 5 AND V2 IS NOT NULL AND u.CITY LIKE 'Premium%';
The Jupyter Notebook contains the full example. We use Python + KSQL for integration, data preprocessing, and interactive analysis and combine them with various other libraries from a common Python machine learning tool stack for prototyping and model training:
Arrays/matrices processing with NumPy and pandas
ML-specific processing (split train/test, etc.) with scikit-learn
Interactive analysis through data visualisations with Matplotlib
ML training + evaluation with TensorFlow and Keras
Model inference and visualisation are done in the Jupyter notebook, too. After you have built an accurate model, you can deploy it anywhere to make predictions and leverage the same integration pipeline for model training. Some examples of model deployment in Kafka environments are:
Analytic models (TensorFlow, Keras, H2O and Deeplearning4j) embedded in Kafka Streams microservices
Anomaly detection of IoT sensor data with a model embedded into a KSQL UDF
RPC communication between Kafka Streams application and model server (TensorFlow Serving)
As you can see, both in theory (Google’s paper Hidden Technical Debt in Machine Learning Systems) and in practice (Uber’s machine learning platform Michelangelo), it is not a simple task to build a scalable, reliable, and performant machine learning infrastructure.
The impedance mismatch between data scientists, data engineers, and production engineers must be resolved in order for machine learning projects to deliver real business value. This requires using the right tool for the job and understanding how to combine them. You can use Python and Jupyter for prototyping and demos (often Kafka and KSQL might be overhead here and not needed if you just want to do fast, simple prototyping on a historical dataset) or combine Python and Jupyter with your whole development lifecycle up to production deployments at scale.
Integration of Kafka event streams and KSQL statements into Jupyter Notebooks allows you to:
Use the preferred existing environment of the data scientist (including Python and Jupyter) and combine it with Kafka and KSQL to integrate and continuously process real-time streaming data by using a simple Python wrapper API to execute KSQL queries
Easily connect to real-time streaming data instead of just historical batches of data (maybe from the last day, week or month, e.g., coming in via CSV files)
Merge different concepts like streaming event-based sensor data coming from Kafka with Python programming concepts like generators or dictionaries objects, which you can use for your Python data processing tools or ML frameworks like NumPy, pandas, or scikit-learn
Reuse the same logic for integration, preprocessing, and monitoring and move it from your Jupyter Notebook and prototyping or demos to large-scale test and production systems
Python for prototyping and Apache Kafka for a scalable streaming platform are not rival technology stacks. They work together very well, especially if you use “helper tools” like Jupyter Notebooks and KSQL.
Please try it out and let us know your thoughts. How do you leverage the Apache Kafka ecosystem in your machine learning projects?
Libraries play an important role when developers decide to work in Machine Learning or Deep Learning researches. In this article, we list down 10 comparisons between TensorFlow and PyTorch these two Machine Learning Libraries.
According to this article, a survey based on a sample of 1,616 ML developers and data scientists, for every one developer using PyTorch, there are 3.4 developers using TensorFlow. In this article, we list down 10 comparisons between these two Machine Learning Libraries.1 - Origin
PyTorch has been developed by Facebook which is based on Torch while TensorFlow, an open sourced Machine Learning Library, developed by Google Brain is based on the idea of data flow graphs for building models.2 - Features
TensorFlow has some attracting features such as TensorBoard which serves as a great option while visualising a Machine Learning model, it also has TensorFlow Serving which is a specific grpc server that is used during the deployment of models in production. On the other hand, PyTorch has several distinguished features too such as dynamic computation graphs, naive support for Python, support for CUDA which ensures less time for running the code and increase in performance.3 - Community
TensorFlow is adopted by many researchers of various fields like academics, business organisations, etc. It has a much bigger community than PyTorch which implies that it is easier to find for resources or solutions in TensorFlow. There is a vast amount of tutorials, codes, as well as support in TensorFlow and PyTorch, being the newcomer into play as compared to TensorFlow, it lacks these benefits.4 - Visualisation
Visualisation plays as a protagonist while presenting any project in an organisation. TensorFlow has TensorBoard for visualising Machine Learning models which helps during training the model and spot the errors quickly. It is a real-time representation of the graphs of a model which not only depicts the graphic representation but also shows the accuracy graphs in real-time. This eye-catching feature is lacked by PyTorch.5 - Defining Computational Graphs
In TensorFlow, defining computational graph is a lengthy process as you have to build and run the computations within sessions. Also, you will have to use other parameters such as placeholders, variable scoping, etc. On the other hand, Python wins this point as it has the dynamic computation graphs which help id building the graphs dynamically. Here, the graph is built at every point of execution and you can manipulate the graph at run-time.6 - Debugging
PyTorch being the dynamic computational process, the debugging process is a painless method. You can easily use Python debugging tools like pdb or ipdb, etc. for instance, you can put “pdb.set_trace()” at any line of code and then proceed for executions of further computations, pinpoint the cause of the errors, etc. While, for TensorFlow you have to use the TensorFlow debugger tool, tfdbg which lets you view the internal structure and states of running TensorFlow graphs during training and inference.7 - Deployment
For now, deployment in TensorFlow is much more supportive as compared to PyTorch. It has the advantage of TensorFlow Serving which is a flexible, high-performance serving system for deploying Machine Learning models, designed for production environments. However, in PyTorch, you can use the Microframework for Python, Flask for deployment of models.8 - Documentation
The documentation of both frameworks is broadly available as there are examples and tutorials in abundance for both the libraries. You can say, it is a tie between both the frameworks.
The serialisation in TensorFlow can be said as one of the advantages for this framework users. Here, you can save your entire graph as a protocol buffer and then later it can be loaded in other supported languages, however, PyTorch lacks this feature.10 - Device Management
By default, Tensorflow maps nearly all of the GPU memory of all GPUs visible to the process which is a comedown but here it automatically presumes that you want to run your code on the GPU because of the well-set defaults and thus result in fair management of the device. On the other hand, PyTorch keeps track of the currently selected GPU and all the CUDA tensors which will be allocated.
TensorFlow Extended (TFX): Machine Learning Pipelines
TensorFlow Extended (TFX): Machine Learning Pipelines
Speaker: Martin Andrews
Event: Google I/O Recap 2019 Singapore AI - From Model to Device by BigDataX
Thanks for watching ❤
If you liked this post, share it with all of your programming buddies!