前回の記事のtf.kerasのクイックスタートでは、機能APIは、シーケンスモデルとは異なる外観を使用してネットワークを定義しているだけです。ただし、ネットワークはレイヤー間の接続においてより柔軟であるだけであり、残りの利点はありません。ネットワークモデルとフォワードパスプロセスを完全にカスタマイズする必要がある場合、それだけでは不十分です。
ここでは、カスタムモデルについて説明します。
カスタムModel
クラスをコピーするには、少なくとも2つのメソッドが必要です。
__init__()
call()
__init__()
我々が初期化する必要がニューラルネットワーク層、我々はcall()
前方に伝播すると理解することができ、これらのニューラルネットワーク層に接続されている方法を定義します。次にoutputs
、出力である1つを返す必要があります。
この記事では、虹彩分類のケースを変更することを検討してください。
では前の記事、私たちはこのようにそれを定義しました:
input_data = tf.keras.Input(shape=(len(x_data[0],)))
h_1 = tf.keras.layers.Dense(4, activation="relu")(input_data)
h_2 = tf.keras.layers.Dense(3, activation="softmax")(h_1)
同様の構造がここに保持されます:
import matplotlib.pyplot as plt
%matplotlib inline
import tensorflow as tf
from sklearn.datasets import load_iris
# 训练集和测试集的划分
from sklearn.model_selection import train_test_split
x_data = load_iris().data # 特征,【花萼长度,花萼宽度,花瓣长度,花瓣宽度】
y_data = load_iris().target # 分类
x_train, x_test, y_train, y_test = train_test_split(x_data, y_data, test_size=0.30, random_state=42)
class MyModel(tf.keras.Model):
def __init__(self, hidden_shape, output_shape):
super(MyModel, self).__init__()
self.layer1 = tf.keras.layers.Dense(hidden_shape, activation='relu')
self.layer2 = tf.keras.layers.Dense(output_shape, activation='softmax')
def call(self, inputs):
h1 = self.layer1(inputs)
out = self.layer2(h1)
return out
model = MyModel(hidden_shape=4, output_shape=3)
model.compile(optimizer=tf.keras.optimizers.Adam(),
loss=tf.keras.losses.sparse_categorical_crossentropy,
metrics=['accuracy'])
history = model.fit(x_train, y_train, epochs=300)
for key in history.history.keys():
plt.plot(history.epoch, history.history[key])