In [ ]:
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
Note: これらのドキュメントは私たちTensorFlowコミュニティが翻訳したものです。コミュニティによる 翻訳はベストエフォートであるため、この翻訳が正確であることや英語の公式ドキュメントの 最新の状態を反映したものであることを保証することはできません。 この翻訳の品質を向上させるためのご意見をお持ちの方は、GitHubリポジトリtensorflow/docsにプルリクエストをお送りください。 コミュニティによる翻訳やレビューに参加していただける方は、 docs-ja@tensorflow.org メーリングリストにご連絡ください。
このチュートリアルでは、pandas のDataFrameをロードして、tf.data.Dataset にデータを読み込む例を示します。
このチュートリアルは、クリーブランドクリニック財団(the Cleveland Clinic Foundation for Heart Disease)から提供された、小さな データセット を使っています。このデータセット(CSV)には数百行のデータが含まれています。行は各患者を、列はさまざまな属性を表しています。
このデータを使って、患者が心臓病を罹患しているかどうかを判別予測することができます。なお、これは二値分類問題になります。
In [ ]:
import pandas as pd
import tensorflow as tf
heart データセットを含んだCSVをダウンロードします。
In [ ]:
csv_file = tf.keras.utils.get_file('heart.csv', 'https://storage.googleapis.com/applied-dl/heart.csv')
pandas を使ってCSVを読み込みます。
In [ ]:
df = pd.read_csv(csv_file)
In [ ]:
df.head()
In [ ]:
df.dtypes
dataframe 内で唯一の object 型である thal 列を離散値に変換します。
In [ ]:
df['thal'] = pd.Categorical(df['thal'])
df['thal'] = df.thal.cat.codes
In [ ]:
df.head()
tf.data.Dataset.from_tensor_slices メソッドを使って、pandas の dataframeから値を読み込みます。
tf.data.Dataset を使う利点は、シンプルに使えて、かつ、大変効率的なデータパイプラインを構築できることです。詳しくは loading data guide を参照してください。
In [ ]:
target = df.pop('target')
In [ ]:
dataset = tf.data.Dataset.from_tensor_slices((df.values, target.values))
In [ ]:
for feat, targ in dataset.take(5):
print ('Features: {}, Target: {}'.format(feat, targ))
pd.Series は __array__ プロトコルを実装しているため、np.array や tf.Tensor を使うところでは、だいたいどこでも使うことができます。
In [ ]:
tf.constant(df['thal'])
データをシャッフルしてバッチ処理を行います。
In [ ]:
train_dataset = dataset.shuffle(len(df)).batch(1)
In [ ]:
def get_compiled_model():
model = tf.keras.Sequential([
tf.keras.layers.Dense(10, activation='relu'),
tf.keras.layers.Dense(10, activation='relu'),
tf.keras.layers.Dense(1, activation='sigmoid')
])
model.compile(optimizer='adam',
loss='binary_crossentropy',
metrics=['accuracy'])
return model
In [ ]:
model = get_compiled_model()
model.fit(train_dataset, epochs=15)
モデルへの入力に辞書型データを渡すことは、 tf.keras.layers.Input におなじ型の辞書を作成し、何らかの前処理を適用して、functional api を使ってスタッキングすることと同様に、簡単に行うことができます。これを 特徴列 の替わりに使うことができます。
In [ ]:
inputs = {key: tf.keras.layers.Input(shape=(), name=key) for key in df.keys()}
x = tf.stack(list(inputs.values()), axis=-1)
x = tf.keras.layers.Dense(10, activation='relu')(x)
output = tf.keras.layers.Dense(1, activation='sigmoid')(x)
model_func = tf.keras.Model(inputs=inputs, outputs=output)
model_func.compile(optimizer='adam',
loss='binary_crossentropy',
metrics=['accuracy'])
tf.data を使うときに、pandas の DataFrame の列構造を保持する一番簡単な方法は、DataFrame を辞書型データに変換して、先頭を切り取ることです。
In [ ]:
dict_slices = tf.data.Dataset.from_tensor_slices((df.to_dict('list'), target.values)).batch(16)
In [ ]:
for dict_slice in dict_slices.take(1):
print (dict_slice)
In [ ]:
model_func.fit(dict_slices, epochs=15)