使用TensorFlow实现Softmax Regression识别手写数字

因为新冠病毒疫情,在家学习,没有带回什么书回家。今天在当当上网购的一本书《TensorFlow实战》到了,因为实验要使用BLSTM+CRF,所以先自己进行简单的学习,对照着里面的例子自己敲和理解,这里做一下记录。

这个例子使用简单的Softmax Regression进行MNIST手写数字识别。将灰度图片展开为28*28=784的一维向量,识别的结果为0-9共10个结果,所以有10个分类。下面是代码。

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

# 将mnist数据集下载到本地更方便使用
mnist = input_data.read_data_sets("F:/Experiment/TensorflowTest/Actual combat of Tensorflow/MNIST_data/", one_hot=True)
print(mnist.train.images.shape, mnist.train.labels.shape)
print(mnist.test.images.shape, mnist.test.labels.shape)
print(mnist.validation.images.shape, mnist.validation.labels.shape)

sess = tf.InteractiveSession()
x = tf.placeholder(tf.float32, [None, 784])
w = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
y = tf.nn.softmax(tf.matmul(x, w) + b)
y_ = tf.placeholder(tf.float32, [None, 10])

# 使用交叉熵
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
tf.global_variables_initializer().run()

for i in range(1000):
    batch_x, batch_y = mnist.train.next_batch(100)
    train_step.run({x: batch_x, y_: batch_y})


correct_prediction = tf.equal(tf.arg_max(y, 1), tf.arg_max(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print(accuracy.eval({x: mnist.test.images, y_: mnist.test.labels}))

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是使用Python实现手写数字识别softmax代码: ```python import numpy as np import matplotlib.pyplot as plt from sklearn.datasets import load_digits from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score # 加载手写数字数据集 digits = load_digits() X, y = digits.data, digits.target # 将数据集分为训练集和测试集 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42) # 定义softmax函数 def softmax(z): return np.exp(z) / np.sum(np.exp(z), axis=1, keepdims=True) # 定义交叉熵损失函数 def cross_entropy_loss(y_pred, y_true): m = y_pred.shape[0] p = softmax(y_pred) log_likelihood = -np.log(p[range(m), y_true]) loss = np.sum(log_likelihood) / m return loss # 定义softmax回归模型 class SoftmaxRegression: def __init__(self, n_features, n_classes, learning_rate=0.1): self.W = np.zeros((n_features, n_classes)) self.b = np.zeros(n_classes) self.learning_rate = learning_rate def fit(self, X, y, n_epochs=1000): m = X.shape[0] for epoch in range(n_epochs): # 前向传播 z = np.dot(X, self.W) + self.b y_pred = softmax(z) # 计算损失函数 loss = cross_entropy_loss(y_pred, y) # 反向传播 dz = y_pred - np.eye(self.W.shape[1])[y] dW = np.dot(X.T, dz) db = np.sum(dz, axis=0) # 更新参数 self.W -= self.learning_rate * dW self.b -= self.learning_rate * db # 打印损失函数 if epoch % 100 == 0: print("Epoch %d loss: %.4f" % (epoch, loss)) def predict(self, X): z = np.dot(X, self.W) + self.b y_pred = softmax(z) return np.argmax(y_pred, axis=1) # 训练softmax回归模型 model = SoftmaxRegression(n_features=X_train.shape[1], n_classes=len(np.unique(y_train))) model.fit(X_train, y_train) # 在测试集上评估模型性能 y_pred = model.predict(X_test) accuracy = accuracy_score(y_test, y_pred) print("Accuracy:", accuracy) # 可视化模型预测结果 fig, axes = plt.subplots(4, 4, figsize=(8, 8)) for i, ax in enumerate(axes.flat): ax.imshow(X_test[i].reshape(8, 8), cmap='binary') ax.set_title("True:%d Pred:%d" % (y_test[i], y_pred[i])) ax.set_xticks([]) ax.set_yticks([]) plt.show() ``` 该代码使用softmax回归模型实现手写数字识别,其中softmax函数用于将模型输出转换为概率分布,交叉熵损失函数用于衡量模型预测结果与真实标签之间的差异。模型训练过程中使用梯度下降算法更新模型参数,最终在测试集上评估模型性能。最后,使用matplotlib库可视化模型预测结果。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值