吴恩达Tensorflow2.0实践第一课笔记

重要链接

吴恩达Tensorflow2.0实践第一课视频
课程示例程序代码
keras中文文档

5/15/20(1.1~2.4)

python复习

python快速教程

Hello World!

预测一次函数K值
github链接

import tensorflow as tf
import numpy as np
from tensorflow import keras

model = tf.keras.Sequential([keras.layers.Dense(units=1, input_shape=[1])])
model.compile(optimizer='sgd', loss='mean_squared_error')

xs = np.array([-1.0,  0.0, 1.0, 2.0, 3.0, 4.0], dtype=float)
ys = np.array([-3.0, -1.0, 1.0, 3.0, 5.0, 7.0], dtype=float)

model.fit(xs, ys, epochs=500)

print(model.predict([10.0]))

解读
(1)keras.Sequential构建模型。
(2)keras.layers.Dense方法是Keras定义网络层的基本方法。
(3)keras.compile编译模型 。
(4)keras.fit训练。
(5)keras.predict预测。

5/16/20 (2.5~4.8)

计算机视觉样例

github链接

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt

mnist=tf.keras.datasets.fashion_mnist
(traning_images,traning_label),(test_images,test_label)=mnist.load_data()
np.set_printoptions(linewidth=200)
plt.imshow(traning_images[0])
print(traning_images[0])
print(traning_label[0])

model=tf.keras.models.Sequential([tf.keras.layers.Flatten(),
                                  tf.keras.layers.Dense(128,activation=tf.nn.relu),
                                  tf.keras.layers.Dense(10,activation=tf.nn.softmax)])

model.compile(optimizer=tf.optimizers.Adam(),
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])
model.fit(traning_images,traning_label,epochs=5)

model.evaluate(test_images,test_label)

这里会遇到的问题:mnist数据无法加载或加载错误的解决办法
昨天已经对函数功能做了基本的阐述。

Keras建立模型的详细解释

今天进行进一步解释:
Keras有两种不同的构建模型的方法:
1. Sequential models
2. Functional API

现在我们只使用Squential。对于该模型
第一步确定模型结构:可使用

model = Sequential()
model.add(Conv2D(64, (3, 3), activation='relu'))

可以一层一层添加。也可以如上实例程序采用元组直接添加

有五种层

  1. 卷积层
model.add(Conv2D(64, (3, 3), activation='relu'))
  1. 最大池化层
model.add(MaxPooling2D(pool_size=(2, 2)))
  1. 全连接层
model.add(Dense(256, activation='relu'))
  1. dropout
model.add(Dropout(0.5))
  1. Flattening layer(展平层)
model.add(Flatten())

activation是激活函数。

mnist程序输入层采用扁平层,中间和输出层采用全连接层。

第二步compile进行模型的编译

  1. optimizer是优化器,即优化的方法。优化器官方文档
  2. loss损失函数。即和标准数据的误差计算方法。损失函数官方文档
  3. metrics评价函数。评价函数用于评估当前训练模型的性能。评估标准官方文档

第三步训练
fit函数传入数据和训练次数

第四步评价模型

mnist示例程序最后结果如下
在这里插入图片描述

回调函数

class myCallback(tf.keras.callbacks.Callback):
  def on_epoch_end(self, epoch, logs={}):
    if(logs.get('accuracy')>0.6):
      print("\nReached 60% accuracy so cancelling training!")
      self.model.stop_training = True

在loss值小于设定值的时候,结束训练。
如下,增加了callbacks的mnist示例程序

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
class myCallback(tf.keras.callbacks.Callback):
  def on_epoch_end(self, epoch, logs={}):
    if(logs.get('accuracy')>0.6):
      print("\nReached 60% accuracy so cancelling training!")
      self.model.stop_training = True
callbacks=myCallback()           
mnist=tf.keras.datasets.fashion_mnist
(traning_images,traning_label),(test_images,test_label)=mnist.load_data()
np.set_printoptions(linewidth=200)
plt.imshow(traning_images[0])
print(traning_images[0])
print(traning_label[0])

model=tf.keras.models.Sequential([tf.keras.layers.Flatten(),
                                  tf.keras.layers.Dense(128,activation=tf.nn.relu),
                                  tf.keras.layers.Dense(10,activation=tf.nn.softmax)])

model.compile(optimizer=tf.optimizers.Adam(),
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])
model.fit(traning_images,traning_label,epochs=10,callbacks=[callbacks])

model.evaluate(test_images,test_label)

卷积和池化

  1. 卷积:我的定义——原始数据reshape成为矩阵的形式。用参数矩阵去乘在原始数据矩阵中所有大小相同的矩阵的和组成一个新矩阵。如下图。
    在这里插入图片描述
  2. 池化:进行特征降维。我们通过卷积形成的特征矩阵还是太大了,对不对?通过池化把这个矩阵在不改变其特征性的前提下,进行降维。
    池化的四种方法
    1. 平均值:取4个特征值的平均值作为新的特征值。
    2. 最大值:取4个特征值中最大值作为新的特征值。
    3. 最小值:取4个特征值中最小值作为新的特征值。

卷积和池化总结
(1)卷积是从一小块图像区域中提取出特征值来表示这一小块区域的内在特征。

(2)池化是将相临的多个特征用一个特征来代替,压缩特征维度。

示例代码

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
class myCallback(tf.keras.callbacks.Callback):
  def on_epoch_end(self, epoch, logs={}):
    if(logs.get('accuracy')>0.6):
      print("\nReached 60% accuracy so cancelling training!")
      self.model.stop_training = True
callbacks=myCallback()           
mnist=tf.keras.datasets.fashion_mnist
(traning_images,traning_label),(test_images,test_label)=mnist.load_data()
np.set_printoptions(linewidth=200)
traning_images=traning_images.reshape(60000, 28, 28, 1)
traning_images=traning_images / 255.0
test_images = test_images.reshape(10000, 28, 28, 1)
test_images=test_images/255.0
model=tf.keras.models.Sequential([
                                  tf.keras.layers.Conv2D(64, (3,3), activation='relu', input_shape=(28, 28, 1)),
                                  tf.keras.layers.MaxPooling2D(2, 2),
                                  tf.keras.layers.Conv2D(64, (3,3), activation='relu'),
                                  tf.keras.layers.MaxPooling2D(2,2),
                                  tf.keras.layers.Flatten(),
                                  tf.keras.layers.Dense(128,activation=tf.nn.relu),
                                  tf.keras.layers.Dense(10,activation=tf.nn.softmax)])

model.compile(optimizer=tf.optimizers.Adam(),
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])
model.fit(traning_images,traning_label,epochs=10)

model.evaluate(test_images,test_label)

TensorFlow处理horse-or-human图像

(参考博文:链接
以上程序使用的均是mnist提供的28×28像素标准的图像,接下来我们需要能够处理不规则图像。

  1. 下载数据集:
    网盘:链接
    提取码:05ia
  2. 解压:这里笔者把该压缩包放在了如下路径中,并新建了同名文件夹。在这里插入图片描述
import zipfile

local_zip='F:\AIlib\horse-or-human.zip'
zip_ref=zipfile.ZipFile(local_zip,'r')
zip_ref.extractall('F:\AIlib\horse-or-human')
zip_ref.close()

用python解压。得到两个文件夹horse和human。但是每个子文件夹分别包含数百张horse或者human的图片,但是并针对于单个图片而言,并没有label信息,这一点是和其他数据集有不同的地方,如在fashion mnist数据集中,28*28的图片数据是T桖还是靴子,都已经在数据集中标记了。

所以,我们需要为该数据集标记label。ImageGenerator可以帮我们完成这个动作,ImageGenerator通过读取单个图片的文件名来标记图片是horse还是human(文件名都是以horse或human开头的)。

  1. 读取文件名以及数量
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import os
import zipfile

local_zip='F:\AIlib\horse-or-human.zip'
zip_ref=zipfile.ZipFile(local_zip,'r')
zip_ref.extractall('F:\AIlib\horse-or-human')
zip_ref.close()

train_horse=os.path.join('F:\AIlib\horse-or-human\horses')
train_human=os.path.join('F:\AIlib\horse-or-human\humans')

train_horse_names=os.listdir(train_horse)
print(len(train_horse_names))
print(train_horse_names[:10])


train_human_names=os.listdir(train_human)  
print(len(train_human_names))  
print(train_human_names[:10]) 

读取结果
在这里插入图片描述

  1. 模型训练
    示例代码
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import os
import zipfile
from tensorflow.keras.optimizers import RMSprop
from tensorflow.keras.preprocessing.image import ImageDataGenerator


local_zip='F:\AIlib\horse-or-human.zip'
zip_ref=zipfile.ZipFile(local_zip,'r')
zip_ref.extractall('F:\AIlib\horse-or-human')
zip_ref.close()

train_horse=os.path.join('F:\AIlib\horse-or-human\horses')
train_human=os.path.join('F:\AIlib\horse-or-human\humans')

train_horse_names=os.listdir(train_horse)

train_human_names=os.listdir(train_human)  

model = tf.keras.models.Sequential([#模型构建
    # Note the input shape is the desired size of the image 300x300 with 3 bytes color
    # This is the first convolution
    tf.keras.layers.Conv2D(16, (3,3), activation='relu', input_shape=(300, 300, 3)),
    tf.keras.layers.MaxPooling2D(2, 2),
    # The second convolution
    tf.keras.layers.Conv2D(32, (3,3), activation='relu'),
    tf.keras.layers.MaxPooling2D(2,2),
    # The third convolution
    tf.keras.layers.Conv2D(64, (3,3), activation='relu'),
    tf.keras.layers.MaxPooling2D(2,2),
    # The fourth convolution
    tf.keras.layers.Conv2D(64, (3,3), activation='relu'),
    tf.keras.layers.MaxPooling2D(2,2),
    # The fifth convolution
    tf.keras.layers.Conv2D(64, (3,3), activation='relu'),
    tf.keras.layers.MaxPooling2D(2,2),
    # Flatten the results to feed into a DNN
    tf.keras.layers.Flatten(),
    # 512 neuron hidden layer
    tf.keras.layers.Dense(512, activation='relu'),
    # Only 1 output neuron. It will contain a value from 0-1 where 0 for 1 class ('horses') and 1 for the other ('humans')
    tf.keras.layers.Dense(1, activation='sigmoid')
])

model.compile(loss='binary_crossentropy',#编译模型
              optimizer=RMSprop(lr=0.001),
              metrics=['acc'])

train_datagen = ImageDataGenerator(rescale=1/255)#打标签
# 使用train_datagen 产生 128批量的图片训练流
train_generator = train_datagen.flow_from_directory(
        'F:/AIlib/horse-or-human/',  # 训练数据所在目录 images
        target_size=(300, 300),  #
        batch_size=128,          # 每次批量128个
        # 由于使用交叉熵代价函数或者叫损失函数,是个二分类的问题
        class_mode='binary')    
history = model.fit_generator(#训练
      train_generator,
      steps_per_epoch=8,  
      epochs=15,
      verbose=1)

进行三次卷积+池化数据格式的变化
在这里插入图片描述
对卷积和池化的再次解读:

  1. 卷积:
tf.keras.layers.Conv2D(16, (3,3), activation='relu', input_shape=(300, 300, 3)),

用该条代码举例:
(1)16代表卷积核的数目,即filters。
(2)(3,3)代表卷积核矩阵的大小。
(3)activation是激活函数。
(4)input_shape代表输入的形状。300×300的矩阵R、G、B各一个。

  1. 池化:
tf.keras.layers.MaxPooling2D(2,2),

·每个2×2的子矩阵缩减成4个数中的最大值。实现矩阵压缩特征降维。

导入图片检验

此项功能示例程序需要google的云服务,因笔者不能科学上网,又暂时没有找到可替代方法。
可能以后会更新~

----------------------------------------------------暂时完结----------------------------------------------------------------------

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值