### Installing PyCall.rb Gem Source: https://github.com/red-data-tools/pycall.rb/blob/master/README.md Demonstrates the standard methods for installing the PyCall.rb gem, either by adding it to the application's Gemfile and running bundle, or by installing it directly using the `gem install` command. ```ruby gem 'pycall' ``` ```bash $ bundle ``` ```bash $ gem install --pre pycall ``` -------------------------------- ### Installing PyCall.rb with pyenv and Shared Library Source: https://github.com/red-data-tools/pycall.rb/blob/master/README.md Provides instructions for installing PyCall.rb when using pyenv. It highlights the need to enable shared library support during Python installation using the `--enable-shared` flag. ```bash env PYTHON_CONFIGURE_OPTS='--enable-shared' pyenv install 3.7.2 ``` -------------------------------- ### Benchmark Array#inject in Ruby Source: https://github.com/red-data-tools/pycall.rb/blob/master/examples/notebooks/sum_benchmarking.ipynb This code benchmarks the performance of the `Array#inject` method in Ruby for summation. It measures the runtime over a specified number of trials. ```ruby require 'benchmark' n = 100_000 trials = 100 array = Array.new(n) { rand } enum = array.each method = [] runtime = [] # Array#inject trials.times do method << 'array.inject' runtime << Benchmark.realtime { array.inject :+ } end ``` -------------------------------- ### Benchmark Array#sum in Ruby Source: https://github.com/red-data-tools/pycall.rb/blob/master/examples/notebooks/sum_benchmarking.ipynb This code benchmarks the performance of the `Array#sum` method in Ruby. It measures the runtime over a specified number of trials and stores the results. ```ruby require 'benchmark' n = 100_000 trials = 100 array = Array.new(n) { rand } enum = array.each method = [] runtime = [] # Array#sum trials.times do method << 'array.sum' runtime << Benchmark.realtime { array.sum } end ``` -------------------------------- ### Benchmark Enumerable#inject in Ruby Source: https://github.com/red-data-tools/pycall.rb/blob/master/examples/notebooks/sum_benchmarking.ipynb This code benchmarks the performance of the `Enumerable#inject` method in Ruby using an enumerator for summation. It measures the runtime over a specified number of trials. ```ruby require 'benchmark' n = 100_000 trials = 100 array = Array.new(n) { rand } enum = array.each method = [] runtime = [] # Enumerable#inject trials.times do method << 'enum.inject' runtime << Benchmark.realtime { enum.inject :+ } end ``` -------------------------------- ### Benchmark Enumerable#sum in Ruby Source: https://github.com/red-data-tools/pycall.rb/blob/master/examples/notebooks/sum_benchmarking.ipynb This code benchmarks the performance of the `Enumerable#sum` method in Ruby using an enumerator. It measures the runtime over a specified number of trials. ```ruby require 'benchmark' n = 100_000 trials = 100 array = Array.new(n) { rand } enum = array.each method = [] runtime = [] # Array#sum trials.times do method << 'array.sum' runtime << Benchmark.realtime { array.sum } end # Enumerable#sum trials.times do method << 'enum.sum' runtime << Benchmark.realtime { enum.sum } end ``` -------------------------------- ### Create Pandas DataFrame from Benchmark Results Source: https://github.com/red-data-tools/pycall.rb/blob/master/examples/notebooks/sum_benchmarking.ipynb This snippet uses PyCall to create a Pandas DataFrame from the collected benchmark data, including method names and their runtimes. This prepares the data for analysis. ```ruby require 'pycall/import' include PyCall::Import pyimport :pandas, as: :pd df = pd.DataFrame.new(data: {method: method, runtime: runtime}) df.groupby('method').describe() ``` -------------------------------- ### Benchmark Custom While Loop Summation in Ruby Source: https://github.com/red-data-tools/pycall.rb/blob/master/examples/notebooks/sum_benchmarking.ipynb This code benchmarks a custom Ruby method `while_sum` that calculates the sum of an array using a while loop. It measures the runtime over a specified number of trials. ```ruby require 'benchmark' n = 100_000 trials = 100 array = Array.new(n) { rand } enum = array.each method = [] runtime = [] # while def while_sum(array) sum, i, cnt = 0, 0, array.length while i < cnt sum += array[i] i += 1 end sum end trials.times do method << 'while' runtime << Benchmark.realtime { while_sum(array) } end ``` -------------------------------- ### Import Python Libraries with PyCall Source: https://github.com/red-data-tools/pycall.rb/blob/master/examples/notebooks/sum_benchmarking.ipynb This snippet shows how to import Python libraries like pandas and seaborn into a Ruby environment using PyCall. It sets up aliases for easier access to these libraries. ```ruby require 'matplotlib/iruby' Matplotlib::IRuby.activate require 'pycall/import' include PyCall::Import pyimport :pandas, as: :pd pyimport :seaborn, as: :sns ``` -------------------------------- ### Create a Simple Plot with Matplotlib in IRuby Source: https://github.com/red-data-tools/pycall.rb/blob/master/examples/notebooks/iruby_integration.ipynb This example shows how to create a basic line plot using Matplotlib within an IRuby environment after activating the integration. It plots a series of y-values against x-values. ```ruby plt.plot([1, 2, 3, 4, 5], [1, 2, 3, 1, 2]) ``` -------------------------------- ### Generate Seaborn Barplot for Benchmark Results Source: https://github.com/red-data-tools/pycall.rb/blob/master/examples/notebooks/sum_benchmarking.ipynb This code uses PyCall to integrate with Matplotlib and Seaborn to create a bar plot visualizing the benchmark results. It sets the title and axis labels for clarity. ```ruby require 'matplotlib/iruby' Matplotlib::IRuby.activate require 'pycall/import' include PyCall::Import pyimport :seaborn, as: :sns sns.barplot(x: 'method', y: 'runtime', data: df, errwidth: 2.5, capsize: 0.04) plt = Matplotlib::Pyplot plt.title("Array and Enumerable summation benchmark (#{trials} trials)") plt.xlabel("Summation method") plt.ylabel("Average runtime [sec]") ``` -------------------------------- ### Debug PyCall Python library discovery Source: https://github.com/red-data-tools/pycall.rb/blob/master/README.md Enables verbose logging for the PyCall python finder mechanism. This helps diagnose issues where the library cannot locate the required Python installation or shared libraries. ```bash PYCALL_DEBUG_FIND_LIBPYTHON=1 ruby -rpycall -ePyCall.builtins ``` -------------------------------- ### Create Multiple Independent Matplotlib Figures in IRuby Source: https://github.com/red-data-tools/pycall.rb/blob/master/examples/notebooks/iruby_integration.ipynb This example demonstrates how to create and manage multiple independent figures using Matplotlib within IRuby. Each `plt.figure()` call creates a new, separate plotting area. ```ruby # Multiple figures plt.figure() plt.plot([1, 2, 3, 4, 5], [1, 2, 3, 1, 2]) plt.figure() plt.plot([10, 20, 30, 40, 50], [1, 2, 3, 1, 2]) ``` -------------------------------- ### Initialize Matplotlib for IRuby Source: https://github.com/red-data-tools/pycall.rb/blob/master/examples/notebooks/classifier_comparison.ipynb Activates the Matplotlib backend for the IRuby notebook environment to enable plotting. ```ruby require 'matplotlib/iruby' Matplotlib::IRuby.activate plt = Matplotlib::Pyplot mplc = Matplotlib.colors ``` -------------------------------- ### Configure Classifiers and Datasets Source: https://github.com/red-data-tools/pycall.rb/blob/master/examples/notebooks/classifier_comparison.ipynb Defines a list of machine learning classifiers and generates synthetic datasets for evaluation. ```ruby h = 0.02 names = ['Nearest Neighbors', 'Linear SVM', 'RBF SVM', 'Decision Tree', 'Random Forest', 'AdaBoost', 'Naive Bayes', 'Linear Discriminant Analysis', 'Quadratic Discriminant Analysis'] classifiers = [ KNeighborsClassifier.new(3), SVC.new(kernel: 'linear', C: 0.025), SVC.new(gamma: 2, C: 1), DecisionTreeClassifier.new(max_depth: 5), RandomForestClassifier.new(max_depth: 5, n_estimators: 10, max_features: 1), AdaBoostClassifier.new, GaussianNB.new, LinearDiscriminantAnalysis.new, QuadraticDiscriminantAnalysis.new ] x, y = *make_classification(n_features: 2, n_redundant: 0, n_informative: 2, random_state: 1, n_clusters_per_class: 1) np.random.seed(42) x += 2 * np.random.random_sample(x.shape) linearly_separable = [x, y] datasets = [make_moons(noise: 0.3, random_state: 0), make_circles(noise: 0.2, factor: 0.5, random_state: 1), linearly_separable] ``` -------------------------------- ### Calling Python Constructors and Callable Objects in Ruby Source: https://github.com/red-data-tools/pycall.rb/blob/master/README.md Illustrates how PyCall.rb maps Python's constructor and callable object syntax to Ruby equivalents. Class instantiation uses `.new` and calling objects uses `.()`. Keyword arguments are passed using Ruby's hash syntax. ```ruby # Calling a constructor classname.new(x, y, z) # Calling a callable object obj.(x, y, z) # Passing keyword arguments func(x: 1, y: 2, z: 3) ``` -------------------------------- ### Initialize PyCall and Scikit-Learn environment Source: https://github.com/red-data-tools/pycall.rb/blob/master/examples/notebooks/forest_importances.ipynb Sets up the necessary Python libraries including NumPy, scikit-learn, and Matplotlib within the Ruby environment. This is a prerequisite for running machine learning workflows via PyCall. ```ruby require 'matplotlib/iruby' Matplotlib::IRuby.activate plt = Matplotlib::Pyplot require 'pycall/import' include PyCall::Import pyimport 'numpy', as: 'np' pyfrom 'sklearn.datasets', import: :fetch_olivetti_faces pyfrom 'sklearn.datasets', import: :make_classification pyfrom 'sklearn.ensemble', import: :ExtraTreesClassifier ``` -------------------------------- ### Creating Maps and Markers with Folium Source: https://github.com/red-data-tools/pycall.rb/blob/master/examples/notebooks/leaflet.ipynb Shows how to instantiate a Folium map object and add a marker to it using Ruby syntax. This leverages PyCall's ability to call Python class constructors and methods directly. ```ruby map = folium.Map.new(location: [35.68053684909772, 139.75749875116222], zoom_start: 15) folium.Marker.new([35.67400045350403, 139.75593234124372], popup: "日比谷公園").add_to(map) map ``` -------------------------------- ### Initialize PyCall and Matplotlib Environment Source: https://github.com/red-data-tools/pycall.rb/blob/master/examples/notebooks/lorenz_attractor.ipynb Configures the Ruby environment to use PyCall for importing Python libraries, specifically Matplotlib and NumPy, and enables 3D plotting capabilities. ```ruby require 'matplotlib/iruby' Matplotlib::IRuby.activate plt = Matplotlib::Pyplot require 'pycall/import' include PyCall::Import pyimport :numpy, as: :np require 'matplotlib/axes_3d' ``` -------------------------------- ### Simulate Lorenz System State Source: https://github.com/red-data-tools/pycall.rb/blob/master/examples/notebooks/lorenz_attractor.ipynb Initializes NumPy arrays to store simulation data and iterates through time steps to calculate the trajectory of the Lorenz attractor based on the defined differential equations. ```ruby dt = 0.01 stepCnt = 10_000 xs = np.empty([stepCnt + 1]) ys = np.empty([stepCnt + 1]) zs = np.empty([stepCnt + 1]) xs[0], ys[0], zs[0] = 0.0, 1.0, 1.05 stepCnt.times do |i| x_dot, y_dot, z_dot = lorenz(xs[i], ys[i], zs[i]) xs[i + 1] = xs[i] + (x_dot * dt) ys[i + 1] = ys[i] + (y_dot * dt) zs[i + 1] = zs[i] + (z_dot * dt) end ``` -------------------------------- ### Import Python Module and Call Function in Ruby Source: https://github.com/red-data-tools/pycall.rb/blob/master/README.md Demonstrates how to import a Python module (e.g., 'math') and call its functions (e.g., 'sin') from Ruby using PyCall. Automatic type conversions are handled for basic data types. ```ruby require 'pycall' math = PyCall.import_module("math") math.sin(math.pi / 4) - Math.sin(Math::PI / 4) # => 0.0 ``` -------------------------------- ### Importing Python Modules with PyCall Source: https://github.com/red-data-tools/pycall.rb/blob/master/examples/notebooks/leaflet.ipynb Demonstrates how to load a Python library into the Ruby runtime using PyCall.import_module. This allows Ruby scripts to access Python-specific functionality like the Folium mapping library. ```ruby require "pycall" folium = PyCall.import_module("folium") ``` -------------------------------- ### Run PyCall Docker Image Source: https://github.com/red-data-tools/pycall.rb/blob/master/docker/README.md Executes the PyCall Docker image. The `port` option specifies the connection port for iruby notebook. The `attach_local` option allows mounting a local directory into the container at `/notebooks/local` for access within Jupyter notebooks. Defaults to the current directory. ```shell rake docker:run [port=] [attach_local=] ``` -------------------------------- ### Visualize Classifier Decision Boundaries Source: https://github.com/red-data-tools/pycall.rb/blob/master/examples/notebooks/classifier_comparison.ipynb Iterates through datasets and classifiers to train models, calculate scores, and plot decision boundaries using Matplotlib. ```ruby fig = plt.figure(figsize: [27, 9]) i = 1 all = 0..-1 datasets.each do |ds| x, y = *ds x = StandardScaler.new.fit_transform(x) x_train, x_test, y_train, y_test = *train_test_split(x, y, test_size: 0.4) x_min, x_max = np.min(x[all, 0]) - 0.5, np.max(x[all, 0]) + 0.5 y_min, y_max = np.min(x[all, 1]) - 0.5, np.max(x[all, 1]) + 0.5 xx, yy = np.meshgrid(np.linspace(x_min, x_max, ((x_max - x_min)/h).round), np.linspace(y_min, y_max, ((y_max - y_min)/h).round)) mesh_points = np.dstack([xx.ravel, yy.ravel])[0, all, all] cm = plt.cm.__dict__[:RdBu] cm_bright = mplc.ListedColormap.new(["#FF0000", "#0000FF"]) names.zip(classifiers).each do |name, clf| ax = plt.subplot(datasets.length, classifiers.length + 1, i) clf.fit(x_train, y_train) scor = clf.score(x_test, y_test) begin z = clf.decision_function(mesh_points) rescue z = clf.predict_proba(mesh_points)[all, 1] end z = z.reshape(xx.shape) ax.contourf(xx, yy, z, cmap: cm, alpha: 0.8) ax.scatter(x_train[all, 0], x_train[all, 1], c: y_train, cmap: cm_bright) ax.scatter(x_test[all, 0], x_test[all, 1], c: y_test, cmap: cm_bright, alpha: 0.6) ax.set_title(name) i += 1 end end fig.subplots_adjust(left: 0.02, right: 0.98) ``` -------------------------------- ### Build PyCall Docker Image Source: https://github.com/red-data-tools/pycall.rb/blob/master/docker/README.md Builds a custom Docker image for PyCall. This command is useful if modifications are made to the PyCall project and a new image needs to be created. ```shell rake docker:build ``` -------------------------------- ### Import Scikit-Learn Modules via PyCall Source: https://github.com/red-data-tools/pycall.rb/blob/master/examples/notebooks/classifier_comparison.ipynb Imports necessary Python modules from Scikit-Learn and NumPy into the Ruby namespace using PyCall. ```ruby require 'pycall/import' include PyCall::Import pyimport 'numpy', as: :np pyfrom 'sklearn.model_selection', import: :train_test_split pyfrom 'sklearn.preprocessing', import: :StandardScaler pyfrom 'sklearn.datasets', import: %i(make_moons make_circles make_classification) pyfrom 'sklearn.neighbors', import: :KNeighborsClassifier pyfrom 'sklearn.svm', import: :SVC pyfrom 'sklearn.tree', import: :DecisionTreeClassifier pyfrom 'sklearn.ensemble', import: %i(RandomForestClassifier AdaBoostClassifier) pyfrom 'sklearn.naive_bayes', import: :GaussianNB pyfrom 'sklearn.discriminant_analysis', import: %i(LinearDiscriminantAnalysis QuadraticDiscriminantAnalysis) ``` -------------------------------- ### Initialize GridSearchCV for SVC in Python Source: https://github.com/red-data-tools/pycall.rb/blob/master/examples/datascience_rb_20170519.ipynb This snippet initializes a GridSearchCV object from scikit-learn to perform hyperparameter tuning for a Support Vector Classifier (SVC). It specifies the SVC kernel, the parameter grid for C and gamma, the scoring metric (roc_auc), the number of parallel jobs, and the cross-validation folds. The gamma values are calculated as the inverse of a list of integers. ```python svc = GridSearchCV( SVC(kernel='rbf'), { 'C': [10.0, 1.0, 0.1, 0.01], 'gamma': [5, 10, 15, 20].map {|x| 1.0 / x }, }, scoring='roc_auc', n_jobs=4, cv=5 ) ``` -------------------------------- ### Fit SVC Model using GridSearchCV in Python Source: https://github.com/red-data-tools/pycall.rb/blob/master/examples/datascience_rb_20170519.ipynb This code snippet demonstrates fitting the initialized GridSearchCV object to the training data (x, y). The `fit` method trains the SVC model with different hyperparameter combinations defined in the `param_grid` and evaluates them using cross-validation. The result is an updated GridSearchCV object containing the results of the training process. ```python svc.fit(x, y) ``` -------------------------------- ### Analyze pixel importance in image datasets Source: https://github.com/red-data-tools/pycall.rb/blob/master/examples/notebooks/forest_importances.ipynb Trains an ExtraTreesClassifier on the Olivetti faces dataset to determine pixel-level importance. The results are visualized as a heatmap using Matplotlib's matshow function. ```ruby n_jobs = 1 data = fetch_olivetti_faces() x = data.images.reshape([PyCall.len(data.images), -1]) y = data.target mask = y < 5 x = x[mask] y = y[mask] forest = ExtraTreesClassifier.new(n_estimators: 1_000, max_features: 128, n_jobs: n_jobs, random_state: 0) forest.fit(x, y) importances = forest.feature_importances_.reshape(data.images[0].shape) plt.matshow(importances, cmap: plt.cm.__dict__[:hot]) plt.title("Pixel importances with forests of trees") ``` -------------------------------- ### Create DataFrame and Bar Plot for Model Scores (Python) Source: https://github.com/red-data-tools/pycall.rb/blob/master/examples/datascience_rb_20170519.ipynb This Python code snippet demonstrates how to create a pandas DataFrame to store model names and their corresponding best scores. It then uses seaborn to generate a bar plot for visualizing these scores. This is useful for comparing the performance of different models. ```python result = pd.DataFrame.(data: { model: %w[RFC LRC SVC], score: [rfc.best_score_, lrc.best_score_, svc.best_score_] }) sns.barplot.(x: :model, y: :score, data: result) ``` -------------------------------- ### Visualize Lorenz Attractor in 3D Source: https://github.com/red-data-tools/pycall.rb/blob/master/examples/notebooks/lorenz_attractor.ipynb Uses Matplotlib to render the calculated trajectory in a 3D plot, setting labels and titles for the axes. ```ruby fig = plt.figure() ax = fig.gca(projection: '3d') ax.plot(xs, ys, zs, lw: 0.5) ax.set_xlabel("X Axis") ax.set_ylabel("Y Axis") ax.set_zlabel("Z Axis") ax.set_title("Lorenz Attractor") ``` -------------------------------- ### Calculate and visualize feature importances Source: https://github.com/red-data-tools/pycall.rb/blob/master/examples/notebooks/forest_importances.ipynb Generates a synthetic classification dataset, trains an ExtraTreesClassifier, and computes feature importances. It outputs a ranked list of features and generates a bar chart using Matplotlib. ```ruby x, y = *make_classification( n_samples: 1000, n_features: 10, n_informative: 3, n_redundant: 0, n_repeated: 0, n_classes: 2, random_state: 0, shuffle: false ) forest = ExtraTreesClassifier.new(n_estimators: 250, random_state: 0) forest.fit(x, y) importances = forest.feature_importances_ std = np.std(forest.estimators_.map {|tree| tree.feature_importances_ }, axis: 0) indices = np.argsort(importances)[(-1..0).step(-1)] puts "Feature ranking:" x.shape[1].times do |f| puts "%d. feature %d (%f)" % [f + 1, indices[f].to_i, importances[indices[f]]] end plt.figure() plt.title("Feature importances") plt.bar([*0...x.shape[1]], importances[indices], color: "r", yerr: std[indices], align: "center") plt.xticks([*0...x.shape[1]], indices) plt.xlim([-1, x.shape[1]]) ``` -------------------------------- ### Initialize PyCall and Import Python Libraries in Ruby Source: https://github.com/red-data-tools/pycall.rb/blob/master/examples/notebooks/xkcd_style.ipynb This snippet initializes the PyCall gem and imports necessary Python libraries, specifically 'numpy' aliased as 'np' and 'matplotlib.pyplot' for plotting, within a Ruby script. It requires the 'matplotlib/iruby' and 'pycall/import' gems. ```ruby require 'matplotlib/iruby' Matplotlib::IRuby.activate require 'pycall/import' include PyCall::Import pyimport 'numpy', as: 'np' plt = Matplotlib::Pyplot ``` -------------------------------- ### Activate Matplotlib Integration in IRuby Source: https://github.com/red-data-tools/pycall.rb/blob/master/examples/notebooks/iruby_integration.ipynb This code snippet demonstrates how to activate the integration between IRuby and Matplotlib using PyCall. It requires the `matplotlib/iruby` library and makes Python's `matplotlib.pyplot` functions available via the `Matplotlib::Pyplot` module. ```ruby require 'matplotlib/iruby' Matplotlib::IRuby.activate plt = Matplotlib::Pyplot ``` -------------------------------- ### Import Python Modules with PyCall.rb Source: https://github.com/red-data-tools/pycall.rb/blob/master/examples/notebooks/polar_axes.ipynb This snippet shows how to import Python modules like NumPy using PyCall.rb. It includes the necessary require statements and the `pyimport` command to make Python functions available in Ruby. No specific input or output is defined beyond the availability of the imported modules. ```ruby require 'matplotlib/iruby' Matplotlib::IRuby.activate plt = Matplotlib::Pyplot require 'pycall/import' include PyCall::Import pyimport :numpy, as: :np ``` -------------------------------- ### Create XKCD-style Plot using Matplotlib and NumPy in Ruby Source: https://github.com/red-data-tools/pycall.rb/blob/master/examples/notebooks/xkcd_style.ipynb This Ruby code, using PyCall to access Python's Matplotlib and NumPy, generates a plot inspired by the 'Stove Ownership' XKCD comic. It customizes plot aesthetics, adds annotations, and plots data. The function `plt.xkcd` is used to achieve the characteristic XKCD style. ```ruby plt.xkcd do # Based on "Stove Ownership" from XKCD by Randall Monroe # http://xkcd.com/418/ fig = plt.figure() ax = fig.add_axes([0.1, 0.2, 0.8, 0.7]) ax.spines['right'].set_color('none') ax.spines['top'].set_color('none') plt.xticks([]) plt.yticks([]) ax.set_ylim([-30, 10]) data = np.ones(100) data[70..-1] -= np.arange(30) plt.annotate( "THE DAY I REALIZED\nI COULD COOK BACON\nWHENEVER I WANTED", xy: [70, 1], arrowprops: { arrowstyle: '->' }, xytext: [15, -10] ) plt.plot(data) plt.xlabel('time') plt.ylabel('my overall health') fig.text( 0.5, 0.05, '"Stove Ownership" from xkcd by Randall Monroe', ha: 'center' ) # Based on "The Data So Far" from XKCD by Randall Monroe # http://xkcd.com/373/ fig = plt.figure() ax = fig.add_axes([0.1, 0.2, 0.8, 0.7]) ax.bar([0, 1], [0, 100], 0.25) ax.spines['right'].set_color('none') ax.spines['top'].set_color('none') ax.xaxis.set_ticks_position('bottom') ax.set_xticks([0, 1]) ax.set_xlim([-0.5, 1.5]) ax.set_ylim([0, 110]) ax.set_xticklabels(["CONFIRMED BY\nEXPERIMENT", "REFUTED BY\nEXPERIMENT"]) plt.yticks([]) plt.title("CLAIMS OF SUPERNATURAL POWERS") fig.text( 0.5, 0.05, '"The Data So Far" from xkcd by Randall Monroe', ha: 'center' ) end ``` -------------------------------- ### Releasing GVL for Long-Running Python Calls in Ruby Source: https://github.com/red-data-tools/pycall.rb/blob/master/README.md Shows how to use `PyCall.without_gvl` to release the Ruby Global Virtual Machine Lock (GVL) during the execution of long-running Python functions. This can improve concurrency by allowing other Ruby threads to run while Python code executes. ```ruby PyCall.without_gvl do # In this block, all Python function calls are performed without # the GVL acquisition. pyobj.long_running_function() end # Outside of PyCall.without_gvl block, # all Python function calls are performed with the GVL acquisition. pyobj.long_running_function() ``` -------------------------------- ### Create Polar Scatter Plot with Matplotlib and NumPy Source: https://github.com/red-data-tools/pycall.rb/blob/master/examples/notebooks/polar_axes.ipynb This snippet demonstrates creating a polar scatter plot using Matplotlib and NumPy via PyCall.rb. It generates random data for `r`, `theta`, `area`, and `colors` using NumPy, then creates a polar subplot and uses `ax.scatter` to plot the data with varying sizes, colors, and transparency. The output is a Matplotlib Figure object. ```ruby n = 150 r = 2 * np.random.rand(n) theta = 2 * np.pi * np.random.rand(n) area = 200 * r**2 colors = theta ax = plt.subplot(111, projection: 'polar') c = ax.scatter(theta, r, c: colors, s: area, cmap: 'hsv', alpha: 0.75) ``` -------------------------------- ### Accessing Python Object Attributes in Ruby Source: https://github.com/red-data-tools/pycall.rb/blob/master/README.md Explains how to access Python object attributes and methods in Ruby. Direct attribute access is mapped to Ruby's method calls. For callable attributes, `PyCall.getattr` is used to retrieve the object before calling. ```ruby # Calling a method on an object obj.meth(x, y, z: 1) # Getting a callable attribute callable_meth = PyCall.getattr(obj, :meth) ``` -------------------------------- ### Display GridSearchCV Results as Pandas DataFrame in Python Source: https://github.com/red-data-tools/pycall.rb/blob/master/examples/datascience_rb_20170519.ipynb This code converts the detailed cross-validation results stored in `svc.cv_results_` into a Pandas DataFrame for easier analysis and visualization. It drops the 'params' column to focus on performance metrics and other relevant information, making it convenient to inspect the outcomes of different hyperparameter settings. ```python pd.DataFrame(data=svc.cv_results_).drop(columns='params', axis=1) ``` -------------------------------- ### Generate Polar Bar Chart with Matplotlib and NumPy Source: https://github.com/red-data-tools/pycall.rb/blob/master/examples/notebooks/polar_axes.ipynb This code generates a polar bar chart using Matplotlib and NumPy through PyCall.rb. It creates arrays for `theta`, `radii`, and `width` using NumPy. A polar subplot is created, and `ax.bar` is used to draw the bars. The code also includes a loop to set the face color and alpha for each bar based on its radius, demonstrating dynamic plot customization. The output is a Matplotlib Figure object. ```ruby n = 20 theta = np.linspace(0.0, 2 * np.pi, n, endpoint: false) radii = 10 * np.random.rand(n) width = np.pi / 4 * np.random.rand(n) ax = plt.subplot(111, projection: 'polar') bars = ax.bar(theta, radii, width: width, bottom: 0.0) # TODO: I want to the following line in `PyCall.zip(radii, bars).each do |r, bar| radii.tolist.zip(PyCall::List.new(bars)) do |r, bar| # r = radii[i] bar.set_facecolor(plt.cm.viridis(r / 10.0)) bar.set_alpha(0.5) end ``` -------------------------------- ### Define Lorenz Attractor Equations Source: https://github.com/red-data-tools/pycall.rb/blob/master/examples/notebooks/lorenz_attractor.ipynb Defines the mathematical function representing the Lorenz system differential equations. It accepts state variables x, y, z and parameters s, r, b, returning the derivatives. ```ruby def lorenz(x, y, z, s: 10, r: 28, b: 2.667) x_dot = s * (y - x) y_dot = r * x - y - x * z z_dot = x * y - b * z [x_dot, y_dot, z_dot] end ``` -------------------------------- ### Retrieve Best Parameters from GridSearchCV in Python Source: https://github.com/red-data-tools/pycall.rb/blob/master/examples/datascience_rb_20170519.ipynb After fitting the GridSearchCV object, this code accesses the `best_params_` attribute to retrieve the hyperparameter combination that yielded the highest score during the cross-validation. This is crucial for understanding which parameters are optimal for the given dataset and model. ```python svc.best_params_ ``` -------------------------------- ### Generate Polar Line Plot with Matplotlib and NumPy Source: https://github.com/red-data-tools/pycall.rb/blob/master/examples/notebooks/polar_axes.ipynb This code generates a polar line plot using Matplotlib and NumPy through PyCall.rb. It first defines `r` and `theta` arrays using NumPy, then creates a polar subplot, plots the data, and customizes the plot's appearance with radial ticks and labels. The output is a Matplotlib Figure object. ```ruby r = np.arange(0, 2, 0.01) theta = 2 * np.pi * r ax = plt.subplot(111, projection: 'polar') ax.plot(theta, r) ax.set_rmax(2) ax.set_rticks([0.5, 1, 1.5, 2]) # less radial ticks ax.set_rlabel_position(-22.5) # get radial labels away from plotted line ax.grid(true) ax.set_title("A line plot on a polar axis", va: 'bottom') ``` -------------------------------- ### Create Multiple Plots in a Single Matplotlib Figure in IRuby Source: https://github.com/red-data-tools/pycall.rb/blob/master/examples/notebooks/iruby_integration.ipynb This snippet illustrates how to generate multiple line plots within the same Matplotlib figure using IRuby. It calls the `plot` method twice, overlaying the new plot on the existing one. ```ruby # Multiple plots in a figure plt.plot([1, 2, 3, 4, 5], [1, 2, 3, 1, 2]) plt.plot([10, 20, 30, 40, 50], [1, 2, 3, 1, 2]) ``` -------------------------------- ### Retrieve Best Score from GridSearchCV in Python Source: https://github.com/red-data-tools/pycall.rb/blob/master/examples/datascience_rb_20170519.ipynb This snippet retrieves the `best_score_` attribute from the fitted GridSearchCV object. This attribute represents the mean cross-validated score of the best_estimator found during the hyperparameter search, indicating the model's performance with the optimal parameters. ```python svc.best_score_ ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.