神经网络保存-导入

保存

python 复制代码
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import gzip
# fashion_mnist=tf.keras.datasets.fashion_mnist
# (train_images,train_labels),(test_images,test_labels)=fashion_mnist.load_data()
 
#数据在个人资源里面,放到该文件目录中即可
def load_data():
#     dirname = os.path.join('datasets', 'fashion-mnist')
#     base = 'https://storage.googleapis.com/tensorflow/tf-ke ras-datasets/'
    files = [
      'train-labels-idx1-ubyte.gz', 'train-images-idx3-ubyte.gz',
      't10k-labels-idx1-ubyte.gz', 't10k-images-idx3-ubyte.gz'
    ]
 
    paths = []
    for fname in files:
        paths.append(fname)
 
    with gzip.open(paths[0], 'rb') as lbpath:
        y_train = np.frombuffer(lbpath.read(), np.uint8, offset=8)
 
    with gzip.open(paths[1], 'rb') as imgpath:
        x_train = np.frombuffer(
        imgpath.read(), np.uint8, offset=16).reshape(len(y_train), 28, 28)
 
    with gzip.open(paths[2], 'rb') as lbpath:
        y_test = np.frombuffer(lbpath.read(), np.uint8, offset=8)
 
    with gzip.open(paths[3], 'rb') as imgpath:
        x_test = np.frombuffer(
        imgpath.read(), np.uint8, offset=16).reshape(len(y_test), 28, 28)
 
    return (x_train, y_train), (x_test, y_test)
(x_train, y_train), (x_test, y_test)=load_data()

x_train=np.expand_dims(x_train,-1)

y_train_one_hot=tf.one_hot(y_train,10).numpy()
x_train=np.float32(x_train)

model=tf.keras.Sequential([
    tf.keras.layers.Conv2D(1,3,1),
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(256,activation="relu"),
    tf.keras.layers.Dense(128,activation="relu"),
    tf.keras.layers.Dense(64,activation="relu"),
    tf.keras.layers.Dense(32,activation="relu"),
    tf.keras.layers.Dense(10,activation="softmax")
])
 
model.build(input_shape=[None,28,28,1])
model.summary()
model.compile(optimizer=tf.keras.optimizers.Adam(),loss=tf.keras.losses.CategoricalCrossentropy(),metrics=[tf.keras.losses.CategoricalCrossentropy()])

import os
checkpoint_path="training_1/cp.ckpt"
cp_callback=tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_path,save_weights_only=True,verbose=1)


history=model.fit(x_train,y_train_one_hot,epochs=10,callbacks=[cp_callback])
LOSS=history.history["loss"]
plt.plot(LOSS)
plt.show()

导入

python 复制代码
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import gzip
# fashion_mnist=tf.keras.datasets.fashion_mnist
# (train_images,train_labels),(test_images,test_labels)=fashion_mnist.load_data()
 
#数据在个人资源里面,放到该文件目录中即可
def load_data():
#     dirname = os.path.join('datasets', 'fashion-mnist')
#     base = 'https://storage.googleapis.com/tensorflow/tf-ke ras-datasets/'
    files = [
      'train-labels-idx1-ubyte.gz', 'train-images-idx3-ubyte.gz',
      't10k-labels-idx1-ubyte.gz', 't10k-images-idx3-ubyte.gz'
    ]
 
    paths = []
    for fname in files:
        paths.append(fname)
 
    with gzip.open(paths[0], 'rb') as lbpath:
        y_train = np.frombuffer(lbpath.read(), np.uint8, offset=8)
 
    with gzip.open(paths[1], 'rb') as imgpath:
        x_train = np.frombuffer(
        imgpath.read(), np.uint8, offset=16).reshape(len(y_train), 28, 28)
 
    with gzip.open(paths[2], 'rb') as lbpath:
        y_test = np.frombuffer(lbpath.read(), np.uint8, offset=8)
 
    with gzip.open(paths[3], 'rb') as imgpath:
        x_test = np.frombuffer(
        imgpath.read(), np.uint8, offset=16).reshape(len(y_test), 28, 28)
 
    return (x_train, y_train), (x_test, y_test)
(x_train, y_train), (x_test, y_test)=load_data()

x_test=np.expand_dims(x_test,-1)
model=tf.keras.Sequential([
    tf.keras.layers.Conv2D(1,3,1),
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(256,activation="relu"),
    tf.keras.layers.Dense(128,activation="relu"),
    tf.keras.layers.Dense(64,activation="relu"),
    tf.keras.layers.Dense(32,activation="relu"),
    tf.keras.layers.Dense(10,activation="softmax")
])
model.build(input_shape=[None,28,28,1])
model.summary()
model.compile(optimizer=tf.keras.optimizers.Adam(),loss=tf.keras.losses.CategoricalCrossentropy(),metrics=[tf.keras.losses.CategoricalCrossentropy()])

checkpoint_path="training_1/cp.ckpt"
model.load_weights(checkpoint_path)

x_test=np.array(x_test,dtype=np.float32)
print(np.argmax(model.predict(x_test),axis=1))
print(y_test)
np.sum((y_test==np.argmax(model.predict(x_test),axis=1))*1)/y_test.shape[0]
相关推荐
innutritious19 分钟前
车辆重识别(2020NIPS去噪扩散概率模型)论文阅读2024/9/27
人工智能·深度学习·计算机视觉
醒了就刷牙1 小时前
56 门控循环单元(GRU)_by《李沐:动手学深度学习v2》pytorch版
pytorch·深度学习·gru
橙子小哥的代码世界1 小时前
【深度学习】05-RNN循环神经网络-02- RNN循环神经网络的发展历史与演化趋势/LSTM/GRU/Transformer
人工智能·pytorch·rnn·深度学习·神经网络·lstm·transformer
985小水博一枚呀2 小时前
【深度学习基础模型】神经图灵机(Neural Turing Machines, NTM)详细理解并附实现代码。
人工智能·python·rnn·深度学习·lstm·ntm
SEU-WYL3 小时前
基于深度学习的任务序列中的快速适应
人工智能·深度学习
OCR_wintone4213 小时前
中安未来 OCR—— 开启高效驾驶证识别新时代
人工智能·汽车·ocr
matlabgoodboy4 小时前
“图像识别技术:重塑生活与工作的未来”
大数据·人工智能·生活
最近好楠啊4 小时前
Pytorch实现RNN实验
人工智能·pytorch·rnn
OCR_wintone4214 小时前
中安未来 OCR—— 开启文字识别新时代
人工智能·深度学习·ocr
学步_技术4 小时前
自动驾驶系列—全面解析自动驾驶线控制动技术:智能驾驶的关键执行器
人工智能·机器学习·自动驾驶·线控系统·制动系统