当前位置:网站首页>用tensorflow.keras模块化搭建神经网络模型
用tensorflow.keras模块化搭建神经网络模型
2022-08-09 06:56:00 【Anakin6174】
资料来源:北京大学 曹建教授的课程 人工智能实践:TensorFlow笔记
使用八股搭建神经网络
其中第三步使用Sequential只能搭建简易的全连接模型,如果是有跳转的卷积网络或者其他复杂设计的网络需要自己创建一个类来设计;
利用鸢尾花数据集来搭建网络举例:
# 用sequential或自己搭建model类
import tensorflow as tf
from sklearn import datasets
import numpy as np
x_train = datasets.load_iris().data
y_train = datasets.load_iris().target
np.random.seed(116)
np.random.shuffle(x_train)
np.random.seed(116)
np.random.shuffle(y_train)
tf.random.set_seed(116)
# ******************
# 可以自己搭建模型类,效果一样
# class IrisModel(Model):
# def __init__(self):
# super(IrisModel, self).__init__()
# self.d1 = Dense(3, activation='softmax', kernel_regularizer=tf.keras.regularizers.l2())
#
# def call(self, x):
# y = self.d1(x)
# return y
#
# model = IrisModel()
# ******************
model = tf.keras.models.Sequential([
tf.keras.layers.Dense(3, activation='softmax', kernel_regularizer=tf.keras.regularizers.l2())
])
model.compile(optimizer=tf.keras.optimizers.SGD(lr=0.1),
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False),
metrics=['sparse_categorical_accuracy'])
model.fit(x_train, y_train, batch_size=32, epochs=500, validation_split=0.2, validation_freq=20)
model.summary()
使用mnist数据集搭建神经网络
import tensorflow as tf
from tensorflow.keras.layers import Dense, Flatten
from tensorflow.keras import Model
mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
class MnistModel(Model):
def __init__(self):
super(MnistModel, self).__init__()
self.flatten = Flatten()
self.d1 = Dense(128, activation='relu')
self.d2 = Dense(10, activation='softmax')
def call(self, x):
x = self.flatten(x)
x = self.d1(x)
y = self.d2(x)
return y
model = MnistModel()
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False),
metrics=['sparse_categorical_accuracy'])
model.fit(x_train, y_train, batch_size=32, epochs=5, validation_data=(x_test, y_test), validation_freq=1)
model.summary()
边栏推荐
- RK3568商显版开源鸿蒙板卡产品解决方案
- 报错:FSADeprecationWarning: SQLALCHEMY_TRACK_MODIFICATIONS重大开销和将disab补充道
- INSTALL_RPATH and BUILD_RPATH problem in CMake
- 细谈VR全景:数字营销时代的宠儿
- 排序第四节——归并排序(附有自己的视频讲解)
- Import the pycharm environment package into another environment
- Integer 线程安全的
- Error: flask: TypeError: 'function' object is not iterable
- Simple to use Lambda expressions
- XxlJobConfig分布式定时器任务管理XxlJob配置类,替代
猜你喜欢
Inception V3 闭眼检测
排序第三节——交换排序(冒泡排序+快速排序+快排的优化)(5个视频讲解)
CMake中INSTALL_RPATH与BUILD_RPATH问题
【Oracle 11g】Redhat 6.5 安装 Oracle11g
jvm线程状态
XILINX K7 FPGA+RK3399 PCIE驱动调试
Output method of list string print(*a) print(““.join(str(c) for c in a) )
长沙学院2022暑假训练赛(一)六级阅读
字节跳动面试题之镜像二叉树2020
Error jinja2.exceptions.UndefinedError: 'form' is undefined
随机推荐
way of thinking problem-solving skills
failed (13: Permission denied) while connecting to upstream
Inception V3 Eye Closure Detection
Silently start over, the first page is also a new page
The JVM thread state
分布式事务的应用场景
线程的6种状态
子路由及路由出口配置
C language implements sequential stack and chain queue
Use of PlantUML plugin in idea
按图搜索1688商品接口(item_search_img-按图搜索1688商品(拍立淘接口)代码对接教程
shardingsphere数据分片配置项说明和示例
io.lettuce.core。RedisCommandTimeoutException命令超时
【sqlite3】sqlite3.OperationalError: table addresses has 7 columns but 6 values were supplied
字节跳动笔试题2020 (抖音电商)
排序第一节——插入排序(直接插入排序+希尔排序)(视频讲解26分钟)
XxlJobConfig distributed timer task management XxlJob configuration class, replace
排序第二节——选择排序(选择排序+堆排序)(两个视频讲解)
Distributed id generator implementation
ByteDance Written Exam 2020 (Douyin E-commerce)