tensorflow示例代码注释3

04_modern_net.py

#!/usr/bin/env python


import tensorflow as tf
import numpy as np
import input_data


def init_weights(shape):
    return tf.Variable(tf.random_normal(shape, stddev=0.01))

//dropout 函数,用于从概率上将一部分input过滤,第二个参数为概率值,从0到1

//relu激励函数

def model(X, w_h, w_h2, w_o, p_keep_input, p_keep_hidden): # this network is the same as the previous one except with an extra hidden layer + dropout
    X = tf.nn.dropout(X, p_keep_input)
    h = tf.nn.relu(tf.matmul(X, w_h))

    h = tf.nn.dropout(h, p_keep_hidden)
    h2 = tf.nn.relu(tf.matmul(h, w_h2))

    h2 = tf.nn.dropout(h2, p_keep_hidden)

    return tf.matmul(h2, w_o)


mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
trX, trY, teX, teY = mnist.train.images, mnist.train.labels, mnist.test.images, mnist.test.labels

X = tf.placeholder("float", [None, 784])
Y = tf.placeholder("float", [None, 10])

w_h = init_weights([784, 625])
w_h2 = init_weights([625, 625])
w_o = init_weights([625, 10])

p_keep_input = tf.placeholder("float")
p_keep_hidden = tf.placeholder("float")
py_x = model(X, w_h, w_h2, w_o, p_keep_input, p_keep_hidden)


//RMSPropOptimizer  随机梯度下降算法的一种,为何不用minibatch?

cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(py_x, Y))
train_op = tf.train.RMSPropOptimizer(0.001, 0.9).minimize(cost)
predict_op = tf.argmax(py_x, 1)

# Launch the graph in a session
with tf.Session() as sess:
    # you need to initialize all variables
    tf.initialize_all_variables().run()

    for i in range(100):
        for start, end in zip(range(0, len(trX), 128), range(128, len(trX), 128)):
            sess.run(train_op, feed_dict={X: trX[start:end], Y: trY[start:end],
                                          p_keep_input: 0.8, p_keep_hidden: 0.5})
        print(i, np.mean(np.argmax(teY, axis=1) ==
                         sess.run(predict_op, feed_dict={X: teX, Y: teY,
                                                         p_keep_input: 1.0,
                                                         p_keep_hidden: 1.0})))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是基于TensorFlow 2.5,使用Winograd算法编写的深度可分离卷积模块的代码注释: ```python import tensorflow as tf class WinogradDepthwiseSeparableConv2D(tf.keras.layers.Layer): def __init__(self, filters, kernel_size, strides=1, padding='same', activation=None): super(WinogradDepthwiseSeparableConv2D, self).__init__() self.filters = filters self.kernel_size = kernel_size self.strides = strides self.padding = padding self.activation = activation self.depthwise_conv = tf.keras.layers.DepthwiseConv2D( kernel_size=self.kernel_size, strides=self.strides, padding=self.padding, depthwise_initializer='he_normal', use_bias=False ) # 使用Winograd算法进行卷积优化的参数 self.winograd_f = tf.constant([ [1.0, 0.0, 0.0], [-2.0 / 9.0, -2.0 / 9.0, -2.0 / 9.0], [-2.0 / 9.0, 2.0 / 9.0, -2.0 / 9.0], [1.0 / 90.0, 1.0 / 45.0, 2.0 / 45.0], [1.0 / 90.0, -1.0 / 45.0, 2.0 / 45.0], [0.0, 0.0, 1.0] ], dtype=tf.float32) self.winograd_g = tf.constant([ [1.0, 0.0, -1.0, 0.0, 1.0, 0.0], [0.0, 1.0, 1.0, -1.0, -1.0, 0.0], [0.0, -1.0, 1.0, 1.0, -1.0, 0.0], [0.0, 1.0 / 2.0, 1.0 / 4.0, -1.0 / 2.0, -1.0 / 4.0, 0.0], [0.0, -1.0 / 2.0, 1.0 / 4.0, 1.0 / 2.0, -1.0 / 4.0, 0.0], [0.0, 2.0, 4.0, 2.0, 1.0, 0.0] ], dtype=tf.float32) self.winograd_b = tf.constant([ [1.0, 0.0, 0.0], [0.0, 1.0, -1.0], [-1.0, 1.0, 1.0], [0.0, 1.0 / 2.0, 1.0 / 2.0], [0.0, -1.0 / 2.0, 1.0 / 2.0], [0.0, 0.0, 1.0] ], dtype=tf.float32) self.pointwise_conv = tf.keras.layers.Conv2D( filters=self.filters, kernel_size=1, strides=1, padding='same', kernel_initializer='he_normal', use_bias=False ) def call(self, inputs): x = self.depthwise_conv(inputs) # 使用Winograd算法进行卷积优化 x = tf.transpose(x, perm=[0, 3, 1, 2]) x = tf.reshape(x, [-1, x.shape[2], x.shape[3]]) x = tf.matmul(self.winograd_f, x) x = tf.matmul(x, self.winograd_g) x = tf.matmul(self.winograd_b, x) x = tf.reshape(x, [-1, tf.shape(inputs)[1], tf.shape(inputs)[2], self.filters]) x = tf.transpose(x, perm=[0, 2, 3, 1]) x = self.pointwise_conv(x) if self.activation is not None: x = self.activation(x) return x ``` 使用示例: ```python model = tf.keras.models.Sequential([ tf.keras.layers.Input(shape=(32, 32, 3)), WinogradDepthwiseSeparableConv2D(filters=32, kernel_size=3, strides=1, padding='same', activation='relu'), WinogradDepthwiseSeparableConv2D(filters=64, kernel_size=3, strides=2, padding='same', activation='relu'), tf.keras.layers.Flatten(), tf.keras.layers.Dense(units=10, activation='softmax') ]) model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) model.summary() ``` 在神经网络中使用该模块时,只需像使用其他层一样将其插入到模型中即可,如上例所示。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值