下面的代码是我操作了一遍tensorflow的helloword教程后,写下的代码。相比教程,多加了些注释,以便更加了解函数的输入输出。
整个代码就是识别鞋子、上衣、裙子、裤子等。安装好tensorflow后就可以马上上手。我用的是spyder写的程序。

1.导入TensorFlow和tf.keras

#----1-------------
from future import absolute_import, division, print_function, unicode_literals

import tensorflow as tf
from tensorflow import keras

#导入辅助库

import numpy as np
import matplotlib.pyplot as plt

print(tf.version)

-------2.导入Fashion MNIST数据集-----------

fashion_mnist = keras.datasets.fashion_mnist

(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()

#由于类别名称不包含在数据集中,因此把他们存储在这里以便在绘制图像时使用:Pullover=套头毛衣; 套衫,Sneaker=运动鞋
class_names = [‘T-shirt/top’, ‘Trouser’, ‘Pullover’, ‘Dress’, ‘Coat’,
‘Sandal’, ‘Shirt’, ‘Sneaker’, ‘Bag’, ‘Ankle boot’]

-------3探索数据

#在训练网络之前必须对数据进行预处理。 如果您检查训练集中的第一个图像,您将看到像素值落在0到255的范围内:
plt.figure()
plt.imshow(train_images[0])
plt.colorbar()
plt.grid(False)
plt.show()

#在馈送到神经网络模型之前,我们将这些值缩放到0到1的范围。为此,我们将像素值值除以255。重要的是,对训练集和测试集要以相同的方式进行预处理:
train_images = train_images / 255.0
test_images = test_images / 255.0

#显示训练集中的前25个图像,并在每个图像下方显示类名。验证数据格式是否正确,我们是否已准备好构建和训练网络。
#plt.figure(figsize=(a, b), dpi=dpi).figsize 设置图形的大小,a 为图形的宽, b 为图形的高,单位为英寸
plt.figure(figsize=(10,10))
for i in range(25):
#subplot(m,n,p)是将多个图画到一个平面上的工具。其中,m表示是图排成m行,n表示图排成n列,也就是整个figure中有n个图是排成一行的,一共m行,如果m=2就是表示2行图。p表示图所在的位置,p=1表示从左到右从上到下的第一个位置。
plt.subplot(5,5,i+1)
# 显示x轴的刻标,不想显示ticks则可以可以传入空的参数
plt.xticks([])
plt.yticks([])
plt.grid(False)#就是是否显示网格线
plt.imshow(train_images[i], cmap=plt.cm.binary)
plt.xlabel(class_names[train_labels[i]])
plt.show()

-------4构建模型

#Relu激活函数(The Rectified Linear Unit)表达式为:f(x)=max(0,x)。
model = keras.Sequential([
keras.layers.Flatten(input_shape=(28, 28)),
keras.layers.Dense(128, activation=tf.nn.relu),
keras.layers.Dense(10, activation=tf.nn.softmax)
])

model.compile(optimizer=‘adam’,
loss=‘sparse_categorical_crossentropy’,
metrics=[‘accuracy’])
#训练模型
model.fit(train_images, train_labels, epochs=5)

#评估准确率
test_loss, test_acc = model.evaluate(test_images, test_labels)
print(‘Test accuracy:’, test_acc)

--------5.模型结果

#通过训练模型,我们可以使用它来预测某些图像。
predictions = model.predict(test_images)
#print(‘predictions[0]’,predictions[0])
np.argmax(predictions[0])

#正确的预测标签是蓝色的,不正确的预测标签是红色的。该数字给出了预测标签的百分比(满分100)。请注意,即使非常自信,也可能出错
def plot_image(i, predictions_array, true_label, img):
predictions_array, true_label, img = predictions_array[i], true_label[i], img[i]
plt.grid(False)
plt.xticks([])
plt.yticks([])

plt.imshow(img, cmap=plt.cm.binary)

predicted_label = np.argmax(predictions_array)
if predicted_label == true_label:
color = ‘blue’
else:
color = ‘red’

plt.xlabel("{} {:2.0f}% ({})".format(class_names[predicted_label],
100*np.max(predictions_array),
class_names[true_label]),
color=color)

def plot_value_array(i, predictions_array, true_label):
predictions_array, true_label = predictions_array[i], true_label[i]
plt.grid(False)
plt.xticks([])
plt.yticks([])
thisplot = plt.bar(range(10), predictions_array, color="#777777")
plt.ylim([0, 1])
predicted_label = np.argmax(predictions_array)

thisplot[predicted_label].set_color(‘red’)
thisplot[true_label].set_color(‘blue’)

i = 0
print(‘predictions[0]’,predictions[i])
plt.figure(figsize=(6,3))
plt.subplot(1,2,1)
plot_image(i, predictions, test_labels, test_images)
plt.subplot(1,2,2)
plot_value_array(i, predictions, test_labels)
plt.show()

i = 12
print(‘predictions[12]’,predictions[i])
plt.figure(figsize=(6,3))
plt.subplot(1,2,1)
plot_image(i, predictions, test_labels, test_images)
plt.subplot(1,2,2)
plot_value_array(i, predictions, test_labels)
plt.show()

#绘制前X个测试图像,预测标签和真实标签 # 以蓝色显示正确的预测,红色显示不正确的预测

num_rows = 5
num_cols = 3
num_images = num_rowsnum_cols
plt.figure(figsize=(2
2num_cols, 2num_rows))
for i in range(num_images):
plt.subplot(num_rows, 2num_cols, 2i+1)
plot_image(i, predictions, test_labels, test_images)
plt.subplot(num_rows, 2num_cols, 2i+2)
plot_value_array(i, predictions, test_labels)
plt.show()

第一个神经网络TensorFlow相关推荐

  1. tensorflow画损失函数的代码_使用TensorFlow编写您的第一个神经网络

    介绍 神经网络是受生物神经网络启发而产生的一套特殊的机器学习算法,它们彻底改变了机器学习.简单地说,它们是通用的函数近似,可以应用于几乎任何关于学习从输入到输出空间的复杂映射的机器学习问题. 神经网络 ...

  2. keras神经网络回归预测_如何使用Keras建立您的第一个神经网络来预测房价

    keras神经网络回归预测 by Joseph Lee Wei En 通过李维恩 一步一步的完整的初学者指南,可使用像Deep Learning专业版这样的几行代码来构建您的第一个神经网络! (A s ...

  3. 独家 | 教你用不到30行的Keras代码编写第一个神经网络(附代码教程)

    翻译:陈丹 校对:和中华 本文长度为3000字,建议阅读5分钟 本文为大家介绍了如何使用Keras来快速实现一个神经网络. 回忆起我第一次接触人工智能的时候,我清楚地记得有些概念看起来是多么令人畏惧. ...

  4. python视频 神经网络 Tensorflow

    python视频 神经网络 Tensorflow 模块 视频教程 (带源码) 所属网站分类: 资源下载 > python视频教程 作者:smile 链接:http://www.pythonhei ...

  5. 第一个神经网络代码分享

    第一个神经网络代码分享 1.数据集 数据集合是广告电视和报纸对销量的一些数据,为了方便大家熟悉神经网络的实现,这里可以复制. ,TV,radio,newspaper,sales 1,230.1,37. ...

  6. 第一章 神经网络如何工作(附Python神经网络编程.pdf)

    Python神经网络编程.pdf 链接: https://pan.baidu.com/s/1RkNfeNgT3Qtt_sEqRhw5Bg 提取码: 98ma 第一章 神经网络如何工作 神经网络的思考模 ...

  7. e智团队实验室项目-第一周-神经网络的学习

    e智团队实验室项目-第一周-神经网络的学习 张钊 *, 赵雅玲* , 李锦玉,迟梦瑶,贾小云,赵尉,潘玉,刘立赛,祝大双,李月,曹海艳, (淮北师范大学计算机科学与技术学院,淮北师范大学经济与管理学院 ...

  8. 用Tensorflow搭建第一个神经网络

    简述 https://blog.csdn.net/a19990412/article/details/82913189 根据上面链接中的前两个学习教程学习 其中Mofan大神的例子非常好,学到了很多 ...

  9. 【深度学习】我的第一个基于TensorFlow的卷积神经网络

    基于MNIST数据集实现简单的卷积神经网络,熟悉基于TensorFlow的CNN的流程和框架. #1.导入相关库 import numpy as np import tensorflow as tf ...

最新文章

  1. 输入一行字符,判断单词数
  2. 联想电脑怎么进入Android,联想电脑怎么连接手机
  3. adguard拦截规则存在哪里_AdGuard 过滤规则分享
  4. win7电脑磁盘文件以分组方式展现解决方案
  5. android token机制_对Android 中的 ANR 进行详解
  6. OPA 22 - sinor fake xml http request
  7. linux ucontext 类型,协程:posix::ucontext用户级线程实现原理分析 | WalkerTalking
  8. wkwebview 下移20像素_UITableView嵌套WKWebView的那些坑
  9. JAVA入门级教学之(逻辑(布尔)运算符)
  10. Python程序-离散和线性图形
  11. 装了python3但在cmd里不识别,Pip无法识别安装命令(Windows 7,Python 3.3)
  12. 如何固定电脑ip地址
  13. android:src app:srccompat,android – 数据绑定与srcCompat
  14. 交易系统开发(五)——华锐柜台简介
  15. 【时间序列分析】02. 线性平稳序列
  16. python抓包库_python抓包_python 抓包_python 抓包库 - 云+社区 - 腾讯云
  17. mongodb异常Prematurely reached end of stream原因分析
  18. 自动化系2023挑战杯预审相关资料
  19. 计算机开机密码有几成,电脑密码设置有哪些类型 电脑开机密码忘了怎么解锁...
  20. 怎么彻底关闭广告弹窗?

热门文章

  1. linux 安装搜狗输入法
  2. 关闭移动存储设备“自动播放”功能
  3. 外汇天眼:美联储认为美国房价有大跌的风险!
  4. 计算机开机看不到桌面图标,电脑开机后桌面图标都不见了怎么处理
  5. 使用OCT将office序列号封装到安装文件中
  6. 云中信息科技有限公司服务器,云中挂服务器
  7. 网络流 - 最大权闭合子图 [NOI2009]植物大战僵尸
  8. win server 2012 r2 版本
  9. win更新一直在100%不动,且重启无效的解决办法
  10. smack4.3.4