tensorflow keras API定义神经网络结构

Keras有三种API,分别是Sequential,functional,和SubclassingAPI,只介绍前两种。

一、Sequential API

# Define the inference model
model = tf.keras.Sequential()
model.add(tf.keras.layers.Dense(256, activation=tf.nn.tanh))
model.add(tf.keras.layers.Dense(128, activation=tf.nn.sigmoid))
model.add(tf.keras.layers.Dense(output_dim))
model.compile(loss=tf.keras.losses.mean_squared_error,
              optimizer='adam')

#compute
model.fit(x_train,y_train,epochs=100)
model.save('./saved_model/keras_function_approx')
y_train_ = model.predict(x_train)
y_pred_ = model.predict(x_test)

下载保存好的模型:

model = tf.keras.models.load_model('saved_model/keras_function_approx')

二、Functional API

将layer变成一个算子,tf.keras.layers.Dense(256,activation='tanh')相当于是(input_x)的算子

def neural_net(input_x):
    output_1 = tf.keras.layers.Dense(256,activation='tanh')(input_x)
    output_2 = tf.keras.layers.Dense(128,'sigmoid')(output_1)
    output_y = tf.keras.layers.Dense(output_dim)(output_2)
    return output_y
input_ = tf.keras.Input(shape=[1])
output_ = neural_net(input_)
model = tf.keras.Model(input_,output_)
model.compile(loss=tf.keras.losses.mean_squared_error,
              optimizer='adam')
#compute
model.fit(x_train,y_train,epochs=100)
model.save('./saved_model/keras_function_approx')
y_train_ = model.predict(x_train)
y_pred_ = model.predict(x_test)

三、Subclassing

用了类的思想

 

使用Keras后,可以使用model.summary()直接输出网络的情况

 

 

你可能感兴趣的:(小知识)