keras搭建神经网络的八股

  1. imoprt
  2. train,rest
  3. model
  4. compile
  5. checkpoint
  6. fit
  7. summary
  8. 参数提取/预测

下面是一个实现字母预测的实例

'''
[送入样本数,循环核时间展开步数,每个时间步输入特征的个数]

ht 记忆体状态信息
'''

from gc import callbacks
from pickletools import optimize
from tabnanny import check
from unittest import result
import numpy as np
from sklearn import metrics
from sklearn.manifold import trustworthiness
import tensorflow as tf
from tensorflow.keras.layers import Dense,SimpleRNN
# import matplotlib.pyplot as plt
import os

input_word = "abcde"
w_to_id = {'a': 0,'b': 1,'c': 2,'d': 3,'e': 4}
id_to_onehot = {0 : [1.,0.,0.,0.,0.],
                1 : [0.,1.,0.,0.,0.],
                2 : [0.,0.,1.,0.,0.],
                3 : [0.,0.,0.,1.,0.],
                4 : [0.,0.,0.,0.,1.]}

x_train = [id_to_onehot[w_to_id['a']],
            id_to_onehot[w_to_id['b']],
            id_to_onehot[w_to_id['c']],
            id_to_onehot[w_to_id['d']],
            id_to_onehot[w_to_id['e']]]
y_train = [w_to_id['b'],
            w_to_id['c'],
            w_to_id['d'],
            w_to_id['e'],
            w_to_id['a']
            ]

np.random.seed(9)
np.random.shuffle(x_train)
np.random.seed(9)
np.random.shuffle(y_train)
tf.random.set_seed(9)

# 改变形状,使输入满足要求
x_train = np.reshape(x_train,(len(x_train),1,5))
y_train = np.array(y_train)

model = tf.keras.Sequential([
    SimpleRNN(3),
    # y = softmax(ht * why + by)
    Dense(5,'softmax')
])


model.compile(optimizer=tf.keras.optimizers.Adam(0.01),
                loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits = False),
                metrics=['sparse_categorical_accuracy']
                )

#  checkpoint
checkpoint_save_path = "./checkpoint/rnn_onehot_lpre1.ckpt"

if os.path.exists(checkpoint_save_path + '.index'):
    print('---------------load the model---------------------')
    model.load_weights(checkpoint_save_path)

cp_callback = tf.keras.callbacks.ModelCheckpoint(filepath = checkpoint_save_path,
                                                save_weights_only = True,
                                                save_best_only=True,
                                                monitor = 'loss')

# 断点续训
history = model.fit(x_train,y_train,batch_size=32,epochs=100,callbacks=[cp_callback])

model.summary()

# 参数提取
file = open('./weights.txt','w')
for v in model.trainable_variables:
    file.write(str(v.name) + '\n')
    file.write(str(v.shape) + '\n')
    file.write(str(v.numpy()) + '\n')
file.close()


# 绘制曲线



# 字母预测
preNum = int(input("input the number"))

for i in range(preNum):
    alphabet1 = input("input test alphabet:")
    alphabet = [id_to_onehot[w_to_id[alphabet1]]]
    alphabet = np.reshape(alphabet,(1,1,5))
    result = model.predict([alphabet])
    pred = tf.argmax(result,axis=1)
    pred = int(pred)
    tf.print(alphabet1 + '->' + input_word[pred])





'''
循环计算过程
'''
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Keras是一个基于Python的深度学习库,提供了许多便捷的API用于神经网络搭建Keras框架的特点是高度模块化、易于扩展、支持GPU和CPU的混合计算、用户友好,可以方便的构建各种神经网络模型并进行训练和预测。 在Keras搭建神经网络,首先需要确定神经网络的模型。Keras支持多种模型构建方法,包括序列模型、函数式模型和子类化API等。 序列模型是最简单的一种,它是一个线性的神经网络模型,是多个网络层的线性堆叠,其中的每一层都是前一层的输出作为下一层的输入。可以用以下方式构建一个序列模型: ``` from keras.models import Sequential from keras.layers import Dense model = Sequential() model.add(Dense(units=32, activation='relu', input_dim=100)) model.add(Dense(units=10, activation='softmax')) ``` 函数式模型可以用于构建更复杂的模型,如多输入和多输出的神经网络。可以用以下方式构建一个函数式模型: ``` from keras.layers import Input, Dense from keras.models import Model # This returns a tensor inputs = Input(shape=(784,)) # a layer instance is callable on a tensor, and returns a tensor x = Dense(64, activation='relu')(inputs) x = Dense(64, activation='relu')(x) predictions = Dense(10, activation='softmax')(x) # This creates a model that includes # the Input layer and three Dense layers model = Model(inputs=inputs, outputs=predictions) model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy']) ``` 子类化API提供了更加灵活的构建方式,可以通过自定义网络层和模型的方式实现复杂的神经网络。可以用以下方式构建一个子类化API模型: ``` import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers class MyModel(keras.Model): def __init__(self): super(MyModel, self).__init__() self.dense1 = layers.Dense(64, activation='relu') self.dense2 = layers.Dense(64, activation='relu') self.dense3 = layers.Dense(10, activation='softmax') def call(self, inputs): x = self.dense1(inputs) x = self.dense2(x) x = self.dense3(x) return x model = MyModel() model.compile(optimizer=keras.optimizers.Adam(learning_rate=1e-3), loss=keras.losses.SparseCategoricalCrossentropy(), metrics=[keras.metrics.SparseCategoricalAccuracy()]) ``` 无论采用何种方式搭建神经网络,都需要进行模型的编译和训练。模型的编译需要指定优化器、损失函数和评估指标。模型的训练则需要指定训练集、验证集、批处理大小和训练轮数等参数。可以用以下方式训练和评估模型: ``` history = model.fit(x_train, y_train, batch_size=64, epochs=5, validation_data=(x_val, y_val)) test_scores = model.evaluate(x_test, y_test, verbose=2) print('Test loss:', test_scores[0]) print('Test accuracy:', test_scores[1]) ``` 以上是Keras搭建神经网络的基本流程,需要根据具体问题和数据集的不同进行调整和优化。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

强大的RGG

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值