当前位置:   article > 正文

第二章:张量基本介绍+一个基本框架_现有的张量处理框架

现有的张量处理框架
  1. from keras.datasets import mnist
  2. (train_images, train_labels), (test_images, test_labels) = mnist.load_data()
  3. # 1.张量的三个属性
  4. print(train_images.ndim) # 轴的个数 3
  5. print(train_images.shape) # 形状 (60000,28,28)
  6. print(train_images.dtype) # 数据类型 unit8
  7. # 看看其中第4张图的样子
  8. digit = train_images[4]
  9. import matplotlib.pyplot as plt
  10. plt.imshow(digit, cmap = plt.cm.binary)
  11. plt.show()
  12. # 2.张量操作
  13. my_slice = train_images[10:100] # 沿着第一个轴选取第10~100个图片(不包括100)
  14. print(my_slice.shape) # (90,28,28)
  15. my_slice = train_images[10:100,:,:] # 等价操作
  16. my_slice = train_images[10:1000:28,0:28] # 等价操作
  17. # 3.一般来说数据张量的第一个轴(0轴)都是样本轴
  18. batch = train_images[:128] # 数据集的一个批量,大小为128
  19. # 3.现实世界的数据张量
  20. '''
  21. 1.向量数据:2D张量,形状为(samples,features)
  22. 2.时间序列数据或序列数据:3D张量,形状为(sample,timesteps,features)
  23. 3.图像:4D张量,形状为(sample,height,width,channels)or(sample,channels,height,width)
  24. 4.视频:5D张量,形状为(sample,frame,height,width,channels)or(samples,frames,channels,height,width)
  25. '''
  26. # 4.张量运算
  27. # 4.1 numpy中元素运算
  28. import numpy as np
  29. x = np.array([1,2,3])
  30. y = np.array([4,5,-4])
  31. z = x+y # 逐个元素相加
  32. print(z) # [5,7,-1]
  33. z = np.maximum(z,0) # 逐元素relu
  34. print(z) # [5,7,0]
  35. # 4.2 广播
  36. x = np.random.random((64, 3, 32, 10))
  37. y = np.random.random((32, 10))
  38. z = np.maximum(x, y) # y的(32,10)重复了(64,3)
  39. # z的输出为64,3,32,10的张量
  40. # 4.3张量点积
  41. x.shape[1] == y.shape[0]
  42. np.dot(x,y)
  43. # 4.4张量变形
  44. train_images = train_images.reshape((60000,28*28))
  45. x = np.zeros((300,20))
  46. x = np.transpose(x) # 变形之转置
  47. # 网络架构
  48. from keras import models
  49. from keras import layers
  50. network = models.Sequential()
  51. network.add(layers.Dense(512,activation='relu',input_shape = (28*28,))) # dense代表全连接层=512我理解的是输出是512神经元在这一层
  52. network.add(layers.Dense(10,activation = 'softmax')) # 输出10个神经元
  53. #编译:损失函数,优化器,评价指标
  54. network.compile(optimizer='rmsprop',loss='categorical_crossentropy',metrics=['accuracy'])
  55. #数据预处理 取值范围在0,1而且是float 32
  56. train_images = train_images.reshape((60000, 28 * 28))
  57. train_images = train_images.astype('float32') / 255
  58. test_images = test_images.reshape((10000, 28 * 28))
  59. test_images = test_images.astype('float32') / 255
  60. #准备标签
  61. from keras.utils import to_categorical
  62. train_labels = to_categorical(train_labels)
  63. test_labels = to_categorical(test_labels)
  64. #模型拟合(会显示之前定义的损失loss和metrics)
  65. network.fit(train_images, train_labels, epochs=5, batch_size=128)
  66. #模型测试
  67. test_loss, test_acc = network.evaluate(test_images, test_labels)
  68. print('test_acc:', test_acc)

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小舞很执着/article/detail/782847
推荐阅读
相关标签
  

闽ICP备14008679号