TensorFlow 基本应用的学习报告及课后习题

一、TensorFlow的基本用法学习报告

TensorFlow是一种较为完善的深度学习框架,支持所有流行编程语言开发,如:Python、C++等。此外,TensorTlow可在多种平台上工作,允许将模型部署到工业生产中,并易于使用。

在TensorFlow 2.x的基本用法中,介绍两种风格的代码,一种使用低阶API进行代码编写,一种使用高阶API进行代码编写,在网上的一些资料中,有时也会出现两种风格混合的代码编写方式。整体上,我们推荐使用TensorFlow中的高阶API-tf.keras进行代码编写·,但也需要读懂低阶API的代码。

1、TensorFlow中低阶API的使用

(1)TensorFlow常量使用:

import tensorflow as tf
#声明标量
t_1 = tf.constant(2)
t_2 = tf.constant(2)
#相加
t_add = tf.add(t_1,t_2)
#一个形如一行三列的常量向量
t_3 = tf.constant([4,3,2])
#定义一个形状为[M,M]的全0张量和全1张量
zeros = tf.zeros(shape=[3,3])
ones = tf.ones(shanpe=[3,3])

(2)TensorFlow变量:

在TensorFlow中,模型的权值和偏置常常定义为变量。变量在创建的时候,需要设定其某初始化方法:可以直接赋值,也可以使用初始化函数。

import tensorflow as tf
#直接赋值
bias1 = tf.Variable(2)
#通过initial_value显示的赋值初始化
bias = tf.Variable(initial_value=3.)

(3)张量属性:

TensorFlow程序使用tensor数据结构来代表所有的数据,计算图中,操作间传递的数据都是tensor。我们可以把张量看作是一个n维的数组或列表。在TensorFlow 2.x中,张量的形状、类型和数值可以通过shape、dtype、numpy()方法获得。

import tensorflow as tf
a = tf.constant([[1.0,2.0],[3.0,4.0]])
print(a.shape)
print(a.dtpye)
print(a.numpy())

(4)Tensor运算:

import tensorflow as tf
 
#0维张量相加
print(tf.ass(1,2))

#1维张量相加
print(tf.add([1,2],[3,4])

#矩阵相乘
print(tf.matmul([[1,2,3]],[[4],[5],[6]]))

#计算5的平方
print(tf.sqare(5))

#计算2的3次方
print(tf.pow(2,3))

#操作符重载
print(tf.square(2)+tf.square(3))

#计算数值的和
print(tf.reduce_sum([1,2,3]))

#计算均值
print(tf.reduce_mean([1,2,3]))

2、TensorFlow中高阶API的使用

(1)tf.keras构建模型

有“序贯式”和“函数式”两种方式构建

1)序贯式:

#序贯式方式一
model = tf.keras.Sequential
#创建一个全连接层,神经元个数为256,输入为781,激活函数为relu
model.add(tf.keras.layer.Dense(256,activation='relu',input_dim=784))
model.add(tf.keras.layer.Dense(128,activation='relu'))
model.add(tf.keras.layer.Dense(10,activation='softmax'))

#序贯式方式二
input_layer = tf.keras.layer.input(shape=(784,))
hid1_layer = tf.layers.Dense(256,activation='relu')
hid2_layer = tf.keras.layer.Dense(128,activation='relu'),
output_layers = tf.keras.layers.Dense(10,activation='sorftmax')
#将层的列表传给Sequential的构造函数
model = tf.keras.Sequential(layers=[input_layer,hit1_layer,hit2_layer,output_layer])

2)函数式:

#创建一个模型,包含一个输入层和三个全连接层
inputs = tf.keras.layers.input(shape=(4)
x = tf.keras.layers.Dense(32,activation='relu')(input)
x = tf.keras.layers.Dense(64,activation='relu')(x)
outputs=tf.keras.layer.Dense(3,activation='softmax')(x)
model = tf.keras.Modle(inputs=inputs,outputs=outputs)

(2)molel.compile编译模型                                       

tf.keras.model.compile 接受如下3个重要的参数。

optimizer:优化器,可从 tf.keras.optimizers 中选择。

loss:损失函数,可从 tf.keras.losses 中选择。

metrics:评估指标,可从 tf.keras.metrics 中选择。

 model.compile (
optimizer = tf.keras.optimizers.Adam(learning_rate=0.001),
loss = tf.keras.losses.sparse_categorical_crossentropy,
metrics = [tf.keras.metrics.sparse_categorical_accuracyl]
)


(3) model.fit 训练模型

 tf.keras.model.fit 接受如下5个重要的参数。

x :训练数据。

y :目标数据(数据标签)。

epochs :将训练数据迭代多少遍。

batch_size :批次的大小。

validation_data :验证数据,可用于在训练过程中监控模型的性能。

 model.fit(data_loader.train_data,
data_loader.train_label,
epochs = num_epochs,
batch_size = batch_size)

二、实验:

代码:

# -*- coding: utf-8 -*-
"""
Created on Sun Apr 17 21:23:45 2022

@author: 86133
"""

# -*- coding: utf-8 -*-
import tensorflow as tf
from tensorflow import keras
import numpy as np
import matplotlib.pyplot as plt
tf.compat.v1.disable_eager_execution()
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_labels
train_images.shape
len(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()
# 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()
#测试部分
img=test_images[1]
print(img.shape)
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])


import tensorflow as tf
sess = tf.compat.v1.Session()
a = tf.constant(1)
b = tf.constant(2) 
print(sess.run(a+b))


import tensorflow as tf
sess = tf.compat.v1.Session()
 
a = tf.constant(10)
b= tf.constant(12)
sess.run(a+b)



import tensorflow as tf

A = tf.constant([[1, 2], [3, 4]])
B = tf.constant([[5, 6], [7, 8]])
C = tf.matmul(A, B)

print(C)

结果:

TensorFlow 基本应用的学习报告及课后习题_第1张图片

 TensorFlow 基本应用的学习报告及课后习题_第2张图片

 TensorFlow 基本应用的学习报告及课后习题_第3张图片

 TensorFlow 基本应用的学习报告及课后习题_第4张图片

 TensorFlow 基本应用的学习报告及课后习题_第5张图片

三、课后作业:

(1)、

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

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

(2)、

把两个相乘的矩阵,相同位置的元素进行乘法运算,这个时候会得到一个新的矩阵(卷积是在作矩阵内积乘法,而不是矩阵乘法)。这个新矩阵的全部值会进行相加,然后会得到一个值,这个值才是卷积运算的结果。

(3)、

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

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

(4)、

局部响应归一化对于 ReLU 这种没有上限边界的激活函数会比较有用,因为它会从附近的
多个卷积核的响应中挑选比较大的反馈,但不适合 Sigmoid 这种有固定边界并且能抑制过大值的激活函数。

(5)、

当目标函数是取最小值时,通过该算法,就会不断迭代,朝着梯度下降的方向前进,不断的逼近最优值。

你可能感兴趣的:(人工智能)