Ruby 为 Jupyter Notebook 设置 Ruby Kernel

rocLv · January 25, 2019 · 3659 hits

做数据科学离不开 Jupyter Notebook,但是显然 Jupyter Notebook 不单单是为了 Python 而设置(但是离开 Python 显然也很不方便)。

首先,我们需要安装 Jupyter,这里需要说明的是 python 有多种版本管理工具,做数据科学方面的话推荐conda, 如果喜欢 GUI 界面的话,可以选择Anaconda

安装好 Jupyter 以后,我们可以开始安装 Ruby Kernel。Ruby Kernel 用的是 IRuby

以 Mac 为例:

$ brew install rbenv automake gmp libtool wget
$ rvm install 2.4.1
$ rvm use 2.4.1

因为iruby已经很久没更新了,所以,最好直接使用默认的2.4.1的版本。在我的笔记本上,我装了2.5.3的 Ruby,但是然并卵。在运行 Jupyter 的时候总是提醒我找不到ruby-2.4.1

$  brew install zeromq
$ brew install czmq --HEAD
$ gem install cztop iruby

然后注册Ruby Kernel

$ iruby register --force

至此,如果顺利的话你启动 Jupyter Notebook 应该可以看到Ruby 2.4.1:

$ jupyter notebook

在新建 ipynb 文件的时候,选择 Ruby Kernel 则可以了。

设置完之后你肯定想是不是可以运行一下 pandas,numpy,matplotlib 之类的 python 数据科学常用的库,很幸运的是确实有人通过pycall打包了一下这几个 python 库。

你可以通过以下命令安装: $ gem install numpy pandas $ gem install --pre matplotlib

使用的时候,基本可以参照 python 的语法来写。

比如说我要在 Jupyter Notebook 里面画个图,为了让图直接的 Notebook 里面显示,我们需要:

require "matplotlib/pyplot"
require 'matplotlib/iruby'
Matplotlib::IRuby.activate

我们再来试试 Numpy (每次安装完 Gem 以后,需要重启一下 Jupyter)

x = Numpy.asarray([[1, 2, 3], [4, 5, 6]])
puts x
# [[1 2 3]
#  [4 5 6]]

puts x[1, 1..2]
# [5 6]

puts x.T
# [[1 4]
#  [2 5]
#  [3 6]]

puts x.dot x.T
# [[14 32]
#  [32 77]]

puts x.reshape([3, 2])
# [[1 2]
#  [3 4]
#  [5 6]]

PS:插入 cell 以后,按 Shift + Enter 可以直接运行 cell 中的代码。

当然了,很多 python 代码,都是把Numpy 简写为 np,在 Ruby 下当然也可以:

np = Numpy

因为,虽然 Ruby 中规定首字母大写的是常量,但是我们也确实可以这样使用:

因为,在 Ruby 中,当我们声明了一个 Module,Class 的时候,其实相当于给这个 Module,Class 起了一个名字而已。 所以,这样的用法是可以 的。

class A
   def self.foo
       p "foo"
    end
end

a = A
a.foo

=> foo

当然,最牛逼的是,你可以在 Jupyter 里面运行 Rails Console。

我们在 Rails App 根目录下面 启动 Jupyter notebook,然后在第一行引入 Rails App 的环境即可:

require "./config/environment"

然后你就可以像用 Rails Console 一样运行 Jupyter 了。

No Reply at the moment.
You need to Sign in before reply, if you don't have an account, please Sign up first.