LoginSignup
25
25

More than 3 years have passed since last update.

Python vs Ruby 『ゼロから作るDeep Learning』 1章 sin関数とcos関数のグラフ

Last updated at Posted at 2017-05-09

概要

書籍『ゼロから作るDeep Learning ―Pythonで学ぶディープラーニングの理論と実装』1章のコードを参考に Python と Ruby でサイン・コサインのグラフを描くプログラムを書く。

環境構築

Python

書籍『ゼロから作るDeep Learning』では Anaconda ディストリビューションをインストールして環境構築していたが、ここでは pip で numpy と matplotlib をインストールするにとどめる。

今回の環境。

macOS Sierra + Homebrew + pyenv + Python 3.6.1

数値計算ライブラリの NumPy と、グラフ描画ライブラリの Matplotlib をインストールする。

$ pip install numpy matplotlib

Ruby

今回の環境。

macOS Sierra + Homebrew + rbenv + Ruby 2.4.1

多次元数値配列ライブラリの Numo::NArray と、グラフ描画ライブラリの Numo::Gnuplot をインストールする。

$ gem install numo-narray numo-gnuplot

Numo::Gnuplot が Gnuplot を使っているので Homebrew でインストールする。

$ brew install gnuplot

sin関数とcos関数のグラフを描くコード

Python

import numpy as np
import matplotlib
matplotlib.use("AGG") # 描画ライブラリにAGG(Anti-Grain Geometry)を使う
import matplotlib.pyplot as plt

# データの作成
x = np.arange(0, 6, 0.1) # 0から6まで0.1刻みで生成
y1 = np.sin(x)
y2 = np.cos(x)

# 数値データを確認用に出力
print("x:", *x)
print("y1:", *y1)
print("y2:", *y2)

# グラフの描画
plt.figure(figsize=(4, 3), dpi=160) # 画像サイズ
plt.plot(x, y1, label="sin")
plt.plot(x, y2, linestyle = "--", label="cos") # 破線で描画
plt.xlabel("x") # x軸のラベル
plt.ylabel("y") # y軸のラベル
plt.title("sin & cos") # タイトル
plt.legend() # 凡例
plt.savefig("python_graph.png")

Ruby

require 'numo/narray'
require 'numo/gnuplot'

# データの作成
x = Numo::DFloat.new(60).seq(0, 0.1) # 0から6まで0.1刻みで生成
y1 = Numo::DFloat::Math.sin(x)
y2 = Numo::DFloat::Math.cos(x)

# 数値データを確認用に出力
puts "x: #{x.to_a.join(' ')}"
puts "y1: #{y1.to_a.join(' ')}"
puts "y2: #{y2.to_a.join(' ')}"

# グラフの描画
g = Numo::gnuplot do
  set term: {png: {size: [640, 480]}} # 画像サイズ
  set output: 'ruby_graph.png'
  set title: 'sin \& cos' # タイトル
  set key: 'box left bottom'
  set offset: [0, 0, 0, 0]
  plot x, y1, {w: 'lines', lw: 3, title: 'sin'},
       x, y2, {w: 'lines', lw: 3, title: 'cos'}
end

出力された画像

Python

python_graph.png

Ruby

ruby_graph.png

参考資料

25
25
7

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
25
25