记录:Mnist手写识别

环境:anaconda64位+python3.6+TensorFlow 1.9.0

重点:

(1)如果你实现此代码,加载数据集Mnist失败,请前往:https://blog.csdn.net/landcruiser007/article/details/79346982,手动下载mnist数据集

(2)分类问题,当然要用到softmax和交叉熵,softmax我也只是简单的了解了一下,大家想知道细节的自己找一下。

交叉熵j精品!!传送门:https://blog.csdn.net/tsyccnh/article/details/79163834

 

话不多说,贴上代码

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist=input_data.read_data_sets("D:/BaiduNetdiskDownload/MNIST_data/",one_hot=True)

#增加一个层
def add_layer(inputs,in_size,out_size,activation_function=None):
    Weights=tf.Variable(tf.random_normal([in_size,out_size]))
    #bias维度:1*outsize
    biases=tf.Variable(tf.zeros([1,out_size])+0.1) 
    Wx_plus_b = tf.matmul(inputs,Weights)+biases
    if activation_function is None:
        outputs=Wx_plus_b
    else:
        outputs=activation_function(Wx_plus_b)
    return outputs

#计算准确率
def compute_accuracy(v_xs,v_ys):
    global prediction
    y_pre=sess.run(prediction,feed_dict={xs:v_xs})
    #tf.argmax()返回各行元素最大值的位置,形成一维向量
    #tf.equal()两个值相等返回True
    correct_prediction=tf.equal(tf.argmax(y_pre,1),tf.argmax(v_ys,1))
    #计算准确率
    accuracy=tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
    result=sess.run(accuracy,feed_dict={xs:v_xs,ys:v_ys})
    print(y_pre.shape)
    return result

xs=tf.placeholder(tf.float32,[None,784])#28*28
ys=tf.placeholder(tf.float32,[None,10])

#激活函数是softmax
prediction=add_layer(xs,784,10,activation_function=tf.nn.softmax)

#两个tf的一维向量相乘,每个元素相乘
cross_entroy=tf.reduce_mean(-tf.reduce_sum(ys*tf.log(prediction),reduction_indices=[1]))
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entroy)

init=tf.global_variables_initializer()#variable需要初始化
with tf.Session() as sess:
    sess.run(init)
    for i in range(500):
        #取100个数据进行学习
        batch_xs,batch_ys=mnist.train.next_batch(100)
        sess.run(train_step,feed_dict={xs: batch_xs,ys:batch_ys})
        if i%50 ==0:
            print(compute_accuracy(mnist.test.images,mnist.test.labels))

 

使用PyTorch实现MNIST手写数字识别是一个常见的深度学习入门示例,它通常涉及几个步骤: 1. **导入库**: ```python import torch from torchvision import datasets, transforms import torch.nn as nn import torch.optim as optim ``` 2. **数据预处理**: ```python transform = transforms.Compose([ transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,)) ]) train_dataset = datasets.MNIST(root='./data', train=True, download=True, transform=transform) test_dataset = datasets.MNIST(root='./data', train=False, download=True, transform=transform) ``` 3. **创建数据加载器**: ```python train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=64, shuffle=True) test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=64, shuffle=False) ``` 4. **定义模型结构**,这里我们用经典的卷积神经网络(CNN)作为例子: ```python class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(1, 10, kernel_size=5) self.pool = nn.MaxPool2d(2, 2) self.fc1 = nn.Linear(10 * 14 * 14, 128) self.fc2 = nn.Linear(128, 10) def forward(self, x): x = self.pool(F.relu(self.conv1(x))) x = x.view(-1, 10 * 14 * 14) x = F.relu(self.fc1(x)) x = self.fc2(x) return x model = Net() ``` 5. **选择损失函数和优化器**: ```python criterion = nn.CrossEntropyLoss() optimizer = optim.SGD(model.parameters(), lr=0.001, momentum=0.9) ``` 6. **训练循环**: ```python for epoch in range(num_epochs): for i, (images, labels) in enumerate(train_loader): # ... 进行前向传播、计算loss、反向传播以及优化操作 # 记录和可视化训练过程的指标(如准确率) ``` 7. **评估模型**: ```python with torch.no_grad(): correct = 0 total = 0 for images, labels in test_loader: outputs = model(images) _, predicted = torch.max(outputs.data, 1) total += labels.size(0) correct += (predicted == labels).sum().item() accuracy = 100 * correct / total ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值