Tensorflow 基础编程

前言

机器学习和以往的编程的区别:

What we’ll do is we can get a bunch of examples from what we want to see, and then have the computer figure out the rules.

注意:我们所打上的标签(Labels)是Answers,而不是Rules。

神经网络入门

model = keras.Sequential([keras.layers.Dense(units=1,input_shape=[1])])

Dense: define a layer of connected neurons

Sequencial:Succesive(连续不断的) layer


model.compile(optimizer='sgd',loss='mean_squared_error')

SGD:Stochastic Gradient Descent(随机梯度下降)

Mean Squared Error:均方误差

补充资料:

深度学习——优化器算法Optimizer详解(BGD、SGD、MBGD、Momentum、NAG、Adagrad、Adadelta、RMSprop、Adam)


X和Y的值:

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)

代入创建好的模型中,迭代500次:

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

完成后,输入新的数据,并让模型预测结果:

print(model.predict([10.0]))

打印了500个,最后一个结果是:

6/6 [==============================] - 0s 492us/step - loss: 5.0427e-05
[[18.979282]]


为什么输出不是19?

  • 你训练的数据很少,只有6个

  • 当你使用神经网络时,神经网络会使用概率帮你找到答案

Fashion mnist

Fashion-MNIST包含70k张图片,10种衣物,并且每张都是28x28灰度图像(数据量更小,但人眼依然可以识别)。

它是在Tensorflow这个API中的数据集。

遍历处理Fashion Mnist

加载数据集

声明变量:

mnist = keras.datasets.fashion_mnist

调用函数,返回四个列表,训练集,训练集标签,测试集,测试集标签:

(training_images, training_labels), (test_images, test_labels) = mnist.load_data()

 选择一张裸靴图片,其标签是09,为什么标签是数字而不是文字?

  • 计算机处理数字处理地更好

  • 减少偏见。如果用英语标注,会偏向English Speakers.

    (啊这,可是主流的编程语言不都是用英语写的嘛。但是换成数字确实免去了转换的麻烦)


搭建模型

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

第一层是扁平层,每个图片的像素是28x28,把这个28x28的正方形变成一个简单的 linear array。

举个例子:把这个 (height, width, channel) 的三维数据压缩成长度为 (height × width × channel, 1) 的一维数组。

第二层是隐藏层,这一层有128个神经元。

#第三层是输出层,因为有10种衣物,所以得到的应该是10个概率,且和为1。


完整代码

import tensorflow as tf
import keras
# import matplotlib.pyplot as plt

# 加载数据集
mnist = keras.datasets.fashion_mnist
(training_images, training_labels), (test_images, test_labels) = mnist.load_data()

# 打印第0个样本的值
plt.imshow(training_images[0])
print(training_labels[0])
print(training_images[0])

# 数据预处理
training_images = training_images/255.0
test_images = test_images/255.0

# 模型搭建
model = keras.Sequential([
    keras.layers.Flatten(input_shape=(28,28)),  #每个图片的像素是28x28
    keras.layers.Dense(128, activation=tf.nn.relu),
    keras.layers.Dense(10,activation=tf.nn.softmax) #因为有10种衣物,所以应该得到的是他们各自的概率
])

# 模型编译
model.compile(optimizer=tf.compat.v1.train.AdamOptimizer(),loss='sparse_categorical_crossentropy')

# 模型拟合
model.fit(training_images,training_labels,epochs=5)

# 模型评估
model.evaluate(test_images,test_labels)

Callback

调用一个回调函数,检查指标,如果这个指标合格的话,你可以在该点取消训练。

class myCallback(tf.keras.callbacks.Callback):
    def on_epoch_end(self, epoch, logs={
   }):     # 在迭代结束时调用
        if(logs.get('loss')<0.4):
            print("\nLoss is low so cancelling training!")
            self.model.stop_training = True  # 如果loss<0.4,就停止训练

实例化刚刚创建的类:

callbacks = myCallback()

修改model.fit函数,使用回调参数,并传递它的类实例:

model.fit(training_images,training_labels,epochs=5,callbacks=[callbacks])

看看结果:

60000/60000 [==============================] - 3s 42us/step - loss: 0.3787

Loss is low so cancelling training!

使用CNN处理 Fashion Mnist

搭建模型

model = tf.keras.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.MaxPool2D(2,2),
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(128,activation='relu'),
    tf.keras.layers.Dense(10,activation='softmax')
])

解释模型

使用卷积神经网络(用滤波器遍历图片)代替逐张照片逐个像素遍历:

tf.keras.layers.Conv2D(64,(3,3),activation='relu',input_shape=(28,28,1))

Conv2D:第一层是卷积层

(3,3):过滤器的大小是 3x3

activation=‘relu’:激活函数是relu,意味着负值将会被抛弃

input_shape=(28,28,1):输入形状和之前一样,是 28x28。额外的1个意味着我们正在用1个字节去来加计算颜色深度(color depth),因为是灰度图像,所以只需要1个字节(如果是彩色图像,则需要3个字节)


 tf.keras.layers.MaxPooling2D(2,2)

MaxPooling2D:第二层是池化层,方式是最大值池化,其尺寸是 2x2

···其余依此类推。

经过两个卷积层和两个池化层之后,content简化了很多。


model.summary()

打印模型概述信息:

Model: "sequential"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d (Conv2D)              (None, 26, 26, 64)        640       
_________________________________________________________________
max_pooling2d (MaxPooling2D) (None, 13, 13, 64)        0         
_________________________________________________________________
conv2d_1 (Conv2D)            (None, 11, 11, 64)        36928     
_________________________________________________________________
max_pooling2d_1 (MaxPooling2 (None, 5, 5, 64)          0         
_________________________________________________________________
flatten (Flatten)            (None, 1600)              0         
_________________________________________________________________
dense (Dense)                (None, 128)               204928    
_________________________________________________________________
dense_1 (Dense)              (None, 10)                1290      
=================================================================
Total params: 243,786
Trainable params: 243,786
Non-trainable params: 0
_________________________________________________________________

Process finished with exit code 0
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值