神经网络保存-导入

保存

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]
相关推荐
深圳市青牛科技实业有限公司12 分钟前
【青牛科技】应用方案|D2587A高压大电流DC-DC
人工智能·科技·单片机·嵌入式硬件·机器人·安防监控
水豚AI课代表33 分钟前
分析报告、调研报告、工作方案等的提示词
大数据·人工智能·学习·chatgpt·aigc
几两春秋梦_33 分钟前
符号回归概念
人工智能·数据挖掘·回归
用户691581141651 小时前
Ascend Extension for PyTorch的源码解析
人工智能
Chef_Chen1 小时前
从0开始学习机器学习--Day13--神经网络如何处理复杂非线性函数
神经网络·学习·机器学习
用户691581141652 小时前
Ascend C的编程模型
人工智能
-Nemophilist-2 小时前
机器学习与深度学习-1-线性回归从零开始实现
深度学习·机器学习·线性回归
成富2 小时前
文本转SQL(Text-to-SQL),场景介绍与 Spring AI 实现
数据库·人工智能·sql·spring·oracle
CSDN云计算3 小时前
如何以开源加速AI企业落地,红帽带来新解法
人工智能·开源·openshift·红帽·instructlab
艾派森3 小时前
大数据分析案例-基于随机森林算法的智能手机价格预测模型
人工智能·python·随机森林·机器学习·数据挖掘