tensorflow示例代码注释2

02_logistic_regression.py

#!/usr/bin/env python


import tensorflow as tf
import numpy as np
import input_data

// random_normal返回一个tensor其中的元素的值服从正态分布,stddev标准差

def init_weights(shape):

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

def model(X, w):
    return tf.matmul(X, w) # notice we use the same model as linear regression, this is because there is a baked in cost function which performs softmax and cross entropy


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]) # create symbolic variables
Y = tf.placeholder("float", [None, 10])

w = init_weights([784, 10]) # like in linear regression, we need a shared variable weight matrix for logistic regression

py_x = model(X, w)

//reduce_mean取均值,第一个参数为输入矩阵,第二个为reduce所沿的维度,X,Y或者Z等

//softmax_cross_entropy_with_logits 取KL散度,交叉熵

//tf.argmax 是一个非常有用的函数,它能给出某个tensor对象在某一维上的其数据最大值所在的索引值。由于标签向量是由0,1组成,因此最大值1所在的索引位置就是类别标

//签,比如tf.argmax(y,1)返回的是模型对于任一输入x预测到的标签值,而 tf.argmax(y_,1) 代表正确的标签,我们可以用tf.equal 来检测我们的预测是否真实标签匹配(索引位置//一样表示匹配)。

cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(py_x, Y)) # compute mean cross entropy (softmax is applied internally)
train_op = tf.train.GradientDescentOptimizer(0.05).minimize(cost) # construct optimizer
predict_op = tf.argmax(py_x, 1) # at predict time, evaluate the argmax of the logistic regression

# Launch the graph in a session
with tf.Session() as sess:
    # you need to initialize all variables
    tf.initialize_all_variables().run()
//range(开始,结束,间隔),这里是每次取128个数进行训练,一个循环128次,100次循环
    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]})
        print(i, np.mean(np.argmax(teY, axis=1) ==

                         sess.run(predict_op, feed_dict={X: teX, Y: teY})))


//重点说一下,np.argmax(teY,axis=1),是对teY矩阵按行求最大值的索引值,也就是分类的编码,也就是数字0,1,2,3...9,如果打印,会看到是一个一维数组,都是结果

//sess.run(predict_op, feed_dict={X: teX, Y: teY}) 中,因为predict_op是求按py_x进行分类的结果,所以测试集teX,teY,实际上teY是不需要的。我验证了一下,不输入teY,结果也没有变化,但是没有teX,会运行错误。


最后一段的意义,就是输出测试集teY的分类和模型测试的结果,有什么区别,求它们的均值。实际上就是准确率了

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是基于tensorflow2.5实现的使用winograd算法优化的深度可分离卷积模块代码注释: ```python import tensorflow as tf class WinogradDepthwiseConv2D(tf.keras.layers.Layer): def __init__(self, filters, kernel_size, padding='same', strides=1): super(WinogradDepthwiseConv2D, self).__init__() self.filters = filters self.kernel_size = kernel_size self.padding = padding self.strides = strides # 计算Winograd卷积的中间矩阵G、B、A self.G, self.B, self.A = self._winograd_transform() # 初始化卷积核权重 self.depthwise_weights = self.add_weight(name='depthwise_weights', shape=(self.kernel_size, self.kernel_size, 1, self.filters), initializer=tf.keras.initializers.RandomNormal(stddev=0.1), trainable=True) def _winograd_transform(self): # Winograd卷积的中间矩阵G、B、A的计算 if self.kernel_size == 3: G = tf.constant([[1, 0, 0], [0.5, 0.5, 0.5], [0.5, -0.5, 0.5]], dtype=tf.float32) B = tf.constant([[1, 0, -1], [0, 1, 1], [0, -1, 1]], dtype=tf.float32) A = tf.constant([[1, 1, 1, 0], [0, 1, -1, -1]], dtype=tf.float32) elif self.kernel_size == 5: G = tf.constant([[1, 0, 0, 0], [0.5, 0.5, 0.5, 0.5], [0.5, -0.5, 0.5, -0.5], [0, 0, 1, 0], [0, 0, 0, 1]], dtype=tf.float32) B = tf.constant([[1, 0, -5, 0, 5], [0, 1, 4, -4, -4], [0, -1, 4, 4, -4], [0, 2, 2, -2, -2], [0, -2, 2, 2, -2]], dtype=tf.float32) A = tf.constant([[1, 1, 1, 1, 1], [0, 1, -1, 2, -2], [0, 1, 1, 4, 4], [0, 1, -1, 8, -8], [0, 1, 1, 16, 16]], dtype=tf.float32) else: raise ValueError('Unsupported kernel size!') return G, B, A def call(self, inputs): # 对输入数据进行填充 if self.padding == 'same': padding_size = self.kernel_size // 2 inputs = tf.pad(inputs, [[0, 0], [padding_size, padding_size], [padding_size, padding_size], [0, 0]], mode='CONSTANT') elif self.padding == 'valid': padding_size = 0 else: raise ValueError('Unsupported padding mode!') # Winograd卷积的前向计算 batch_size, input_height, input_width, input_channels = inputs.shape output_height = (input_height - self.kernel_size + 2 * padding_size) // self.strides + 1 output_width = (input_width - self.kernel_size + 2 * padding_size) // self.strides + 1 # Reshape inputs: [batch, height, width, channels] -> [batch, height * width, channels] inputs = tf.reshape(inputs, [batch_size, input_height * input_width, input_channels]) # Compute U = G * inputs U = tf.matmul(self.G, inputs, transpose_a=True) # Compute V = U * depthwise_weights V = tf.matmul(U, self.depthwise_weights) # Reshape V: [batch, height * width, channels] -> [batch, height, width, channels] V = tf.reshape(V, [batch_size, output_height, output_width, input_channels * self.filters]) # Compute Y = B * V * At Y = tf.matmul(V, self.B, transpose_b=True) Y = tf.transpose(Y, [0, 3, 1, 2]) Y = tf.reshape(Y, [batch_size, self.filters, output_height * output_width]) Y = tf.matmul(self.A, Y) Y = tf.reshape(Y, [batch_size, self.filters, output_height, output_width]) Y = tf.transpose(Y, [0, 2, 3, 1]) return Y ``` 然后,我们可以使用该模块来构建神经网络,如下所示: ```python import tensorflow as tf # 构建神经网络 model = tf.keras.Sequential([ # 输入层 tf.keras.layers.InputLayer(input_shape=(224, 224, 3)), # 第一个Winograd卷积层 WinogradDepthwiseConv2D(filters=32, kernel_size=3, strides=2), tf.keras.layers.BatchNormalization(), tf.keras.layers.ReLU(), # 第二个Winograd卷积层 WinogradDepthwiseConv2D(filters=64, kernel_size=3, strides=1), tf.keras.layers.BatchNormalization(), tf.keras.layers.ReLU(), # 第三个Winograd卷积层 WinogradDepthwiseConv2D(filters=128, kernel_size=3, strides=2), tf.keras.layers.BatchNormalization(), tf.keras.layers.ReLU(), # 第四个Winograd卷积层 WinogradDepthwiseConv2D(filters=256, kernel_size=3, strides=1), tf.keras.layers.BatchNormalization(), tf.keras.layers.ReLU(), # 第五个Winograd卷积层 WinogradDepthwiseConv2D(filters=512, kernel_size=3, strides=2), tf.keras.layers.BatchNormalization(), tf.keras.layers.ReLU(), # 第六个Winograd卷积层 WinogradDepthwiseConv2D(filters=1024, kernel_size=3, strides=1), tf.keras.layers.BatchNormalization(), tf.keras.layers.ReLU(), # 平均池化层 tf.keras.layers.GlobalAveragePooling2D(), # 输出层 tf.keras.layers.Dense(units=1000, activation='softmax') ]) # 编译模型 model.compile(optimizer=tf.keras.optimizers.Adam(), loss=tf.keras.losses.CategoricalCrossentropy(), metrics=['accuracy']) # 训练模型 model.fit(train_dataset, epochs=10, validation_data=val_dataset) ``` 在这个示例中,我们使用了6个Winograd卷积层来构建一个简单的卷积神经网络。我们可以通过传入不同的参数来设置卷积层的大小、步长、滤波器数量等。最后,我们编译模型并使用训练数据集对其进行训练。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值