13  Python 💖 R

13.1 Lernsteuerung

13.1.1 Lernziele

  • Sie wissen, wo und wie Sie sich die Grundlagen von Python aneignen können.
  • Sie können Python aus RStudio heraus verwenden.
  • Sie können grundlegende Funktionen zur Verwaltung Ihrer Python-Installation wie das Hinzufügen von Modulen.

13.1.2 Begleitliteratur

Es gibt viele Lehrbücher zu Python. Mein Rat ist, das zu wählen, das es in Ihrer Lieblingsbibliothek gibt. 🤓 Solange es einigermaßen uptodate ist und Ihnen die didaktische Aufmachung zusagt.

Hier ist eine Auswahl an Einstiegsbücher in deutscher Sprache: Bekannt ist z.B. Downey (2021); vergleichsweise aktuell ist Inden (2023); auch ganz nett ist Barry (2017).

(Beat im Hintergrund…)

Python:

Yo, I’m Python, the snake that’s striking, Clean syntax, got your code reciting. Versatile, dynamic, no need for stressing, From web apps to scripts, I’m truly impressing.

Pandas roll deep, handling data so fine, NumPy’s my crew, doing math in every line. Machine learning skills, yeah, I got the game, TensorFlow and PyTorch, ain’t that my fame?

Indentation’s the key, my style’s so clean, Readability supreme, in every code scene. Fluent in libraries, got Matplotlib on the beat, Visualizing data, making it all sweet.

R:

Hold up, Python, slow down the hype, I’m R, in statistics, I’m the type. Dataframes and vectors, I pioneered the game, ggplot2’s my art, visuals never the same.

Tidyverse, my squad, we stay organized, Read and manipulate, got data mesmerized. Shiny apps shining, interactive delight, In the world of data, I’m taking flight.

Base R or dplyr, I got the choices, Statistical models, hear the data’s voices. In the realm of data science, I hold my own, From regression to clustering, my skills are honed.

Python:

R, you’re cool with stats, I give you that, But in the industry, I’m where it’s at. Django and Flask, web frameworks so sleek, Building APIs, from strong to boutique.

Jupyter Notebooks, my interactive stage, Collaborating with data at every page. Anaconda’s my lair, where I thrive, In the world of programming, I’m the hive.

R:

Python, you’re flashy, I won’t deny, But in data analysis, I reach for the sky. RMarkdown’s my rhyme, in reports so sweet, Knitting documents, making it elite.

CRAN repository, where packages reside, Shiny dashboards, taking users on a ride. I might be niche, but my stats are profound, In the world of data, I wear the crown.

(Beat fades out…)

Quelle: ChatGPT 3.5, 2023-11-23

13.2 Python aus RStudio

RStudio bietet die Möglichkeit, R und Python gleichzeitig in einem Notebook zu verwenden. Und nicht nur das:

  • Man kann Objekte (Daten) zwischen den beiden Sprachen tauschen
  • Man kann aus R Python-Funktionen verwenden.

Sie haben zwei Möglichkeiten, Python in RStudio zu nutzen:

  1. Öffnen Sie ein reines Python-Skript.
  2. Fügen Sie Python-Chunks in ein Notebook (d.h. Quarto-Doc) ein.

Quelle: Imgflip

13.3 Python-Setup

13.3.1 Python installieren

Man kann Python kostenlos herunterladen bei https://www.python.org/downloads/. Hier ist eine Anleitung von Wikihow. Bei Unix-Betriebssystemen werden häufig Paketmanager verwendet.

Welche Versionen gibt’s?

pyenv install --list
pyenv install 3.12.0a3

13.3.2 Welche Python-Version läuft gerade?

In R läuft gerade folgende Python-Version:

library(reticulate)
py_config()
## python:         /Users/sebastiansaueruser/.virtualenvs/r-tensorflow/bin/python
## libpython:      /Users/sebastiansaueruser/.pyenv/versions/3.8.16/lib/libpython3.8.dylib
## pythonhome:     /Users/sebastiansaueruser/.virtualenvs/r-tensorflow:/Users/sebastiansaueruser/.virtualenvs/r-tensorflow
## version:        3.8.16 (default, Sep 15 2023, 17:53:02)  [Clang 14.0.3 (clang-1403.0.22.14.1)]
## numpy:          /Users/sebastiansaueruser/.virtualenvs/r-tensorflow/lib/python3.8/site-packages/numpy
## numpy_version:  1.24.3
## 
## NOTE: Python version was forced by VIRTUAL_ENV

Aus der reticulate-Doku:

By default, reticulate uses an isolated python virtual environment named “r-reticulate”.

Check: Ist Python gestartet und bereit?

py_available()
## [1] TRUE

Wir können die Kommandozeile auch aus Notebooks heraus ansprechen.

```{zsh}
python --version
```
## Python 3.8.16

Aber Achtung: Die gezeigt Version ist nicht unbedingt diejenige, die im Notebook oder im interaktiven R verwendet wird.

RStudio zeigt Ihnen, welche Python-Versionen verfügbar sind unter Tools > Global Options > Python.

13.3.3 Versionen wechseln

13.3.3.1 RStudio

RStudio bietet in den Optionen per GUI die Möglichkeit, eine bestimmte Version von Python auszuwählen. Zumeist sind mehrere Versionen auf einem Computer vorhanden.

Natürlich kann man auch via R virtuelle Environments (venvs) nutzen, wie es in Python üblich ist:

use_virtualenv("r-tensorflow")

Oder man legt sich solche venvs an:

reticulate::virtualenv_create("scikit-llm")

Mit pyenv virtualenv legt man eine neue venv mit Namen my_venv an:

pyenv virtualenv 3.11.1 test_venv

13.3.3.2 Pyenv

Mit pyenv kann man komfortabel zwischen mehreren installierten Python-Versionen wechseln.

Um Python-Module zu installieren via pyenv bietet sich dieser (Kommondozeilen-)Befehl an:

pyenv exec pip install <name-des-moduls>.

Beispiel 13.1 Um das Modul spacy zu installieren, schreibt man pyenv exec pip install spacy. \(\square\)

in der Shell ist gerade folgende Python-Version aktiviert:

system2(command = "pyenv",
        args = "version")
pyenv version
## 3.11.1 (set by /Users/sebastiansaueruser/.python-version)

Die “aktuelle” Python-Version ist nicht (unbedingt) die Python-Version, die in R aktiv ist. \(\square\)

```{zsh}
pyenv versions
```
##   system
##   3.8.1
##   3.8.16
##   3.9.16
## * 3.11.1 (set by /Users/sebastiansaueruser/.python-version)
Vorsicht

Es werden nur Python-Versionen angezeigt, die im Pfad (in der Shell) definiert sind. \(\square\)

13.3.4 Liste installierter Module

Die Liste installierter Module bezieht sich auf die aktuell aktivierte Version von Python.

pip list
## Package                       Version
## ----------------------------- ------------
## absl-py                       1.4.0
## aiohttp                       3.9.0
## aiosignal                     1.3.1
## annotated-types               0.6.0
## anyio                         3.7.1
## array-record                  0.4.0
## astunparse                    1.6.3
## async-timeout                 4.0.3
## attrs                         23.1.0
## cachetools                    5.3.1
## certifi                       2023.7.22
## charset-normalizer            3.3.0
## click                         8.1.7
## distro                        1.8.0
## dm-tree                       0.1.8
## etils                         1.3.0
## exceptiongroup                1.2.0
## filelock                      3.13.1
## flatbuffers                   23.5.26
## frozenlist                    1.4.0
## fsspec                        2023.10.0
## gast                          0.4.0
## google-api-core               2.14.0
## google-auth                   2.23.4
## google-auth-oauthlib          1.0.0
## google-cloud-aiplatform       1.36.4
## google-cloud-bigquery         3.13.0
## google-cloud-core             2.3.3
## google-cloud-resource-manager 1.10.4
## google-cloud-storage          2.13.0
## google-crc32c                 1.5.0
## google-pasta                  0.2.0
## google-resumable-media        2.6.0
## googleapis-common-protos      1.60.0
## grpc-google-iam-v1            0.12.7
## grpcio                        1.59.3
## grpcio-status                 1.59.3
## h11                           0.14.0
## h5py                          3.9.0
## httpcore                      1.0.2
## httpx                         0.25.1
## huggingface                   0.0.1
## huggingface-hub               0.19.4
## idna                          3.4
## importlib-metadata            6.8.0
## importlib-resources           6.1.0
## joblib                        1.3.2
## keras                         2.13.1
## libclang                      16.0.6
## Markdown                      3.4.4
## MarkupSafe                    2.1.3
## multidict                     6.0.4
## numpy                         1.24.3
## oauthlib                      3.2.2
## openai                        1.3.5
## opt-einsum                    3.3.0
## packaging                     23.2
## pandas                        2.0.3
## Pillow                        10.0.1
## pip                           23.2.1
## promise                       2.3
## proto-plus                    1.22.3
## protobuf                      4.25.1
## psutil                        5.9.5
## pyasn1                        0.5.0
## pyasn1-modules                0.3.0
## pydantic                      2.5.2
## pydantic_core                 2.14.5
## pydot                         1.4.2
## pyparsing                     3.1.1
## python-dateutil               2.8.2
## pytz                          2023.3.post1
## PyYAML                        6.0.1
## regex                         2023.10.3
## requests                      2.31.0
## requests-oauthlib             1.3.1
## rsa                           4.9
## safetensors                   0.4.0
## scikit-learn                  1.3.2
## scipy                         1.10.1
## setuptools                    68.2.2
## shapely                       2.0.2
## six                           1.16.0
## sniffio                       1.3.0
## tensorboard                   2.13.0
## tensorboard-data-server       0.7.1
## tensorflow                    2.13.1
## tensorflow-datasets           4.9.2
## tensorflow-estimator          2.13.0
## tensorflow-hub                0.14.0
## tensorflow-io-gcs-filesystem  0.34.0
## tensorflow-metadata           1.14.0
## termcolor                     2.3.0
## threadpoolctl                 3.2.0
## tokenizers                    0.15.0
## toml                          0.10.2
## tqdm                          4.66.1
## transformers                  4.35.2
## typing_extensions             4.8.0
## tzdata                        2023.3
## urllib3                       2.0.6
## Werkzeug                      3.0.0
## wheel                         0.41.2
## wrapt                         1.15.0
## yarl                          1.9.3
## zipp                          3.17.0
## 
## [notice] A new release of pip is available: 23.2.1 -> 23.3.1
## [notice] To update, run: pip install --upgrade pip
import os
os.system("pip list")
## 0

Die Version eines bestimmten installierten Moduls bekommt man einfach mit grep:

!pip list | grep openai

Das Ausrufezeichen ! zeigt Shell-Code in einem Python-Chunk an. Der Balken | ist eine Pfeife wie |> in R.

13.3.5 Module installieren

Mit dem Kommandozeilen-Befehl pip kann man Pythonmodule installieren.

pip install module-name

Dabei steht module-name für den Namen des zu installierenden Moduls, z.B. openai.

Und auch wieder löschen

pip uninstall module-name

Oder via R:

py_install("openai")

13.4 Einstieg in Python

13.4.1 Hallo, 🐍

```{python}
print("Hello! Here's 🐍")

python_list = [1,2,3]  # im Standard Integer
python_list
```
## Hello! Here's 🐍
## [1, 2, 3]

13.4.2 Objektaustausch zwischen R und Python

In R ein Python-Objekt ansprechen, das geht mit py$:

py$python_list
## [1] 1 2 3

r_vec <- c(1L,2L,3L)  # Integer aktiv gewählt, da R im Standard  Float wählt
r_vec
## [1] 1 2 3

In Python ein R-Objekt ansprechen, das geht mit r.:

r.r_vec
## [1, 2, 3]

13.5 Vertiefung

Es gibt viele Onlinekurse, um Python zu lernen, z.B. Googles Crashkurs bei Coursera; überhaupt bietet Coursera eine Menge Onlinekurse zu dem Thema Python. Andere Anbieter bieten das auch, etwa edx. https://www.learnpython.org/ bietet einen E-Learning-Kurs.

Barry, Paul. 2017. Python von Kopf bis Fuß. Übersetzt von Jørgen W. Lang. Zweite Auflage. Von Kopf bis Fuß. Beijing Boston Farnham Sebastopol Tokyo: O’Reilly.
Downey, Allen B. 2021. Think Python: systematisch programmieren lernen mit Python. Übersetzt von Peter Klicman. 1. Auflage. Heidelberg: O’Reilly.
Inden, Michael. 2023. Python lernen: kurz & gut. 1. Auflage. O’Reillys Taschenbibliothek. Heidelberg: O’Reilly.