使用tensorflow实现对fashion mnist本地数据集的建模、训练、预测   

 以下内容均在jupyterlab中实现

## 1.添加提示
%config IPComplter.greedy=True
## 2.加载Fashion MNIST数据集
from tensorflow import keras
# fashion_mnist = keras.datasets.fashion_mnist
# (train_images, train_labels),(test_images, test_labels) = fashion_mnist.load_data()
## 加载本地
import numpy as np
import os
import gzip

def load_data(data_folder):
  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(os.path.join(data_folder,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)

(train_images, train_labels), (test_images, test_labels) = load_data('fashion')
## 3.建立三层神经元网络模型
import tensorflow as tf
model = keras.Sequential()
model.add(keras.layers.Flatten(input_shape=(28,28)))
model.add(keras.layers.Dense(128,activation=tf.nn.relu))
model.add(keras.layers.Dense(10,activation=tf.nn.softmax))
## 4.查看model的概述
model.summary()
## 5.对输入的数据正则化,使其映射到0,1之间+编译模型:包括三方面(优化函数optimizer、损失函数loss、显示精度metrics)
train_images_scaled = train_images/255
model.compile(optimizer=tf.optimizers.Adam(),loss=tf.losses.sparse_categorical_crossentropy,metrics=['accuracy'])
## 6.训练模型 fit函数包括 训练数据集images、训练集的标签tabels、训练的次数epochs=
model.fit(train_images_scaled,train_labels,epochs=5)
## 7.使用测试数据检测使用model.ecaluate() ,修改test_images的值,(接收的数据,原来数据的label)
test_images_scaled = test_images/255
model.evaluate(test_images_scaled,test_labels)
## 8.单体检测使用model.predict()
import numpy as np
predict = model.predict(test_images)
print(np.argmax(predict[0]))
print(test_labels[0])
## 9.查看test的第一张图片
import matplotlib.pyplot as plt
plt.imshow(test_images[0])

Tips:虽然成功了,但是我这里model.predict直接对所有的测试数据预测,使用predict[index]表示对应的预测结果,当我对test_images[0]/255 单独进行预测的时候会出错误,不知道咋回事小白求告知,万分感谢!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值