尝试执行model.save(save_path)
时出现错误。
我正在使用tensorflow 2.0 alpha
文件 “ /home/eugenekim/virtualenvs/ds-pip/local/lib/python3.6/site-packages/tensorflow/python/util/serialization.py”, 第69行,在get_json_type中 引发TypeError('Not JSON Serializable:',obj)TypeError:('Not JSON Serializable:', b'\ n \ x04Mean \ x12 \ x04Mean \ x1a“ item_1 / embedding_lookup / Identity_2 \ x1a \ x16Mean / reduction_indices * \ n \ n \ x04Tidx \ x12 \ x020 \ x03 * \ x0f \ n \ tkeep_dims \ x12 \ x02(\ x00 * \ x07 \ n \ x01T \ x12 \ x020 \ x01')
相关代码如下(我的最佳猜测)。 对于输入(这是ID列表),我将获得每个的嵌入并将其平均。我将它们作为连接图层的功能之一。
import copy
import tensorflow as tf
import pandas as pd
from tensorflow.keras.layers import Input, Embedding, concatenate, Dense, Flatten
from tensorflow import feature_column
from tensorflow.python.keras.engine import training_utils
def df_to_dataset(dataframe, shuffle=True, batch_size=32):
dataframe = dataframe.copy()
labels = dataframe.pop('target')
d = dict(dataframe)
ds = tf.data.Dataset.from_tensor_slices((d, labels))
if shuffle:
ds = ds.shuffle(buffer_size=len(dataframe))
ds = ds.batch(batch_size)
return ds
def get_model():
first_input = Input(shape = (1,), name='first_input')
second_input = Input(shape = (1,), name='second_input' )
embedding_layer = Embedding(input_dim=10, output_dim=3, input_length=1)
first_input_encoded = embedding_layer(first_input)
first_input_encoded = tf.keras.layers.Reshape((3,))(first_input_encoded)
selected = embedding_layer(second_input)
item_average = tf.reduce_mean(selected, axis=1, keepdims=True)
second_input_encoded = tf.keras.layers.Reshape((3,))(item_average)
o = concatenate([first_input_encoded, second_input_encoded])
o = Dense(1)(o)
inputs = [first_input, second_input]
model = tf.keras.models.Model(inputs=inputs, outputs=o)
return model
df = pd.DataFrame(
[[3,[4,2,3],5, 'boy', 0],
[2,[6,1,2],7, 'girl', 1]], columns=['first_input', 'second_input', 'child_month_young', 'child_gender_young', 'target'])
train_ds = df_to_dataset(df)
val_ds = df_to_dataset(df)
model = get_model()
model.compile(optimizer='adam',
loss='binary_crossentropy',
metrics=['accuracy'])
model.fit(
train_ds,
validation_data=val_ds,
epochs=1
)
print(model.summary())
# tf.keras.models.save_model(model, 'test.h5')
model.save('test.h5')