0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

TensorFlowでモデルの重み(Weights)を手動で設定してみる

Posted at

TensorFlowではモデルの重みは通常トレーニングによって学習させますが、手動で設定してたのでメモ。

Google Colaboratoryを使います。

モデルを作る

全結合層が1つだけのシンプルなモデルを定義します。

NoteBook
import tensorflow as tf
import numpy as np
from tensorflow import keras
from tensorflow.keras import layers

model = keras.Sequential()
model.add(layers.Dense(1,input_shape=(1,)))

model.compile('adam', 'categorical_crossentropy', metrics=['accuracy'])

重みを確認してみる

NoteBook
W = model.get_weights()
W
# 出力結果
# [array([[-0.56507134]], dtype=float32), array([0.], dtype=float32)]

重みは1つだけです。この時点ではランダムな値です。

重みを設定してみる

重みを設定してみます。

NoteBook
W[0][0][0] = 1.1
model.set_weights(W)

モデルを動作させてみる

モデルに0〜19の数字の配列を与えてみます。

NoteBook
x_train = np.arange(20).reshape((20,1))
model.predict(x_train)
# 出力結果
# array([[ 0.       ],
#        [ 1.1      ],
#        [ 2.2      ],
#        [ 3.3000002],
#        [ 4.4      ],
#        [ 5.5      ],
#        [ 6.6000004],
#        [ 7.7000003],
#        [ 8.8      ],
#        [ 9.900001 ],
#        [11.       ],
#        [12.1      ],
#        [13.200001 ],
#        [14.3      ],
#        [15.400001 ],
#        [16.5      ],
#        [17.6      ],
#        [18.7      ],
#        [19.800001 ],
#        [20.9      ]], dtype=float32)

0〜19の数字に重み1.1を乗じた数字になっていますね。

最後に

NoteではiOS開発、とくにCoreML、ARKit、Metalなどについて定期的に発信していますので。
https://note.com/tokyoyoshida

Twitterでも発信しています。
https://twitter.com/jugemjugemjugem

0
2
0

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
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?