[ML][Tensorflow] 训练模型的基本步骤

[ML][Tensorflow] 训练模型的基本步骤,第1张

https://www.tensorflow.org/tutorials/keras/classification?hl=zh-cnhttps://www.tensorflow.org/tutorials/keras/classification?hl=zh-cn 

from MY import wrapper1

import tensorflow as tf
from tensorflow import keras
import numpy as np
import matplotlib.pyplot as plt

print(tf.__version__)

# 获取数据集,以便用作训练和验证
fashion_mnist = keras.datasets.fashion_mnist

# 从数据集里面获取训练数据和验证数据
(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()

# 规划神经网络
model = keras.Sequential([
    keras.layers.Flatten(input_shape=(28, 28)),
    keras.layers.Dense(128, activation='relu'),
    keras.layers.Dense(10)
])

# 为神经网络添加配套的 优化器 , 损失函数 和 指标
model.compile(optimizer='adam',
              loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),
              metrics=['accuracy'])

# 开始训练
model.fit(train_images, train_labels, epochs=10)

# 评估训练结果
test_loss, test_acc = model.evaluate(test_images,  test_labels, verbose=2)
print('\nTest accuracy:', test_acc)

# ============ 以上是生成模型的步骤,模型的训练和生成 同时需要 训练集 和 验证集,训练集用来形成模型,验证集用来矫正模型精准度。

# ============ 下面开始使用模型

# 基于之前生成的model , 再在后面添加一个 softmax 层,这个层是一个数据展示层,不会对整个模型产生任何影响,只是为了方便展示结果
probability_model = keras.Sequential([model,keras.layers.Softmax()])

# 使用模型开始预测某个图像(这里用test_images来作为入参)
predictions = probability_model.predict(test_images)

# 输出预测结果
print(predictions[0])



欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/2989957.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-09-23
下一篇 2022-09-23

发表评论

登录后才能评论

评论列表(0条)

保存