SlideShare a Scribd company logo
Copyright (c) WLOG Solutions
How to lock a Python in a cage?
Managing Python environment inside an R project
PyData meetup
Warsaw, 2018-02-06
Piotr Chaberski, WLOG Solutions
Copyright (c) WLOG Solutions
A brief intro...
Imagine that you are developing a project using R and
your big corporate customer, after weeks of processing
requests to establish open-source analytical environment,
finally managed to install R on their production machines.
Now you realized, that it would be nice to use some
Python library in your solution...
How would you tell the client to switch to Python for a
while?
Copyright (c) WLOG Solutions
Deployment
https://www.walldevil.com/wallpapers/a88/earth-moon-planet-astronaut.jpg
Scripting
Both R and Python are great for writing scripts, but...
Copyright (c) WLOG Solutions
Why R Suite?
• develop your solution maintaining
full control over dependencies
and their versions
• build the solution for a desired
production environment
• close your solution in ready-to-
deploy package that doesn’t
require any installations or
configuration… so doesn’t Python, to be clear
Copyright (c) WLOG Solutions
Why Python in R?
Why not only Python? Why not only R?
… but you still need some specific Python functionalities
Your client has R production
environment
You have well managed R
deployment procedure (using R
Suite)
You’d like to create a Shiny
app on top of your solution
You just know/like R better
Copyright (c) WLOG Solutions
So how to use Python when you have
R on production?
… just hide it deep down in your R Suite project
Deep learning using Keras/Tensorflow in R
Use case with focus on deployment
Copyright (c) WLOG Solutions
Prerequisites
• R
• R Suite CLI
• RStudio (optional but recommended)
• Miniconda
Example created on Windows, but after prerequisites are
installed for specific system, further steps are identical on Linux
Copyright (c) WLOG Solutions
Copyright (c) WLOG Solutions
Copyright (c) WLOG Solutions
Copyright (c) WLOG Solutions
Copyright (c) WLOG Solutions
Copyright (c) WLOG Solutions
Copyright (c) WLOG Solutions
Copyright (c) WLOG Solutions
Python code adapted from:
https://www.pyimagesearch.com/2016/09/26/a-simple-neural-network-with-python-and-keras
Dataset downloaded from:
https://www.kaggle.com/c/dogs-vs-cats/data
Copyright (c) WLOG Solutions
3 ways to use Keras in R
Copyright (c) WLOG Solutions
3 ways to use Keras in R
No matter how you use it, remember to use local Python!
use_python(python = dirname(...), required = TRUE)
Copyright (c) WLOG Solutions
1. keras R package
• most natural for R users
• wraps all Keras/Tensorflow
features with R syntax
• provides some R Studio
add-ins
• still uses reticulate and runs
Python under the hood
library(keras)
# keras model architecture
model <- keras_model_sequential() %>%
layer_dense(units = 768, input_shape = 3072, kernel_initializer
= "uniform", activation = "relu") %>%
layer_dense(units = 384, kernel_initializer = "uniform",
activation = "relu") %>%
layer_dense(units = 2, activation = "softmax")
# keras model compilation
loginfo("Compiling model...")
model %>% compile(
optimizer = optimizer_sgd(lr = 0.01),
loss = "binary_crossentropy",
metrics = "accuracy")
# keras model training and evaluation
loginfo("Model fitting and evaluation...")
model %>% fit(train_data, train_labels,
epochs = 20,
batch_size = 128,
validation_data = list(valid_data, valid_labels))
loginfo("Model training complete.")
Copyright (c) WLOG Solutions
2. reticulate interface
• general interface for
Python modules
• automatic conversions
between Python and R
data types (careful when
passing integers, tuples,
lists to Python functions)
• use “$” operator instead
of Python’s “.”
library(reticulate)
Sequential <- import("keras.models")$Sequential
Activation <- import("keras.layers")$Activation
SGD <- import("keras.optimizers")$SGD
Dense <- import("keras.layers")$Dense
# keras model architecture
model <- Sequential()
model$add(Dense(768L, input_dim = 3072L, init = "uniform",
activation = "relu"))
model$add(Dense(384L, init = "uniform", activation = "relu"))
model$add(Dense(2L))
model$add(Activation("softmax"))
# keras model compilation
loginfo("Compiling model...")
sgd <- SGD(lr = 0.01)
model$compile(loss = "binary_crossentropy",
optimizer = sgd,
metrics = list("accuracy"))
# keras model training and evaluation
loginfo("Starting model training...")
model$fit(train_data, train_labels,
epochs = 20L,
batch_size = 128L,
validation_data = list(valid_data, valid_labels))
loginfo("Model training complete.")
Copyright (c) WLOG Solutions
3. running raw Python
• handy when you already
have some code in
Python
• hard to control Python
script execution from R
(separate loggers etc.)
• all objects from Python
session available in R
(converted or not)
library(reticulate)
from keras.models import Sequential
from keras.layers import Activation
from keras.optimizers import SGD
from keras.layers import Dense
# keras model architecture
model = Sequential()
model.add(Dense(768, input_dim=3072, init="uniform",
activation="relu"))
model.add(Dense(384, init="uniform", activation="relu"))
model.add(Dense(2))
model.add(Activation("softmax"))
# keras model compilation
log.info("Compiling model...")
sgd = SGD(lr=0.01)
model.compile(loss="binary_crossentropy",
optimizer=sgd,
metrics=["accuracy"])
# keras model training and evaluation
log.info("Starting model training...")
model.fit(train_data, train_labels,
epochs=20,
batch_size=128,
validation_data=[valid_data, valid_labels])
log.info("Model training complete.")
py_script_results <- py_run_file(python_script_fpath, convert =
TRUE)
> py_script_results$model
<keras.models.Sequential>
Copyright (c) WLOG Solutions
Copyright (c) WLOG Solutions
Copyright (c) WLOG Solutions
Deployment package contains...
All R master scripts: All R binary packages:
Internal Python environment: Additional Python scripts:
Copyright (c) WLOG Solutions
Package deployment
Prod:
• binary consistent with Dev
• R
Dev:
• binary consistent with Prod
• R
• R Suite
• Miniconda
Copyright (c) WLOG Solutions
Soon in R Suite...
• add Python dependencies to R packages DESCRIPTION
• rsuite sysreqs collect; rsuite sysreqs install
• check if conda is installed, then create local Python env
• not only Python dependencies; also e.g. Linux system libraries
Copyright (c) WLOG Solutions
Piotr Chaberski
Thank You!
pchaberski@wlogsolutions.com
info@wlogsolutions.com
http://rsuite.io
https://github.com/WLOGSolutions/RSuite

More Related Content

PDF
Managing large scale projects in R with R Suite
PDF
Large scale machine learning projects with r suite
PDF
Build microservice with gRPC in golang
PPTX
Taking Jenkins Pipeline to the Extreme
PDF
The Challenges of Container Configuration
PDF
Hiveminder - Everything but the Secret Sauce
PPTX
Pynvme introduction
PDF
Últimas atualizações de produtividade no Visual Studio 2017​
Managing large scale projects in R with R Suite
Large scale machine learning projects with r suite
Build microservice with gRPC in golang
Taking Jenkins Pipeline to the Extreme
The Challenges of Container Configuration
Hiveminder - Everything but the Secret Sauce
Pynvme introduction
Últimas atualizações de produtividade no Visual Studio 2017​

What's hot (20)

PDF
Hardware monitoring with collectd at CERN
PDF
PyHEP 2018: Tools to bind to Python
PPTX
Js tacktalk team dev js testing performance
PDF
Source Plugins
PPT
Mod06 new development tools
PDF
How to Make Hand Detector on Native Activity with OpenCV
PPTX
PDF
Kernel Recipes 2018 - Live (Kernel) Patching: status quo and status futurus -...
PDF
Better Code: Concurrency
PDF
Functional and scale performance tests using zopkio
PDF
用 Go 語言打造多台機器 Scale 架構
PPTX
CI-CD WITH GITLAB WORKFLOW
PDF
What is new with JavaScript in Gnome: The 2021 edition
PDF
Job Queue in Golang
PDF
The Power of Rails 2.3 Engines & Templates
PDF
PyCon TW 2017 - PyPy's approach to construct domain-specific language runtime...
PDF
Kernel Recipes 2018 - 10 years of automated evolution in the Linux kernel - J...
PDF
Austin Python Meetup 2017: What's New in Pythons 3.5 and 3.6?
PDF
grep.metacpan.org
Hardware monitoring with collectd at CERN
PyHEP 2018: Tools to bind to Python
Js tacktalk team dev js testing performance
Source Plugins
Mod06 new development tools
How to Make Hand Detector on Native Activity with OpenCV
Kernel Recipes 2018 - Live (Kernel) Patching: status quo and status futurus -...
Better Code: Concurrency
Functional and scale performance tests using zopkio
用 Go 語言打造多台機器 Scale 架構
CI-CD WITH GITLAB WORKFLOW
What is new with JavaScript in Gnome: The 2021 edition
Job Queue in Golang
The Power of Rails 2.3 Engines & Templates
PyCon TW 2017 - PyPy's approach to construct domain-specific language runtime...
Kernel Recipes 2018 - 10 years of automated evolution in the Linux kernel - J...
Austin Python Meetup 2017: What's New in Pythons 3.5 and 3.6?
grep.metacpan.org
Ad

Similar to How to lock a Python in a cage? Managing Python environment inside an R project (20)

PDF
Keras & R
PPTX
INTRODUCTION TO KERAS FOR BEGINNERS.pptx
PPTX
KERAS Python Tutorial
PPTX
Keras on tensorflow in R & Python
PPTX
Next.ml Boston: Data Science Dev Ops
PDF
What We Learned Building an R-Python Hybrid Predictive Analytics Pipeline
PDF
CI-Keras for deep learning by adrian.pdf
PDF
Keras: Deep Learning Library for Python
PPTX
python_libraries_for_artificial_intelligence.pptx
PPTX
Machine Learning Toolssssssssssssss.pptx
PDF
Turbocharge your data science with python and r
PDF
Managing large (and small) R based solutions with R Suite
PDF
Keras and TensorFlow
PDF
PyTorch crash course
PDF
Introduction to python along with the comparitive analysis with r
PDF
Getting Started with Keras and TensorFlow - StampedeCon AI Summit 2017
PPTX
Keras_Core_introduction.pptx
PPTX
Python libraries
PDF
keras_tutorial.pdf
PDF
Hitchhiker's guide to the kerasverse
Keras & R
INTRODUCTION TO KERAS FOR BEGINNERS.pptx
KERAS Python Tutorial
Keras on tensorflow in R & Python
Next.ml Boston: Data Science Dev Ops
What We Learned Building an R-Python Hybrid Predictive Analytics Pipeline
CI-Keras for deep learning by adrian.pdf
Keras: Deep Learning Library for Python
python_libraries_for_artificial_intelligence.pptx
Machine Learning Toolssssssssssssss.pptx
Turbocharge your data science with python and r
Managing large (and small) R based solutions with R Suite
Keras and TensorFlow
PyTorch crash course
Introduction to python along with the comparitive analysis with r
Getting Started with Keras and TensorFlow - StampedeCon AI Summit 2017
Keras_Core_introduction.pptx
Python libraries
keras_tutorial.pdf
Hitchhiker's guide to the kerasverse
Ad

Recently uploaded (20)

PDF
Galatica Smart Energy Infrastructure Startup Pitch Deck
PPTX
Introduction to Firewall Analytics - Interfirewall and Transfirewall.pptx
PPTX
The THESIS FINAL-DEFENSE-PRESENTATION.pptx
PPTX
mbdjdhjjodule 5-1 rhfhhfjtjjhafbrhfnfbbfnb
PDF
Launch Your Data Science Career in Kochi – 2025
PPT
Chapter 2 METAL FORMINGhhhhhhhjjjjmmmmmmmmm
PDF
BF and FI - Blockchain, fintech and Financial Innovation Lesson 2.pdf
PPTX
Moving the Public Sector (Government) to a Digital Adoption
PPTX
Business Acumen Training GuidePresentation.pptx
PPTX
Acceptance and paychological effects of mandatory extra coach I classes.pptx
PPTX
CEE 2 REPORT G7.pptxbdbshjdgsgjgsjfiuhsd
PPTX
Supervised vs unsupervised machine learning algorithms
PPTX
05. PRACTICAL GUIDE TO MICROSOFT EXCEL.pptx
PDF
Clinical guidelines as a resource for EBP(1).pdf
PPT
Chapter 3 METAL JOINING.pptnnnnnnnnnnnnn
PPTX
Introduction to Basics of Ethical Hacking and Penetration Testing -Unit No. 1...
PPTX
IBA_Chapter_11_Slides_Final_Accessible.pptx
PPTX
1_Introduction to advance data techniques.pptx
PDF
168300704-gasification-ppt.pdfhghhhsjsjhsuxush
Galatica Smart Energy Infrastructure Startup Pitch Deck
Introduction to Firewall Analytics - Interfirewall and Transfirewall.pptx
The THESIS FINAL-DEFENSE-PRESENTATION.pptx
mbdjdhjjodule 5-1 rhfhhfjtjjhafbrhfnfbbfnb
Launch Your Data Science Career in Kochi – 2025
Chapter 2 METAL FORMINGhhhhhhhjjjjmmmmmmmmm
BF and FI - Blockchain, fintech and Financial Innovation Lesson 2.pdf
Moving the Public Sector (Government) to a Digital Adoption
Business Acumen Training GuidePresentation.pptx
Acceptance and paychological effects of mandatory extra coach I classes.pptx
CEE 2 REPORT G7.pptxbdbshjdgsgjgsjfiuhsd
Supervised vs unsupervised machine learning algorithms
05. PRACTICAL GUIDE TO MICROSOFT EXCEL.pptx
Clinical guidelines as a resource for EBP(1).pdf
Chapter 3 METAL JOINING.pptnnnnnnnnnnnnn
Introduction to Basics of Ethical Hacking and Penetration Testing -Unit No. 1...
IBA_Chapter_11_Slides_Final_Accessible.pptx
1_Introduction to advance data techniques.pptx
168300704-gasification-ppt.pdfhghhhsjsjhsuxush

How to lock a Python in a cage? Managing Python environment inside an R project

  • 1. Copyright (c) WLOG Solutions How to lock a Python in a cage? Managing Python environment inside an R project PyData meetup Warsaw, 2018-02-06 Piotr Chaberski, WLOG Solutions
  • 2. Copyright (c) WLOG Solutions A brief intro... Imagine that you are developing a project using R and your big corporate customer, after weeks of processing requests to establish open-source analytical environment, finally managed to install R on their production machines. Now you realized, that it would be nice to use some Python library in your solution... How would you tell the client to switch to Python for a while?
  • 3. Copyright (c) WLOG Solutions Deployment https://www.walldevil.com/wallpapers/a88/earth-moon-planet-astronaut.jpg Scripting Both R and Python are great for writing scripts, but...
  • 4. Copyright (c) WLOG Solutions Why R Suite? • develop your solution maintaining full control over dependencies and their versions • build the solution for a desired production environment • close your solution in ready-to- deploy package that doesn’t require any installations or configuration… so doesn’t Python, to be clear
  • 5. Copyright (c) WLOG Solutions Why Python in R? Why not only Python? Why not only R? … but you still need some specific Python functionalities Your client has R production environment You have well managed R deployment procedure (using R Suite) You’d like to create a Shiny app on top of your solution You just know/like R better
  • 6. Copyright (c) WLOG Solutions So how to use Python when you have R on production? … just hide it deep down in your R Suite project
  • 7. Deep learning using Keras/Tensorflow in R Use case with focus on deployment
  • 8. Copyright (c) WLOG Solutions Prerequisites • R • R Suite CLI • RStudio (optional but recommended) • Miniconda Example created on Windows, but after prerequisites are installed for specific system, further steps are identical on Linux
  • 9. Copyright (c) WLOG Solutions
  • 10. Copyright (c) WLOG Solutions
  • 11. Copyright (c) WLOG Solutions
  • 12. Copyright (c) WLOG Solutions
  • 13. Copyright (c) WLOG Solutions
  • 14. Copyright (c) WLOG Solutions
  • 15. Copyright (c) WLOG Solutions
  • 16. Copyright (c) WLOG Solutions Python code adapted from: https://www.pyimagesearch.com/2016/09/26/a-simple-neural-network-with-python-and-keras Dataset downloaded from: https://www.kaggle.com/c/dogs-vs-cats/data
  • 17. Copyright (c) WLOG Solutions 3 ways to use Keras in R
  • 18. Copyright (c) WLOG Solutions 3 ways to use Keras in R No matter how you use it, remember to use local Python! use_python(python = dirname(...), required = TRUE)
  • 19. Copyright (c) WLOG Solutions 1. keras R package • most natural for R users • wraps all Keras/Tensorflow features with R syntax • provides some R Studio add-ins • still uses reticulate and runs Python under the hood library(keras) # keras model architecture model <- keras_model_sequential() %>% layer_dense(units = 768, input_shape = 3072, kernel_initializer = "uniform", activation = "relu") %>% layer_dense(units = 384, kernel_initializer = "uniform", activation = "relu") %>% layer_dense(units = 2, activation = "softmax") # keras model compilation loginfo("Compiling model...") model %>% compile( optimizer = optimizer_sgd(lr = 0.01), loss = "binary_crossentropy", metrics = "accuracy") # keras model training and evaluation loginfo("Model fitting and evaluation...") model %>% fit(train_data, train_labels, epochs = 20, batch_size = 128, validation_data = list(valid_data, valid_labels)) loginfo("Model training complete.")
  • 20. Copyright (c) WLOG Solutions 2. reticulate interface • general interface for Python modules • automatic conversions between Python and R data types (careful when passing integers, tuples, lists to Python functions) • use “$” operator instead of Python’s “.” library(reticulate) Sequential <- import("keras.models")$Sequential Activation <- import("keras.layers")$Activation SGD <- import("keras.optimizers")$SGD Dense <- import("keras.layers")$Dense # keras model architecture model <- Sequential() model$add(Dense(768L, input_dim = 3072L, init = "uniform", activation = "relu")) model$add(Dense(384L, init = "uniform", activation = "relu")) model$add(Dense(2L)) model$add(Activation("softmax")) # keras model compilation loginfo("Compiling model...") sgd <- SGD(lr = 0.01) model$compile(loss = "binary_crossentropy", optimizer = sgd, metrics = list("accuracy")) # keras model training and evaluation loginfo("Starting model training...") model$fit(train_data, train_labels, epochs = 20L, batch_size = 128L, validation_data = list(valid_data, valid_labels)) loginfo("Model training complete.")
  • 21. Copyright (c) WLOG Solutions 3. running raw Python • handy when you already have some code in Python • hard to control Python script execution from R (separate loggers etc.) • all objects from Python session available in R (converted or not) library(reticulate) from keras.models import Sequential from keras.layers import Activation from keras.optimizers import SGD from keras.layers import Dense # keras model architecture model = Sequential() model.add(Dense(768, input_dim=3072, init="uniform", activation="relu")) model.add(Dense(384, init="uniform", activation="relu")) model.add(Dense(2)) model.add(Activation("softmax")) # keras model compilation log.info("Compiling model...") sgd = SGD(lr=0.01) model.compile(loss="binary_crossentropy", optimizer=sgd, metrics=["accuracy"]) # keras model training and evaluation log.info("Starting model training...") model.fit(train_data, train_labels, epochs=20, batch_size=128, validation_data=[valid_data, valid_labels]) log.info("Model training complete.") py_script_results <- py_run_file(python_script_fpath, convert = TRUE) > py_script_results$model <keras.models.Sequential>
  • 22. Copyright (c) WLOG Solutions
  • 23. Copyright (c) WLOG Solutions
  • 24. Copyright (c) WLOG Solutions Deployment package contains... All R master scripts: All R binary packages: Internal Python environment: Additional Python scripts:
  • 25. Copyright (c) WLOG Solutions Package deployment Prod: • binary consistent with Dev • R Dev: • binary consistent with Prod • R • R Suite • Miniconda
  • 26. Copyright (c) WLOG Solutions Soon in R Suite... • add Python dependencies to R packages DESCRIPTION • rsuite sysreqs collect; rsuite sysreqs install • check if conda is installed, then create local Python env • not only Python dependencies; also e.g. Linux system libraries
  • 27. Copyright (c) WLOG Solutions Piotr Chaberski Thank You! pchaberski@wlogsolutions.com info@wlogsolutions.com http://rsuite.io https://github.com/WLOGSolutions/RSuite