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 社区翻译了这些文档。因为社区翻译是尽力而为, 所以无法保证它们是最准确的,并且反映了最新的 官方英文文档。如果您有改进此翻译的建议, 请提交 pull request 到 tensorflow/docs GitHub 仓库。要志愿地撰写或者审核译文,请加入 docs-zh-cn@tensorflow.org Google Group。
本教程提供了如何将 pandas dataframes 加载到 tf.data.Dataset。
本教程使用了一个小型数据集,由克利夫兰诊所心脏病基金会(Cleveland Clinic Foundation for Heart Disease)提供. 此数据集中有几百行CSV。每行表示一个患者,每列表示一个属性(describe)。我们将使用这些信息来预测患者是否患有心脏病,这是一个二分类问题。
In [ ]:
!pip install tensorflow-gpu==2.0.0-rc1
import pandas as pd
import tensorflow as tf
下载包含心脏数据集的 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
将 thal 列(数据帧(dataframe)中的 object )转换为离散数值。
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 的其中一个优势是可以允许您写一些简单而又高效的数据管道(data pipelines)。从 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'])
随机读取(shuffle)并批量处理数据集。
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。 您可以使用它作为 feature columns 的替代方法。
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 一起使用时,保存 pd.DataFrame 列结构的最简单方法是将 pd.DataFrame 转换为 dict ,并对该字典进行切片。
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)