神经网络保存-导入

保存

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]
相关推荐
galileo20163 分钟前
LLM与金融
人工智能
DREAM依旧19 分钟前
隐马尔科夫模型|前向算法|Viterbi 算法
人工智能
GocNeverGiveUp32 分钟前
机器学习2-NumPy
人工智能·机器学习·numpy
B站计算机毕业设计超人1 小时前
计算机毕业设计PySpark+Hadoop中国城市交通分析与预测 Python交通预测 Python交通可视化 客流量预测 交通大数据 机器学习 深度学习
大数据·人工智能·爬虫·python·机器学习·课程设计·数据可视化
学术头条2 小时前
清华、智谱团队:探索 RLHF 的 scaling laws
人工智能·深度学习·算法·机器学习·语言模型·计算语言学
18号房客2 小时前
一个简单的机器学习实战例程,使用Scikit-Learn库来完成一个常见的分类任务——**鸢尾花数据集(Iris Dataset)**的分类
人工智能·深度学习·神经网络·机器学习·语言模型·自然语言处理·sklearn
feifeikon2 小时前
机器学习DAY3 : 线性回归与最小二乘法与sklearn实现 (线性回归完)
人工智能·机器学习·线性回归
游客5202 小时前
opencv中的常用的100个API
图像处理·人工智能·python·opencv·计算机视觉
古希腊掌管学习的神2 小时前
[机器学习]sklearn入门指南(2)
人工智能·机器学习·sklearn
Ven%2 小时前
如何在防火墙上指定ip访问服务器上任何端口呢
linux·服务器·网络·深度学习·tcp/ip