Keras框架建立模型方法2——函数API

  • 张量作为参数进行操作
  • 层:作为函数进行调用
# coding: utf-8
from tensorflow.keras import Input, layers


input_tensor = Input(shape=(32, )) # 一个张量

dense = layers.Dense(32, activation='relu') # 一个层就是一个函数

output_tensor = dense(input_tensor) # 可以在一个张量上调用一个层,它会返回一个张量
  • API的例子
# coding: utf-8
from tensorflow.keras.models import Sequential, Model
from tensorflow.keras import layers, Input
import numpy as np


# -------------------------------sequential模型-------------------------------
seq_model = Sequential()
seq_model.add(layers.Dense(32, activation='relu', input_shape=(64, )))
seq_model.add(layers.Dense(32, activation='relu'))
seq_model.add(layers.Dense(10, activation='softmax'))

# --------------------------sequential模型与之对应的API-----------------------
input_tensor = Input(shape=(64, ))
x = layers.Dense(32, activation='relu')(input_tensor)
x = layers.Dense(32, activation='relu')(x)
output_tensor = layers.Dense(10, activation='softmax')(x)

# -----------------Model类将输入张量和输出张量转化为一个模型---------------------
model = Model(input_tensor, output_tensor)

model.summary()

# ---------------------------对模型进行编译-------------------------------------
model.compile(optimizer='rmsprop', loss='categorical_crossentropy')

# ----------------------生成训练的虚伪数据--------------------------------------
x_train = np.random.random((1000, 64))
y_train = np.random.random((1000, 10))

history = model.fit(x_train, y_train, batch_size=128, epochs=10) # 训练10轮次

score = model.evaluate(x_train, y_train) # 评估模型
print('\n', score)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值