ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

TensorFlow读书笔记

2022-04-24 23:02:20  阅读:163  来源: 互联网

标签:... plt 读书笔记 predictions images tf test TensorFlow


TensorFlow读书笔记:

TensorFlow 程序通常被组织成一个构建阶段和一个执行阶段。 在构建阶段, op 的执行步骤 被描述成一个图。在执行阶段, 使用会话执行执行图中的 op。
  TensorFlow的名字中已经说明了它最为重要的两个特点:Tensor和Flow。其中Tensor意思是张量,可以被简单的理解为多维数组或者矩阵。Flow就是“流”的意思,直观的表达了张量之间通过计算相互转化的过程。

  在TensorFlow中,常量用tf.constant()来定义,变量用tf.Variable()来定义。这些常量、变量就是我们所说的张量。一个张量中主要包含三个部分:name(名字), shape(维度),type(类型)。我们在定义常量或者变量的时候,最好指定数据类型,类型不匹配会报错。用dtype=''来设置,主要的数据类型有14种:

实数:tf.float32, tf.float64
整数:tf.int8, tf.int16, tf.int32, tf.int64, tf.uint128
布尔型:tf.bool
复数:tf.complex64, tf.complex128

  在tensorflow中,变量在操作前必须初始化,而常量则不用。
  tensorflow中调用会话 Session 来启动图, 并调用 Session.run() 方法执行操作。为了便于使用诸如 IPython 之类的 Python 交互环境, 可以使用 InteractiveSession 代替 Session 类, 对于张量(主要指的是变量)可以使用 Tensor.eval() ,对于执行操作可以使用 Operation.run() 方法,代替 Session.run()。这样可以避免使用一个变量来持有会话。

代码实现如下:

# TensorFlow and tf.keras
import tensorflow as tf
from tensorflow import keras

# Helper libraries
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()

class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
               'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']

train_images.shape

len(train_labels)

train_labels

test_images.shape

len(test_labels)

plt.figure()
plt.imshow(train_images[0])
plt.colorbar()
plt.grid(False)
plt.show()

train_images = train_images / 255.0

test_images = test_images / 255.0

plt.figure(figsize=(10,10))
for i in range(25):
    plt.subplot(5,5,i+1)
    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()

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=tf.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)

probability_model = tf.keras.Sequential([model, 
                                         tf.keras.layers.Softmax()])

predictions = probability_model.predict(test_images)

predictions[0]

np.argmax(predictions[0])

test_labels[0]

def plot_image(i, predictions_array, true_label, img):
  predictions_array, true_label, img = predictions_array, 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, true_label[i]
  plt.grid(False)
  plt.xticks(range(10))
  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
plt.figure(figsize=(6,3))
plt.subplot(1,2,1)
plot_image(i, predictions[i], test_labels, test_images)
plt.subplot(1,2,2)
plot_value_array(i, predictions[i],  test_labels)
plt.show()

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

# Plot the first X test images, their predicted labels, and the true labels.
# Color correct predictions in blue and incorrect predictions in red.
num_rows = 5
num_cols = 3
num_images = num_rows*num_cols
plt.figure(figsize=(2*2*num_cols, 2*num_rows))
for i in range(num_images):
  plt.subplot(num_rows, 2*num_cols, 2*i+1)
  plot_image(i, predictions[i], test_labels, test_images)
  plt.subplot(num_rows, 2*num_cols, 2*i+2)
  plot_value_array(i, predictions[i], test_labels)
plt.tight_layout()
plt.show()

# Grab an image from the test dataset.
img = test_images[1]

print(img.shape)

# Add the image to a batch where it's the only member.
img = (np.expand_dims(img,0))

print(img.shape)

predictions_single = probability_model.predict(img)

print(predictions_single)

plot_value_array(1, predictions_single[0], test_labels)
_ = plt.xticks(range(10), class_names, rotation=45)

np.argmax(predictions_single[0])

 

 

 

 

 

 

第六章TensorFlow习题答案:

习题1.  卷积中的局部连接:层间神经只有局部范围内的连接,在这个范围内采用全连接的方式,超过这个范围的神经元则没有连接;连接与连接之间独立参数,相比于去全连接减少了感受域外的连接,有效减少参数规模。

            全连接:层间神经元完全连接,每个输出神经元可以获取到所有神经元的信息,有利于信息汇总,常置于网络末尾;连接与连接之间独立参数,大量的连接大大增加模型的参数规模。

 

习题2. 卷积过程是指用一个大小固定的卷积核按照一定步长扫描输入矩阵进行点阵运算。

 

习题3. 池化作用的操作就是缩小特征图的尺寸,减少计算量,同时使得同样大小的区域可以概括更加全局的信息。

           激活函数是用来加入非线性因素的,解决线性模型所不能解决的问题。

 

习题4. 局部响应归一化的作用是模仿了生物神经系统的“侧抑制”机制,对局部神经元的活动创建了竞争环境,使得其中响应比较大的值变得相对更大,并抑制其他反馈较小的神经元,增强了模型的泛化能力。

 

习题5. 

             1、先决条件: 确认优化模型的假设函数和损失函数。

    比如对于线性回归,假设函数表示为hθ(x1,x2,...xn)=θ0+θ1x1+...+θnxnhθ(x1,x2,...xn)=θ0+θ1x1+...+θnxn,其中θi(i=0,1,2...n)θi(i=0,1,2...n)为模型参数,xi(i=0,1,2...n)xi(i=0,1,2...n)为每个样本的n个特征值。我们增加一个特征x0=1x0=1,这样hθ(x0,x1,...xn)=∑ni=0θixi。

    同样是线性回归,对应于上面的假设函数,损失函数为:

    J(θ0,θ1...,θn)=12m∑mj=1(hθ(x(j)0,x(j)1,...x(j)n−yj)2         

    2、算法相关参数初始化:主要是初始化θ0,θ1...,θn,算法终止距离εε以及步长αα。在没有任何先验知识的时候,将所有θ0θ0初始化为0,将步长初始化为1,在调优的时候再优化。

    3、 算法过程:

      1)确定当前位置的损失函数的梯度,对于θiθi,其梯度表达式如下:

        ∂∂θiJ(θ0,θ1...,θn)∂∂θiJ(θ0,θ1...,θn)

      2)用步长乘以损失函数的梯度,得到当前位置下降的距离,即a∂∂θiJ(θ0,θ1...,θn)a∂∂θiJ(θ0,θ1...,θn)对应前面登山例子中的某一步。

      3)确定是否所有的θiθi,梯度下降的距离都小于εε,如果小于εε则算法终止,当前所有的θi(i=0,1,2...n)θi(i=0,1,2...n)即为最终结果。否则进入步骤4.

      4)更新所有的θθ,对于θiθi,其更新表达式如下。更新完毕后继续转入步骤1.

        J(θ0,θ1...,θn)=12m∑mj=1(hθ(x(j)0,x(j)1,...x(j)n)−yj)2J(θ0,θ1...,θn)=12m∑j=1m(hθ(x0(j),x1(j),...xn(j))−yj)2

      随机梯度下降(SGD)每次只从样本中选择1组数据进行梯度下降,这样经过足够多的迭代次数,SGD也可以发挥作用,但过程会非常杂乱。“随机”的含义是每次从全部数据中中随机抽取一个样本。

 

标签:...,plt,读书笔记,predictions,images,tf,test,TensorFlow
来源: https://www.cnblogs.com/xzfbky/p/16188166.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有