深度学习|keras编程基础

使用 tensorflow.keras 接口,组装神经网络层次,训练并预测

参考链接:https://blog.csdn.net/March_A/article/details/129240390?ops_request_misc=&request_id=&biz_id=102&utm_term=tensorflow.keras%20&utm_medium=distribute.pc_search_result.none-task-blog-2~all~sobaiduweb~default-3-129240390.142^v96^pc_search_result_base5&spm=1018.2226.3001.4449

  1. Keras 基础:
    Keras 是一个用 Python 编写的高级神经网络 API,它能够以TensorFlow ,CNTK 或者Theano作为后端运行。在Keras的官方github上写着"Deep Learning for humans",主要是因为它能简单快速的创建神经网络, 而不需要像Tensorflow一样考虑很多中间过程.

Keras说白了就是一个壳子, 需要结合TensorFlow, CNTK或者Theano等后端框架来运行.基于这些特点, Keras的入门非常简单. TensorFlow已经把keras集成了.

  1. 基本语言:

    代码运行调整到 CPU 或者 GPU:
bash 复制代码
cpu=tf.config.list_physical_devices("CPU")
tf.config.set_visible_devices(cpu)

模型显示: model.summary()

模型创建: model = Sequential()

添加卷积层: model.add(Dense(32, activation='relu', input_dim=100)) # 第一层需要 input_dim

添加dropout: model.add(Dropout(0.2))

添加第二次网络: model.add(Dense(512, activation='relu')) # 除了first, 其他层不要输入shape

添加输出层: model.add(Dense(num_classes, activation='softmax')) # last 通常使用softmax

TensorFlow 中,使用 model.compile 方法来选择优化器和损失函数:

optimizer: 优化器: 主要有: tf.train.AdamOptimizer , tf.train.RMSPropOptimizer , or tf.train.GradientDescentOptimizer .

loss: 损失函数: 主要有:mean square error (mse, 回归), categorical_crossentropy (多分类) , and binary_crossentropy (二分类).

metrics: 算法的评估标准, 一般分类用accuracy.

bash 复制代码
model.compile(loss='categorical_crossentropy',
optimizer='rmsprop',
metrics=['accuracy'])

模型训练:

bash 复制代码
model.fit(x_train, y_train, batch_size = 64, epochs = 20, validation_data = (x_test, y_test))    # 模型训练

模型评估:

bash 复制代码
score = model.evaluate(x_test, y_test, verbose=0)    两个返回值: [ 损失率 , 准确率 ]

大数据集处理:把大数据集数据变成dataset:

bash 复制代码
dataset = tf.data.Dataset.from_tensor_slices((data, labels))
指定每批数据大小: `dataset = dataset.batch(32).repeat()`
dataset 数据训练: `model.fit(dataset, epochs=10, steps_per_epoch=30)`

保存模型: model.save('my_model.h5')

加载模型: model = tf.keras.models.load_model('my_model.h5')

bash 复制代码
from keras.models import Sequential
from keras.layers import Dense, Activation
 
model = Sequenti([
    Dense(32, input_shape=(784,)),
    Activation('relu'),
    Dense(10),
    Activation('softmax'),
]al)
model.summary()

也可以简单的使用.add()方法将各层添加到模型中:

bash 复制代码
model = Sequential()
model.add(Dense(32, input_dim=784))
model.add(Activation('relu'))
model.summary()

手写数字识别问题 mnist 数据集

python 复制代码
from keras.layers import Input, Dense
from keras.models import Model
from keras.datasets import mnist
import tensorflow as tf
 
# 导入手写数字数据集
(x_train, y_train), (x_test, y_test) = mnist.load_data()#60000train ,10000test
# 对数据进行初步处理
x_train = x_train.reshape(60000, 784)
x_train = x_train.astype('float32')
x_train /= 255
# 将标记结果转化为独热编码
y_train = tf.keras.utils.to_categorical(y_train, num_classes=10)
# 这部分返回一个张量
inputs = Input(shape=(784))
# 层的实例是可调用的,它以张量为参数,并且返回一个张量
output_1 = Dense(64, activation='relu')(inputs)
output_2 = Dense(64, activation='relu')(output_1)
predictions = Dense(10, activation='softmax')(output_2)
 
# 这部分创建了一个包含输入层和三个全连接层的模型
model = Model(inputs=inputs, outputs=predictions)
model.compile(optimizer='rmsprop',
              loss='categorical_crossentropy',
              metrics=['accuracy'])
model.fit(x_train, y_train)  # 开始训练
相关推荐
kakaZhui4 分钟前
【llm对话系统】大模型源码分析之 LLaMA 位置编码 RoPE
人工智能·深度学习·chatgpt·aigc·llama
struggle20251 小时前
一个开源 GenBI AI 本地代理(确保本地数据安全),使数据驱动型团队能够与其数据进行互动,生成文本到 SQL、图表、电子表格、报告和 BI
人工智能·深度学习·目标检测·语言模型·自然语言处理·数据挖掘·集成学习
佛州小李哥1 小时前
通过亚马逊云科技Bedrock打造自定义AI智能体Agent(上)
人工智能·科技·ai·语言模型·云计算·aws·亚马逊云科技
云空2 小时前
《DeepSeek 网页/API 性能异常(DeepSeek Web/API Degraded Performance):网络安全日志》
运维·人工智能·web安全·网络安全·开源·网络攻击模型·安全威胁分析
AIGC大时代2 小时前
对比DeepSeek、ChatGPT和Kimi的学术写作关键词提取能力
论文阅读·人工智能·chatgpt·数据分析·prompt
山晨啊83 小时前
2025年美赛B题-结合Logistic阻滞增长模型和SIR传染病模型研究旅游可持续性-成品论文
人工智能·机器学习
一水鉴天4 小时前
为AI聊天工具添加一个知识系统 之77 详细设计之18 正则表达式 之5
人工智能·正则表达式
davenian4 小时前
DeepSeek-R1 论文. Reinforcement Learning 通过强化学习激励大型语言模型的推理能力
人工智能·深度学习·语言模型·deepseek
X.AI6664 小时前
【大模型LLM面试合集】大语言模型架构_llama系列模型
人工智能·语言模型·llama
CM莫问4 小时前
什么是门控循环单元?
人工智能·pytorch·python·rnn·深度学习·算法·gru