ICode9

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

Tensorflow学习报告

2022-04-25 00:34:48  阅读:216  来源: 互联网

标签:layers plt keras 报告 predictions 学习 test tf Tensorflow


# -*- coding: utf-8 -*-
"""
Created on Mon Apr 11 23:34:27 2022

@author: Binnie
"""

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()
fashion_mnist = keras.datasets.fashion_mnist

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


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)

np.argmax(predictions[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])

运行结果:

 

 

 

 

 

 

 

 

 

第五章课后习题:

(1)Tensorflow和Pytorch

(2)可以直接赋值,也可以使用初始化函数

import tensorflow as tf

bias1=tf.Variable(2)

bias2=tf.Variable(initial_value=3.)

 

还有其他更加复杂的初始化方法 如:tf.zeros\tf.zeros_like\tf.ones_like\tf.random.truncated_normal等等

tf.random.truncated_normal和tf.zeros是常常用来进行权值和偏置的初始化方法

(3)序贯式、函数式

 

#序贯式1

import tensorflow as tf

model = tf.keras.Sequential()

 

#创建一个全连接层,神经元个数为256,输入为784,激活函数为relu

model.add(tf.keras.layers.Dense(256, activation='relu', input_dim=784))
model.add(tf.keras.layers.Dense(128, activation='relu'))
model.add(tf.keras.layers.Dense(10, activation='softmax'))

 

#序贯式2

import tensorflow as tf

imput_layer = tf.keras.layers.Input(shape=(784,))
hid1_layer = tf.keras.layers.Dense(256, activation='relu')
hid2_layer = tf.keras.layers.Dense(128, activation='relu')
output_layers = tf.keras.layers.Dense(10, activation='softmax') #将层的列表传给Sequential的构造函数
model = tf.keras.Sequential(layers=[imput_layer, hid1_layer, hid2_layer, output_layers])

 

 

#函数式

import tensorflow as tf

 


#创建一个模型,包含一个输入层和三个全连接层

inputs = tf.keras.layers.Input(shape=(4))
x=tf.keras.layers.Dense(32,activation='relu')(inputs)
x=tf.keras.layers.Dense(64,activation='relu')(x)
outputs=tf.keras.layers.Dense(3,activation='softmax')(x)
model=tf.keras.Model(inputs=inputs,outputs =outputs)

 

 (4)

import torch
data=torch.rand(5,3)
print(data)

运行结果:

 

 

 

 (5)Keras、Caffe、MXNet、Sonnet、Deeplearning4j

第六章课后习题:

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

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

(2)利用快速傅里叶变换把图片和卷积核变换到频域,频域把两者相乘,把结果利用傅里叶逆变换得到特征图。

(3)池化操作的作用:对输入的特征图进行压缩,一方面使特征图变小,简化网络计算复杂度;一方面进行特征压缩,提取主要特征。

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

(4)  消除数据之间的量纲差异,便于数据利用与快速计算。

(5) 寻找损失函数的最低点,就像我们在山谷里行走,希望找到山谷里最低的地方。那么如何寻找损失函数的最低点呢?在这里,我们使用了微积分里导数,通过求出函数导数的值,从而找到函数下降的方向或者是最低点(极值点)。损失函数里一般有两种参数,一种是控制输入信号量的权重(Weight, 简称  ),另一种是调整函数与真实值距离的偏差(Bias,简称  )。我们所要做的工作,就是通过梯度下降方法,不断地调整权重  和偏差b,使得损失函数的值变得越来越小。而随机梯度下降算法只随机抽取一个样本进行梯度计算。

学号:2020310143041

昵称:Binnie

标签:layers,plt,keras,报告,predictions,学习,test,tf,Tensorflow
来源: https://www.cnblogs.com/Binnie/p/16188437.html

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

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

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

ICode9版权所有