Más contenido relacionado
La actualidad más candente (20)
Similar a 【LT版】Elixir入門「第7回:Python/KerasをElixirから繋いでアレコレする」 (20)
【LT版】Elixir入門「第7回:Python/KerasをElixirから繋いでアレコレする」
- 9. 8
2.Pythonを使えるようにする
Pythonのサンプルとして、ノイズ入りsin波のグラフ表示をします
以下で起動します
import numpy as np
def sin( x, T = 100 ):
return np.sin( 2.0 * np.pi * x / T )
def noisy_sin( T = 100, ampl = 0.05 ):
x = np.arange( 0, 2 * T + 1 )
noise = ampl * np.random.uniform( low = - 1.0, high = 1.0, size = len( x ) )
return sin( x ) + noise
def plot():
f = noisy_sin()
plt.figure()
plt.plot( range( 0, len( f ) ), f, color = "b", label = "sin" )
plt.legend()
plt.show()
py_sample.py
# pip install matplotlib
# python predict_sin.py
- 19. 18
4.ElixirからPythonを呼び出す
クラスを呼び出すこともできます
lib/pyex.ex
defmodule Pyex do
…
def value_receive( value ) do
{ :ok, py_exec } = :python.start( [ python_path: 'lib' ] )
result = :python.call( py_exec, :py_sample, :Sample, [] )
result = :python.call( py_exec, :py_sample, :"Sample.arrange", [ object, value ] )
IO.puts "received from python: #{result}"
end
end
…
def class Sample( object ):
def __init__( self ):
print( " on python: __init__()" )
self.message = "Hello "
def arrange( self, name ):
print( " on python: arrange()" )
return self.message + name.decode( "utf-8" )
py_sample.py
Elixirから渡した文字列は、
Pythonだと、bytes型で解釈
されるので、str型に変換する
クラスのインスタンスを生成
メソッド名をクラス名と共に指定 インスタンスを
第1引数に指定
引数を第2引数
以降に指定
- 25. 24
5.Kerasを使えるようにする
ノイズ入りサイン波を予測するKerasコードをPythonで組みます
predict_sin.py
import numpy as np
from keras.models import Sequential
from keras.layers import Dense, Activation
from keras.layers.recurrent import LSTM
from keras.optimizers import Adam
from keras.callbacks import EarlyStopping
def sin( x, T = 100 ):
return np.sin( 2.0 * np.pi * x / T )
def noisy_sin( T = 100, ampl = 0.05 ):
x = np.arange( 0, 2 * T + 1 )
noise = ampl * np.random.uniform( low = - 1.0, high = 1.0, size = len( x ) )
return sin( x ) + noise
def make_dataset( datas, n_prev = 100 ):
data = []
target = []
maxlen = 25
for i in range( len( datas ) - maxlen ):
data.append( datas[ i: i + maxlen ] )
target.append( datas[ i + maxlen ] )
re_data = np.array( data ).reshape( len( data ), maxlen, 1 )
re_target = np.array( target ).reshape( len( data ), 1 )
return re_data, re_target
…
- 26. 25
5.Kerasを使えるようにする
(続き) 学習モデルを構築し、学習させます
…
def predict():
f = noisy_sin()
g, h = make_dataset( f )
length_of_sequence = x.shape[ 1 ]
in_out_neurons = 1
n_hidden = 300
model = Sequential()
model.add( LSTM( n_hidden, batch_input_shape =
( None, length_of_sequence, in_out_neurons ), return_sequences = False ) )
model.add( Dense( in_out_neurons ) )
model.add( Activation( "linear" ) )
optimizer = Adam( lr = 0.001 )
model.compile( loss = "mean_squared_error", optimizer = optimizer )
early_stopping = EarlyStopping( monitor = "val_loss", mode = "min", patience = 20 )
model.fit( x, y,
batch_size = 300,
epochs = 100,
validation_split = 0.1,
callbacks = [ early_stopping ]
)
future_test = g[ 175 ].T
time_length = future_test.shape[ 1 ]
future_result = np.empty( ( 0 ) )
…
predict_sin.py
- 27. 26
5.Kerasを使えるようにする
(続き) 学習モデルで未来データを予測し、グラフ表示します
…
for step2 in range( 400 ):
test_data = np.reshape( future_test, ( 1, time_length, 1 ) )
batch_predict = model.predict( test_data )
future_test = np.delete( future_test, 0 )
future_test = np.append( future_test, batch_predict )
future_result = np.append( future_result, batch_predict )
predicted = model.predict( x )
plt.figure()
plt.plot( range( 0, len( f ) ), f, color = "b", label = "sin" )
plt.plot( range( 25, len( predicted ) + 25 ), predicted, color = "r", label = "predict" )
plt.plot( range( len( f ), len( future_result ) + len( f ) ), future_result, color = "g", label = "future" )
plt.legend()
plt.show()
predict()
predict_sin.py
- 38. 37
株式会社TechJIN
CTO when デジタルマーケッター
。 森 正和 = 。
{ XPer: 17, KernelHacker: 7 }
[ Elixir, ElixirScript, Elm, Keras ] |> 福岡信仰 |> 東京侵攻w
my favotite technology & implements.
Twitter
@piacere_ex
Qiita
@piacere
私をフォローいただいても
開催タイミング分かります