Tensorflow简单复现softmax模型对于mnist数据集分类

本文通过使用TensorFlow实现了一个简单的MNIST手写数字识别模型,并对比了GradientDescentOptimizer和AdamOptimizer两种优化器的效果。在输入数据定义、模型变量定义、模型定义及成本函数定义的基础上,展示了如何用GradientDescentOptimizer进行训练。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

代码中对于GradientDescentOptimizer和AdamOptimizer进行了简单比较。

import tensorflow as tf 
import numpy as np
from tensorflow.examples.tutorials.mnist import input_data

mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)

# Input data definition
x = tf.placeholder(tf.float32,[None,784])
y = tf.placeholder(tf.float32,[None,10])
# Model variable definition
W = tf.Variable(tf.zeros([784,10]))
b = tf.Variable(tf.zeros([10]))
# Define model
y_predict = tf.matmul(x,W)+b
# Define cost function 
cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels = y,logits = y_predict))
# Thinking1 - What will happen here,if i use adam optimizer?
#optimizer = tf.train.AdamOptimizer(1e-4)
optimizer = tf.train.GradientDescentOptimizer(0.5)
train_step = optimizer.minimize(cross_entropy)

sess = tf.InteractiveSession()
global_initial = tf.global_variables_initializer()
sess.run(global_initial)

for i in range(1000):
	batch = mnist.train.next_batch(100)
	sess.run(train_step,feed_dict={x:batch[0],y:batch[1]})

correct_prediction = tf.equal(tf.argmax(y_predict,1),tf.argmax(y,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
print(sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels}))

print(sess.run(b))


### 使用公开数据集进行图像处理的详细教程 #### 准备工作 在开始之前,确保安装必要的Python库。这些工具对于加载、预处理和操作图像至关重要。 ```bash pip install numpy matplotlib opencv-python tensorflow scikit-image ``` #### 导入所需模块并设置环境变量 准备阶段涉及导入所有必需的包,并配置任何全局参数或路径。 ```python import os import cv2 import numpy as np from skimage import io, transform import matplotlib.pyplot as plt import tensorflow.keras as tk ``` #### 获取数据集 可以利用TensorFlow内置函数轻松获取MNIST手写数字识别数据集[^3]: ```python (train_images, train_labels), (test_images, test_labels) = tk.datasets.mnist.load_data() print(f'Training data shape: {train_images.shape}') print(f'Number of training labels: {len(train_labels)}') print(f'Testing data shape: {test_images.shape}') print(f'Number of testing labels: {len(test_labels)}') ``` 对于更复杂的应用场景,则可能需要手动下载其他类型的公共数据集,比如PASCAL VOC 2012用于语义分割挑战赛[^1] 或者 Open Images Dataset V6 跨越多个类别的大规模视觉理解任务[^2]。 假设已经获得了目标检测项目所需的Open Images Dataset的一部分,在继续下一步前先解压缩文件到指定位置。 #### 预览样本图片及其标签信息 通过随机选取几张来自训练集合中的样本来观察其外观特征以及对应的分类标记。 ```python def display_random_samples(dataset, labelset=None, num=5): indices = np.random.choice(len(dataset), size=num, replace=False) fig, axes = plt.subplots(1, num, figsize=(num * 2, 4)) for i, idx in enumerate(indices): img = dataset[idx] ax = axes[i] ax.imshow(img, cmap='gray') if len(img.shape)==2 else ax.imshow(img) title = f'Label:{labelset[idx]}' if labelset is not None else '' ax.set_title(title) ax.axis('off') display_random_samples(train_images[:], train_labels[:]) plt.show() ``` #### 图像增强与标准化 为了提高模型泛化能力,通常会对原始输入执行一系列变换来扩充有效样本数量;同时也要注意保持统计特性的一致性以便于后续计算收敛更快更好。 常见的方法包括但不限于旋转、翻转、缩放和平移等几何变形方式,还有亮度对比度调整之类的色彩空间转换手段。 这里展示了一个简单的例子——水平镜像反射加均值中心化处理后的效果对比图。 ```python def augment_and_normalize(image_batch): augmented_imgs = [] mean_value = image_batch.mean(axis=(0, 1)) for img in image_batch: flipped_img = cv2.flip(img, flipCode=1) # Horizontal Flip normalized_flipped_img = ((flipped_img - mean_value)/255.).astype(np.float32) original_normalized_img = ((img - mean_value)/255.).astype(np.float32) concatenated_result = np.concatenate([original_normalized_img[...,np.newaxis], normalized_flipped_img[...,np.newaxis]], axis=-1) augmented_imgs.append(concatenated_result) return np.array(augmented_imgs) sample_augmented = augment_and_normalize(train_images[:8]) fig, axs = plt.subplots(nrows=len(sample_augmented)//2, ncols=4, sharex=True, sharey=True, squeeze=False) for row_idx, pair_of_images in zip(range(axs.shape[0]), sample_augmented.reshape(-1,2,*sample_augmented.shape[-2:])): for col_offset, single_image in enumerate(pair_of_images.transpose((2,0,1))): axs[row_idx][col_offset*2].imshow(single_image.squeeze(), cmap="gray") axs[row_idx][col_offset*2+1].imshow(cv2.flip(single_image.squeeze(),flipCode=1),cmap="gray") plt.tight_layout(pad=.4) plt.show() ``` #### 构建卷积神经网络架构 定义适合当前问题域特点的基础框架结构,例如LeNet-5风格的小型CNN可用于初步探索二元或多类别区分任务性能表现如何变化趋势。 ```python model = tk.models.Sequential([ tk.layers.Conv2D(filters=32,kernel_size=(3,3), activation='relu', input_shape=(None,None,1)), tk.layers.MaxPooling2D(pool_size=(2,2)), tk.layers.Flatten(), tk.layers.Dense(units=128,activation='relu'), tk.layers.Dropout(rate=0.5), tk.layers.Dense(units=10,activation='softmax') ]) model.compile(optimizer='adam',loss='sparse_categorical_crossentropy',metrics=['accuracy']) ``` #### 训练过程监控记录 启动迭代优化流程的同时开启tensorboard日志追踪功能方便后期分析评估指标走势情况。 ```python log_dir="./logs" if not os.path.exists(log_dir):os.makedirs(log_dir) callbacks=[tk.callbacks.TensorBoard(log_dir=log_dir,histogram_freq=1)] history=model.fit(x=train_images[:,:,:,np.newaxis]/255., y=train_labels,batch_size=64,epochs=5,callbacks=callbacks, validation_split=0.2) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值