首页 > 其他分享 >TensorFlow2.0(一)

TensorFlow2.0(一)

时间:2022-10-11 11:24:21浏览次数:60  
标签:plt predictions label TensorFlow2.0 images tf test

本文简单实现,模型训练  Softmax分类器操作

参照官网图像分类:基本分类:对服装图像进行分类  |  TensorFlow Core (google.cn)

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
#加载数据
fashion_mnist=tf.keras.datasets.fashion_mnist
(train_images,train_labels),(test_images,test_labels)=fashion_mnist.load_data()
class_name=['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
               'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
print(train_images.shape)
#测试集预处理,像素值0-255映射到0-1
train_images=train_images/255.0
test_images=test_images/255.0
#构建模型,设置层
model=tf.keras.Sequential([tf.keras.layers.Flatten(input_shape=(28,28)),#将图像格式二维数组转换成一维数组
                           tf.keras.layers.Dense(128,activation='relu'),#第一个Dense层有128个节点,全链接层
                           tf.keras.layers.Dense(10)])#返回长度为10的logits数组,每个节点包含一个得分,表示当前图像属于10个类中的哪一类
#tf.keras.Sequential()创建顺序模型,model.layers():访问涂层   详见官方api  https://tensorflow.google.cn/guide/keras/sequential_model
#构建模型,编译模型
model.compile(optimizer='adam',#优化器
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),#损失函数
              metrics=['accuracy'])#培训和测试期间模型评估指标列表
#训练模型,
model.fit(train_images,train_labels,epochs=18)#该方法将模型与训练数据进行拟合

#评估准确率
test_loss,test_acc=model.evaluate(test_images,test_labels,verbose=2)#比较模型在测试数据集上的表现
#test_loss:测试损失值#   test_acc:测试结果准确性
#verbose:测试信息复杂程度,0 1 2三个取值
print('\nTest accuracy',test_acc)

#对未知图片进行分类
#预测
#Softmax层(回归分类器)
probablility_model=tf.keras.Sequential([model,
                                      tf.keras.layers.Softmax()])

#模型预测
predictions=probablility_model.predict(test_images)
#np.argmax(predictions[0])#对模型预测得到10个特征值,取最大值
class_names=predictions
#plt.imshow(test_images)
#绘制图表
def plot_image(i, predictions_array, true_label, img):
  true_label, img = 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):
  true_label = 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')



#验证预测结果
def test_result():
    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()
#使用训练好的模型,对单个图像进行预测
img=test_images[1]
print(img.shape)
img=(np.expand_dims(img,0))
print(img.shape)
predictions_single=probablility_model.predict(img)
print(predictions_single)
plot_value_array(1,predictions_single[0],test_labels)
#_=plt.xticks(range(10),class_names,rotation=45)
plt.show()

 

标签:plt,predictions,label,TensorFlow2.0,images,tf,test
From: https://www.cnblogs.com/Ms-wang/p/16778582.html

相关文章

  • Tensorflow2.0-随笔笔记-基础
    创建张量tf.convert_to_tensor函数In[22]:tf.convert_to_tensor([1,2.])#从列表创建张量Out[22]:<tf.Tensor:id=86,shape=(2,),dtype=float32,numpy=array([1......