mnist 预测值=nan 帮我看看哪里出问题了?

# -*- coding: utf-8 -*-
import tensorflow as tf
import os
import struct
import numpy as np
import numpy
import matplotlib.pyplot as plt


#显示单张图片
def ShowPic(x_train,prediction,origin):
    plt.title('Number = '+ str(origin)+',prediction='+str(prediction))
    plt.imshow(x_train.reshape([28,28]), cmap='Greys', interpolation='nearest')
    plt.show()

# 数据处理
"""
60000行的训练数据集(mnist.train)和10000行的测试数据集(mnist.test)。
一张包含手写数字的图片mnist.train.images 和一个对应的标签 mnist.train.labels。

mnist.train.images[60000, 784] 
mnist.train.images[1至60000张的图片索引, 每张图片中的像素点] 
每一张图片包含28X28个像素点,总共784个像素点,
文件 = 'train-images.idx3-ubyte'

mnist.train.labels[60000, 10]
mnist.train.labels[1至60000张的图片索引, 每张图片中表示的数字] 
数字n将表示成一个只有在第n维度(从0开始)数字为1的10维向量。
比如,标签0将表示成([1,0,0,0,0,0,0,0,0,0,0])。
文件 = train-labels.idx1-ubyte
"""

train_images_path = r'D:\MNIST预测手写数字图片\MNIST_data\train-images.idx3-ubyte'
train_labels_path = r'D:\MNIST预测手写数字图片\MNIST_data\train-labels.idx1-ubyte'

train_images = []  # =mnist.train.images
train_labels = []  # =mnist.train.labels

"""Load MNIST data from `path`"""
with open(train_labels_path, 'rb') as lbpath:
    magic, n = struct.unpack('>II', lbpath.read(8))
    train_labels = np.fromfile(lbpath, dtype=np.uint8)
with open(train_images_path, 'rb') as imgpath:
    magic, num, rows, cols = struct.unpack('>IIII', imgpath.read(16))
    train_images = np.fromfile(imgpath, dtype=np.uint8).reshape(len(train_labels), 784)

# train_labels 修改形状和值(=1)
new_train_labels = np.zeros((60000, 10), np.float32)
i = 0
for item in train_labels:
    new_train_labels[i][item] = 1.0
    i = i + 1
train_labels = new_train_labels

# 验证形状
print('train_images.shape =>' + str(train_images.shape))
print('train_labels.shape =>' + str(train_labels.shape))

print(train_labels[0:10])

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("float", [None, 10])  # 计算交叉熵
cross_entropy = -tf.reduce_sum(y_ * tf.log(y))  # 计算交叉熵
# 以0.01的学习速率最小化交叉熵
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)


# 初始化我们创建的变量
init = tf.initialize_all_variables()
sess = tf.Session()
sess.run(init)


#样本数量
num_examples =len(train_images)
#总的循环训练多少遍样本
train_total_number=1
# 遍历1次训练的数量
batch_size =100
#循环1遍样本需要遍历的次数
Loop_one_examples=int(num_examples/batch_size+1)

#需要遍历次数
want_loop =Loop_one_examples*train_total_number

#当前索引
index=0
batch_xs=[]
batch_ys=[]
# 打乱数据
perm = numpy.arange(num_examples)  # 生成索引数组 值为 0 至 样本总数减1
numpy.random.shuffle(perm)  # 打乱索引顺序
train_images = train_images[perm]  # images索引=打乱顺序的索引
train_labels = train_labels[perm]


# 让模型循环 样本训练1次,循环的每个步骤 随机抓取训练数据中的100个批处理数据点
for i in range(want_loop):
    if index + batch_size >= num_examples-1:#到结尾时,不够一个batch,取最后
        batch_xs=train_images[num_examples-1-batch_size:num_examples-1]
        batch_ys=train_labels[num_examples-1-batch_size:num_examples-1]
    else:
        start = index
        index += batch_size
        end = index
        batch_xs=train_images[start:end]
        batch_ys=train_labels[start:end]
    sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
    print(str(want_loop)+'=total loop num,curr loop num ='+str(i))

# 下面验证测试部分
test_images_path = r'D:\MNIST预测手写数字图片\MNIST_data\t10k-images.idx3-ubyte'
test_labels_path = r'D:\MNIST预测手写数字图片\MNIST_data\t10k-labels.idx1-ubyte'

test_images = []  # =mnist.train.images
test_labels = []  # =mnist.train.labels

"""Load MNIST data from `path`"""
with open(test_labels_path, 'rb') as lbpath:
    magic, n = struct.unpack('>II', lbpath.read(8))
    test_labels = np.fromfile(lbpath, dtype=np.uint8)
with open(test_images_path, 'rb') as imgpath:
    magic, num, rows, cols = struct.unpack('>IIII', imgpath.read(16))
    test_images = np.fromfile(imgpath, dtype=np.uint8).reshape(len(test_labels), 784)

# test_labels   不用修改了,因为不参与训练
# new_test_labels = np.zeros((10000, 10), np.float32)
# i = 0
# for item in test_labels:
#     new_test_labels[i][item] = 1.0
#     i = i + 1
# test_labels = new_test_labels

# 验证形状
print('test_images.shape =>' + str(test_images.shape))
print('test_labels.shape =>' + str(test_labels.shape))


#预测 第一张图片 的值
res = sess.run(y,feed_dict={x: [test_images[0]]})
print('curr num = ' +str(test_labels[0].max()) +",,prediction =" )
print(res)


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值