聊城做网站的公司渠道,寺庙网站素材,应用中心下载,惠州做棋牌网站建设哪家好文章目录 数据导入和数据可视化数据集制作以及预处理模型结构低阶 API 构建模型中阶 API 构建模型高阶 API 构建模型保存和导入模型 这里以实际项目CIFAR-10为例#xff0c;分别使用低阶#xff0c;中阶#xff0c;高阶 API 搭建模型。 这里以CIFAR-10为数据集#xff0c;C… 文章目录 数据导入和数据可视化数据集制作以及预处理模型结构低阶 API 构建模型中阶 API 构建模型高阶 API 构建模型保存和导入模型 这里以实际项目CIFAR-10为例分别使用低阶中阶高阶 API 搭建模型。 这里以CIFAR-10为数据集CIFAR-10为小型数据集一共包含10个类别的 RGB 彩色图像飞机airplane、汽车automobile、鸟类bird、猫cat、鹿deer、狗dog、蛙类frog、马horse、船ship和卡车truck。图像的尺寸为 32×32像素3个通道 数据集中一共有 50000 张训练圄片和 10000 张测试图像。CIFAR-10数据集有3个版本这里使用Python版本。 数据导入和数据可视化
这里不用书中给的CIFAR-10数据直接使用TensorFlow自带的玩意导入数据可能需要魔法其实TensorFlow中的数据特别的经典。 接下来导入cifar10数据集并进行可视化展示
import matplotlib.pyplot as plt
import tensorflow as tf(x_train, y_train), (x_test, y_test) tf.keras.datasets.cifar10.load_data()
# x_train.shape, y_train.shape, x_test.shape, y_test.shape
# ((50000, 32, 32, 3), (50000, 1), (10000, 32, 32, 3), (10000, 1))index_name {0:airplane,1:automobile,2:bird,3:cat,4:deer,5:dog,6:frog,7:horse,8:ship,9:truck
}def plot_100_img(imgs, labels):fig plt.figure(figsize(20,20))for i in range(10):for j in range(10):plt.subplot(10,10,i*10j1)plt.imshow(imgs[i*10j])plt.title(index_name[labels[i*10j][0]])plt.axis(off)plt.show()plot_100_img(x_test[:100])数据集制作以及预处理
数据集预处理很简单就能实现直接一行代码。
train_data tf.data.Dataset.from_tensor_slices((x_train, y_train))# 提取出一行数据
# train_data.take(1).get_single_element()这里接着对数据预处理操作也很容易就能实现。
def process_data(img, label):img tf.cast(img, tf.float32) / 255.0return img, labeltrain_data train_data.map(process_data)# 提取出一行数据
# train_data.take(1).get_single_element()这里对数据还有一些存储和提取操作 dataset 中 shuffle()、repeat()、batch()、prefetch()等函数的主要功能如下。 1repeat(countNone) 表示重复此数据集 count 次实际上我们看到 repeat 往往是接在 shuffle 后面的。为何要这么做而不是反过来先 repeat 再 shuffle 呢 如果shuffle 在 repeat 之后epoch 与 epoch 之间的边界就会模糊出现未遍历完数据已经计算过的数据又出现的情况。 2shuffle(buffer_size, seedNone, reshuffle_each_iterationNone) 表示将数据打乱数值越大混乱程度越大。为了完全打乱buffer_size 应等于数据集的数量。 3batch(batch_size, drop_remainderFalse) 表示按照顺序取出 batch_size 大小数据最后一次输出可能小于batch 如果程序指定了每次必须输入进批次的大小那么应将drop_remainder 设置为 True 以防止产生较小的批次默认为 False。 4prefetch(buffer_size) 表示使用一个后台线程以及一个buffer来缓存batch提前为模型的执行程序准备好数据。一般来说buffer的大小应该至少和每一步训练消耗的batch数量一致也就是 GPU/TPU 的数量。我们也可以使用AUTOTUNE来设置。创建一个Dataset便可从该数据集中预提取元素注意examples.prefetch(2) 表示将预取2个元素2个示例而examples.batch(20).prefetch(2) 表示将预取2个元素2个批次每个批次有20个示例buffer_size 表示预提取时将缓冲的最大元素数返回 Dataset。 最后我们对数据进行一些缓存操作
learning_rate 0.0002
batch_size 64
training_steps 40000
display_step 1000AUTOTUNE tf.data.experimental.AUTOTUNE
train_data train_data.map(process_data).shuffle(5000).repeat(training_steps).batch(batch_size).prefetch(buffer_sizeAUTOTUNE)目前数据准备完毕
模型结构
模型的结构如下现在使用低阶中阶高阶 API 来构建这一个模型 低阶 API 构建模型
import matplotlib.pyplot as plt
import tensorflow as tf## 定义模型
class CustomModel(tf.Module):def __init__(self, nameNone):super(CustomModel, self).__init__(namename)self.w1 tf.Variable(tf.initializers.RandomNormal()([32*32*3, 256]))self.b1 tf.Variable(tf.initializers.RandomNormal()([256]))self.w2 tf.Variable(tf.initializers.RandomNormal()([256, 128]))self.b2 tf.Variable(tf.initializers.RandomNormal()([128]))self.w3 tf.Variable(tf.initializers.RandomNormal()([128, 64]))self.b3 tf.Variable(tf.initializers.RandomNormal()([64]))self.w4 tf.Variable(tf.initializers.RandomNormal()([64, 10]))self.b4 tf.Variable(tf.initializers.RandomNormal()([10]))def __call__(self, x):x tf.cast(x, tf.float32)x tf.reshape(x, [x.shape[0], -1])x tf.nn.relu(x self.w1 self.b1)x tf.nn.relu(x self.w2 self.b2)x tf.nn.relu(x self.w3 self.b3)x tf.nn.softmax(x self.w4 self.b4)return x
model CustomModel()## 定义损失
def compute_loss(y, y_pred):y_pred tf.clip_by_value(y_pred, 1e-9, 1.)loss tf.keras.losses.sparse_categorical_crossentropy(y, y_pred)return tf.reduce_mean(loss)## 定义优化器
optimizer tf.keras.optimizers.Adam(learning_rate0.0002)## 定义准确率
def compute_accuracy(y, y_pred):correct_pred tf.equal(tf.argmax(y_pred, axis1), tf.cast(tf.reshape(y, -1), tf.int64))correct_pred tf.cast(correct_pred, tf.float32)return tf.reduce_mean(correct_pred)## 定义一次epoch
def train_one_epoch(x, y):with tf.GradientTape() as tape:y_pred model(x)loss compute_loss(y, y_pred)accuracy compute_accuracy(y, y_pred)grads tape.gradient(loss, model.trainable_variables)optimizer.apply_gradients(zip(grads, model.trainable_variables))return loss.numpy(), accuracy.numpy()## 开始训练loss_list, acc_list [], []
for i, (batch_x, batch_y) in enumerate(train_data.take(1000), 1):loss, acc train_one_epoch(batch_x, batch_y)loss_list.append(loss)acc_list.append(acc)if i % 10 0:print(f第{i}次训练-, loss: ,loss, acc:, acc)中阶 API 构建模型
## 定义模型
class CustomModel(tf.Module):def __init__(self):super(CustomModel, self).__init__()self.flatten tf.keras.layers.Flatten()self.dense_1 tf.keras.layers.Dense(256, activationrelu)self.dense_2 tf.keras.layers.Dense(128, activationrelu)self.dense_3 tf.keras.layers.Dense(64, activationrelu)self.dense_4 tf.keras.layers.Dense(10, activationsoftmax)def __call__(self, x):x self.flatten(x)x self.dense_1(x)x self.dense_2(x)x self.dense_3(x)x self.dense_4(x)return xmodel CustomModel()## 定义损失以及准确率
compute_loss tf.keras.losses.SparseCategoricalCrossentropy()
train_loss tf.keras.metrics.Mean()
train_accuracy tf.keras.metrics.SparseCategoricalAccuracy()## 定义优化器
optimizer tf.keras.optimizers.Adam(learning_rate0.0002)## 定义一次epoch
def train_one_epoch(x, y):with tf.GradientTape() as tape:y_pred model(x)loss compute_loss(y, y_pred)grads tape.gradient(loss, model.trainable_variables)optimizer.apply_gradients(zip(grads, model.trainable_variables))train_loss(loss)train_accuracy(y, y_pred)## 开始训练
loss_list, accuracy_list [], []
for i, (batch_x, batch_y) in enumerate(train_data.take(1000), 1):train_one_epoch(batch_x, batch_y)loss_list.append(train_loss.result())accuracy_list.append(train_accuracy.result())if i % 10 0:print(f第{i}次训练 loss: {train_loss.result()} accuarcy: {train_accuracy.result()})高阶 API 构建模型
## 定义模型
model tf.keras.Sequential([tf.keras.layers.Input(shape[32,32,3]),tf.keras.layers.Flatten(),tf.keras.layers.Dense(256, activationrelu),tf.keras.layers.Dense(128, activationrelu),tf.keras.layers.Dense(64, activationrelu),tf.keras.layers.Dense(10, activationsoftmax),
])## 定义optimizerloss, accuracy
model.compile(optimizertf.keras.optimizers.Adam(learning_rate0.0002),loss tf.keras.losses.SparseCategoricalCrossentropy(),metrics[accuracy]
)## 开始训练
model.fit(train_data.take(10000))保存和导入模型
保存模型
tf.keras.models.save_model(model, model_folder)导入模型
model tf.keras.models.load_model(model_folder)
文章转载自: http://www.morning.bmssj.cn.gov.cn.bmssj.cn http://www.morning.rxnxl.cn.gov.cn.rxnxl.cn http://www.morning.yrgb.cn.gov.cn.yrgb.cn http://www.morning.rsbqq.cn.gov.cn.rsbqq.cn http://www.morning.ryyjw.cn.gov.cn.ryyjw.cn http://www.morning.qfkdt.cn.gov.cn.qfkdt.cn http://www.morning.hfxks.cn.gov.cn.hfxks.cn http://www.morning.mywnk.cn.gov.cn.mywnk.cn http://www.morning.gfhng.cn.gov.cn.gfhng.cn http://www.morning.xldpm.cn.gov.cn.xldpm.cn http://www.morning.rgqnt.cn.gov.cn.rgqnt.cn http://www.morning.wdpbq.cn.gov.cn.wdpbq.cn http://www.morning.zwgbz.cn.gov.cn.zwgbz.cn http://www.morning.ttrdr.cn.gov.cn.ttrdr.cn http://www.morning.hjlsll.com.gov.cn.hjlsll.com http://www.morning.fhhry.cn.gov.cn.fhhry.cn http://www.morning.lbfgq.cn.gov.cn.lbfgq.cn http://www.morning.rlcqx.cn.gov.cn.rlcqx.cn http://www.morning.tkfnp.cn.gov.cn.tkfnp.cn http://www.morning.mbqyl.cn.gov.cn.mbqyl.cn http://www.morning.swimstaracademy.cn.gov.cn.swimstaracademy.cn http://www.morning.bgbnc.cn.gov.cn.bgbnc.cn http://www.morning.wrbx.cn.gov.cn.wrbx.cn http://www.morning.rkrcd.cn.gov.cn.rkrcd.cn http://www.morning.yptwn.cn.gov.cn.yptwn.cn http://www.morning.wcrcy.cn.gov.cn.wcrcy.cn http://www.morning.jmlgk.cn.gov.cn.jmlgk.cn http://www.morning.zxqyd.cn.gov.cn.zxqyd.cn http://www.morning.wjplr.cn.gov.cn.wjplr.cn http://www.morning.pwlxy.cn.gov.cn.pwlxy.cn http://www.morning.nypsz.cn.gov.cn.nypsz.cn http://www.morning.phjny.cn.gov.cn.phjny.cn http://www.morning.nqrfd.cn.gov.cn.nqrfd.cn http://www.morning.c7496.cn.gov.cn.c7496.cn http://www.morning.jwcmq.cn.gov.cn.jwcmq.cn http://www.morning.ktnt.cn.gov.cn.ktnt.cn http://www.morning.dbnrl.cn.gov.cn.dbnrl.cn http://www.morning.lgxzj.cn.gov.cn.lgxzj.cn http://www.morning.dhnqt.cn.gov.cn.dhnqt.cn http://www.morning.ryztl.cn.gov.cn.ryztl.cn http://www.morning.hjssh.cn.gov.cn.hjssh.cn http://www.morning.qbjgw.cn.gov.cn.qbjgw.cn http://www.morning.pdghl.cn.gov.cn.pdghl.cn http://www.morning.qinhuangdjy.cn.gov.cn.qinhuangdjy.cn http://www.morning.wjjxr.cn.gov.cn.wjjxr.cn http://www.morning.qzpkr.cn.gov.cn.qzpkr.cn http://www.morning.rlxg.cn.gov.cn.rlxg.cn http://www.morning.rqsr.cn.gov.cn.rqsr.cn http://www.morning.qywfw.cn.gov.cn.qywfw.cn http://www.morning.dblgm.cn.gov.cn.dblgm.cn http://www.morning.xltwg.cn.gov.cn.xltwg.cn http://www.morning.zqbrw.cn.gov.cn.zqbrw.cn http://www.morning.jiuyungps.com.gov.cn.jiuyungps.com http://www.morning.xgmf.cn.gov.cn.xgmf.cn http://www.morning.rmltt.cn.gov.cn.rmltt.cn http://www.morning.lmfmd.cn.gov.cn.lmfmd.cn http://www.morning.jtsdk.cn.gov.cn.jtsdk.cn http://www.morning.kxymr.cn.gov.cn.kxymr.cn http://www.morning.bqdpy.cn.gov.cn.bqdpy.cn http://www.morning.khzml.cn.gov.cn.khzml.cn http://www.morning.mlwhd.cn.gov.cn.mlwhd.cn http://www.morning.jqlx.cn.gov.cn.jqlx.cn http://www.morning.bkqdg.cn.gov.cn.bkqdg.cn http://www.morning.zwyuan.com.gov.cn.zwyuan.com http://www.morning.skfkx.cn.gov.cn.skfkx.cn http://www.morning.qhczg.cn.gov.cn.qhczg.cn http://www.morning.sqhtg.cn.gov.cn.sqhtg.cn http://www.morning.nchlk.cn.gov.cn.nchlk.cn http://www.morning.frsbf.cn.gov.cn.frsbf.cn http://www.morning.wgkz.cn.gov.cn.wgkz.cn http://www.morning.fmqw.cn.gov.cn.fmqw.cn http://www.morning.ntqlz.cn.gov.cn.ntqlz.cn http://www.morning.pwxkn.cn.gov.cn.pwxkn.cn http://www.morning.lpzqd.cn.gov.cn.lpzqd.cn http://www.morning.gsrh.cn.gov.cn.gsrh.cn http://www.morning.bpmfq.cn.gov.cn.bpmfq.cn http://www.morning.nkqrq.cn.gov.cn.nkqrq.cn http://www.morning.qddtd.cn.gov.cn.qddtd.cn http://www.morning.rwqj.cn.gov.cn.rwqj.cn http://www.morning.dgsx.cn.gov.cn.dgsx.cn