ICode9

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

Tensorflow学习报告

2022-04-25 18:00:06  阅读:167  来源: 互联网

标签:plt 报告 predictions label 学习 print tf Tensorflow array


import tensorflow as tf
print(tf.__version__)
a = tf.constant(2.0)
print(a)

 

 

#声明一个标量常量
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,N]的全0张量和全1张量
zeros = tf.zeros(shape=[3,3])
ones = tf.ones(shape=[3,3])
#直接赋值初始化
import tensorflow as tf
#直接给变量赋值初始化
bias1 = tf.Variable(2)
#通过initial_value显示的赋值初始化
bias2 = tf.Variable(initial_value=3.)
#使用初始化函数初始化
a=tf.Variable(tf.zeros([2,1]))   #将形状为[2,1]张量初始化为0
b=tf.Variable(tf.zeros_like(a))  #返回一个和给定tensor同样shape的tensor,其中的元素全部置0
c=tf.Variable(tf.ones([2,1]))    #初始化为1
d=tf.Variable(tf.ones_like(a))   #将与a一个形状的张量初始化为1
e=tf.fill([2,3],4)                  #将指定形状的张量初始化为指定数值
import tensorflow as tf
a=tf.constant([[1.0,2.0],[3.0,4.0]])
print(a.shape)
print(a.dtype)
print(a.numpy())

 

 Tensorflow的基础运算操作

import tensorflow as tf
print(tf.add(1,2))                          #0维张量相加
print(tf.add([1,2],[3,4]))                 #一维张量相加
print(tf.matmul([[1,2,3]],[[4],[5],[6]]))  #矩阵相乘
print(tf.square(5))                        #计算5的平方
print(tf.pow(2,3))                         #计算2的3次方
print(tf.square(2)+tf.square(3))           #也支持操作符重载
print(tf.reduce_sum([1,2,3]))              #计算数值的和
print(tf.reduce_mean([1,2,3]))             #计算均值

 

 

模型搭建时常用的Tensor操作
(1)取最大索引:tf.argmax

 

 (2)扩张维度:tf.expand_dims

 

 (3)张量拼接:tf.concat

x=[[1,2,3],[4,5,61],[7,8,9]]
y=[[2,3,4],[5,6,7],[8,9,10]]
z1=tf.concat([x,y],axis=0)   #按照维度0拼接
z2=tf.concat([x,y],axis=1)   #按照维度1拼接
print(z1,z2)

 

 (4)形状变换:tf.reshape

 课后作业

import tensorflow as tf
from tensorflow import keras

import numpy as np
import matplotlib.pyplot as plt

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)

 

 

 

 

#模型对于全部 10 个类的预测
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()

 

标签:plt,报告,predictions,label,学习,print,tf,Tensorflow,array
来源: https://www.cnblogs.com/pcr-2020310143107/p/16191338.html

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

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

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

ICode9版权所有