鱼C论坛

 找回密码
 立即注册
查看: 100|回复: 1

图片识别代码问题

[复制链接]
发表于 2024-4-30 07:27:51 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
创建了四个独立的.py文件合起来实现手写数字识别


有没有大佬能帮着看一下下面的问题,因为1.x版本的Tensorflow已经下架,但是这里面很多编码都是1.X版本的Tensorflow,所以可能导致错误,可以帮着改一下不,就是不要改变大致目标

第一个文件:mnist_forward.py
-源代码:

  1. import tensorflow as tf

  2. INPUT_NODE = 784
  3. OUTPUT_NODE = 10
  4. LAYER1_NODE = 500

  5. def get_weight(shape, regularizer):
  6.     w = tf.Variable(tf.random.truncated_normal(shape, stddev=0.1))
  7.     if regularizer != None:
  8.         tf.add_to_collection("losses", tf.keras.regularizers.l2(regularizer)(w))
  9.     return w

  10. def get_bias(shape):
  11.     b = tf.Variable(tf.zeros(shape))
  12.     return b

  13. def forward(x, regularizer):
  14.     w1 = get_weight([INPUT_NODE, LAYER1_NODE], regularizer)
  15.     b1 = get_bias([LAYER1_NODE])
  16.     y1 = tf.nn.relu(tf.matmul(x, w1) + b1)

  17.     w2 = get_weight([LAYER1_NODE, OUTPUT_NODE], regularizer)
  18.     b2 = get_bias([OUTPUT_NODE])
  19.     y = tf.matmul(y1, w2) + b2
  20.     return y
复制代码



运行结果:无报错信息,无任何执行结果,执行后一段时间自动跳出

第二个文件:mnist_backward.py
-源代码:

  1. import tensorflow as tf
  2. from tensorflow.keras.datasets import mnist
  3. from mnist_forward import INPUT_NODE, OUTPUT_NODE  # 修正导入错误
  4. import os

  5. BATCH_SIZE = 200
  6. LEARNING_RATE_BASE = 0.1
  7. LEARNING_RATE_DECAY = 0.99
  8. REGULARIZER = 0.0001
  9. STEPS = 50000
  10. MOVING_AVERAGE_DECAY = 0.99
  11. MODEL_SAVE_PATH = "./model/"
  12. MODEL_NAME = "mnist_model"

  13. def backward(dataset):

  14.     x = tf.placeholder(tf.float32, [None, INPUT_NODE])  # 使用修正后的导入
  15.     y_ = tf.placeholder(tf.float32, [None, OUTPUT_NODE])  # 使用修正后的导入
  16.     y = mnist_forward.forward(x, REGULARIZER)
  17.     global_step = tf.Variable(0, trainable=False)

  18.     logits = y  # 将神经网络输出 y 作为 logits
  19.     labels = tf.argmax(y_, 1)  # 将类别索引作为 labels
  20.     ce = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=labels)  # 修改损失计算方式
  21.     cem = tf.reduce_mean(ce)
  22.     loss = cem + tf.add_n(tf.get_collection("losses"))

  23.     learning_rate = tf.train.exponential_decay(
  24.         LEARNING_RATE_BASE,
  25.         global_step,
  26.         dataset.train.num_examples / BATCH_SIZE,
  27.         LEARNING_RATE_DECAY,
  28.         staircase=True)

  29.     train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss, global_step=global_step)

  30.     ema = tf.train.ExponentialMovingAverage(MOVING_AVERAGE_DECAY, global_step)
  31.     ema_op = ema.apply(tf.trainable_variables())
  32.     with tf.control_dependencies([train_step, ema_op]):
  33.         train_op = tf.no_op(name="train")

  34.     saver = tf.train.Saver()

  35.     with tf.Session() as sess:
  36.         init_op = tf.global_variables_initializer()
  37.         sess.run(init_op)

  38.         ckpt = tf.train.get_checkpoint_state(MODEL_SAVE_PATH)
  39.         if ckpt and ckpt.model_checkpoint_path:
  40.             saver.restore(sess, ckpt.model_checkpoint_path)

  41.         for i in range(STEPS):
  42.             xs, ys = dataset.train.next_batch(BATCH_SIZE)
  43.             _, lossvalue, step = sess.run([train_op, loss, global_step], feed_dict={x: xs, y_: ys})
  44.             if i % 1000 == 0:
  45.                 print("After %d training step(s), loss on training batch is %g." % (step, lossvalue))
  46.                 saver.save(sess, os.path.join(MODEL_SAVE_PATH, MODEL_NAME), global_step=global_step)


  47. def main():
  48.     (x_train, y_train), _ = mnist.load_data()
  49.     x_train = x_train.reshape(x_train.shape[0], -1) / 255.0
  50.     y_train = tf.keras.utils.to_categorical(y_train, 10)
  51.     dataset = tf.data.Dataset.from_tensor_slices((x_train, y_train)).shuffle(10000).batch(BATCH_SIZE)
  52.     backward(dataset)

  53. if __name__ == "__main__":
  54.     main()
复制代码



-运行结果:无报错信息,执行以后只要你点了IDLE的弹窗口就会卡死然后你必须手动退出,如果你让它往下执行,它就会出现很多字符串,想下载器一样,时不时会卡死一段时间,然后接着执行,运行大概五分钟以后,就会彻底卡死,需要手动退出,下面给一个运行截图:

                               
登录/注册后可看大图


第三个文件:mnist_test.py
-源代码:
  1. import tensorflow as tf
  2. import numpy as np
  3. import mnist_forward
  4. import os

  5. TEST_INTERVAL_SECS = 5

  6. def test(mnist):
  7.     x = tf.placeholder(tf.float32, [None, mnist_forward.INPUT_NODE])
  8.     y_ = tf.placeholder(tf.float32, [None, mnist_forward.OUTPUT_NODE])
  9.     y = mnist_forward.forward(x, None)

  10.     ema = tf.train.ExponentialMovingAverage(mnist_backward.MOVING_AVERAGE_DECAY)
  11.     ema_restore = ema.variables_to_restore()
  12.     saver = tf.train.Saver(ema_restore)

  13.     correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
  14.     accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

  15.     while True:
  16.         latest_checkpoint = tf.train.latest_checkpoint(mnist_backward.MODEL_SAVE_PATH)
  17.         if latest_checkpoint:
  18.             saver.restore(tf.compat.v1.get_default_session(), latest_checkpoint)
  19.             global_step = int(latest_checkpoint.split("-")[-1])
  20.             accuracy_score = accuracy.eval(feed_dict={x: mnist.test.images, y_: mnist.test.labels})
  21.             print("After %s training step(s), test accuracy = %g" % (global_step, accuracy_score))
  22.         else:
  23.             print("No checkpoint file found")
  24.             return
  25.         time.sleep(TEST_INTERVAL_SECS)

  26. def main():
  27.     mnist = tf.keras.datasets.mnist
  28.     (x_train, y_train), (x_test, y_test) = mnist.load_data()
  29.     x_test = np.reshape(x_test, (-1, mnist_forward.INPUT_NODE))
  30.     y_test = tf.keras.utils.to_categorical(y_test, mnist_forward.OUTPUT_NODE)
  31.     mnist.test = tf.data.Dataset.from_tensor_slices((x_test, y_test)).batch(10000)
  32.     test(mnist)

  33. if __name__ == "__main__":
  34.     main()

复制代码


-运行结果:
同样没有报错信息,但是结果跟mnist.backward.py的结果一样,非常卡顿,运行一段时间后会自动退出,出现的数据也是一抹一样

第四个文件:mnist_app.py
-源代码:
  1. import tensorflow.compat.v1 as tf
  2. import numpy as np
  3. from PIL import Image
  4. import mnist_backward
  5. import mnist_forward
  6. import os

  7. tf.compat.v1.disable_v2_behavior()

  8. def restore_model(testPicArr):
  9.     with tf.Graph().as_default() as tg:
  10.         x = tf.compat.v1.placeholder(tf.float32, [None, mnist_forward.INPUT_NODE])
  11.         y = mnist_forward.forward(x, None)
  12.         preValue = tf.argmax(y, 1)

  13.         variable_averages = tf.train.ExponentialMovingAverage(mnist_backward.MOVING_AVERAGE_DECAY)
  14.         variables_to_restore = variable_averages.variables_to_restore()
  15.         saver = tf.compat.v1.train.Saver(variables_to_restore)

  16.         with tf.compat.v1.Session() as sess:
  17.             ckpt = tf.train.get_checkpoint_state(mnist_backward.MODEL_SAVE_PATH)
  18.             if ckpt and ckpt.model_checkpoint_path:
  19.                 print("Checkpoint file path:", ckpt.model_checkpoint_path)
  20.                 saver.restore(sess, ckpt.model_checkpoint_path)

  21.                 preValue = sess.run(preValue, feed_dict={x: testPicArr})
  22.                 return preValue
  23.             else:
  24.                 print("No checkpoint file found in", mnist_backward.MODEL_SAVE_PATH)
  25.                 return -1

  26. def pre_pic(picName):
  27.     img = Image.open(picName)
  28.     reIm = img.resize((28, 28), Image.LANCZOS)
  29.     im_arr = np.array(reIm.convert('L'))
  30.     threshold = 50
  31.     for i in range(28):
  32.         for j in range(28):
  33.             im_arr[i][j] = 255 - im_arr[i][j]
  34.             if im_arr[i][j] < threshold:
  35.                 im_arr[i][j] = 0
  36.             else:
  37.                 im_arr[i][j] = 255
  38.     nm_arr = im_arr.reshape([1, 784])
  39.     nm_arr = nm_arr.astype(np.float32)
  40.     img_ready = np.multiply(nm_arr, 1.0 / 255.0)
  41.     return img_ready

  42. def application():
  43.     testNum = int(input("input the number of test pictures:"))
  44.     for i in range(testNum):
  45.         testPic = input("the path of test picture:")
  46.         testPicArr = pre_pic(testPic)
  47.         preValue = restore_model(testPicArr)
  48.         print("The prediction number is:", preValue)

  49. def main():
  50.     application()

  51. if __name__ == "__main__":
  52.     main()

复制代码
-运行结果:
(1)警告信息:
  1. WARNING:tensorflow:From D:\卢天恩文件夹\3.编程\0.Tendsorflow学习\2.代码实践\手写数字识别\源代码\mnist_app.py:8: The name tf.disable_v2_behavior is deprecated. Please use tf.compat.v1.disable_v2_behavior instead.

  2. WARNING:tensorflow:From C:\Users\Administrator\AppData\Local\Programs\Python\Python311\Lib\site-packages\tensorflow\python\compat\v2_compat.py:98: disable_resource_variables (from tensorflow.python.ops.resource_variables_toggle) is deprecated and will be removed in a future version.
  3. Instructions for updating:
  4. non-resource variables are not supported in the long term
复制代码
(2)运行时无法查找节点,无法识别图片:
  1. input the number of test pictures:3
  2. the path of test picture:pic/3.jpg
  3. WARNING:tensorflow:From D:\卢天恩文件夹\3.编程\0.Tendsorflow学习\2.代码实践\手写数字识别\源代码\mnist_app.py:18: The name tf.train.Saver is deprecated. Please use tf.compat.v1.train.Saver instead.

  4. No checkpoint file found in ./model/
  5. The prediction number is: -1
  6. the path of test picture:pic/10.jpg
  7. No checkpoint file found in ./model/
  8. The prediction number is: -1
  9. the path of test picture:pic/4.jpg
  10. No checkpoint file found in ./model/
  11. The prediction number is: -1
复制代码


请求帮我看一下,可能是这四个文件都有问题,都互相关联,向前传播的过程没报错没结果,一段时间就退出了,向后传播和优化训练都会卡死
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2024-4-30 07:28:15 | 显示全部楼层
问题可能出在两个地方:

1. TensorFlow版本不兼容:
首先,你提到的这些代码是基于TensorFlow 1.x版本编写的,而你可能在使用TensorFlow 2.x版本。在TensorFlow 2.x版本中,一些API和函数名称发生了变化,所以代码可能无法正常运行。

解决方法:
将`import tensorflow.compat.v1 as tf`替换为`import tensorflow as tf`,然后将所有使用`tf.compat.v1`前缀的函数和类名改为使用`tf`即可。

2. 模型文件缺失或路径错误:
在`mnist_app.py`文件中,你尝试从模型文件中恢复模型权重以进行预测。可能是由于模型文件丢失或路径设置不正确,导致无法找到模型文件。

解决方法:
确保模型文件`.ckpt`位于指定的模型保存路径`MODEL_SAVE_PATH`下,并且命名为`mnist_model.ckpt`。另外,请确保`mnist_test.py`文件中的`TEST_INTERVAL_SECS`变量设置的时间足够长,以允许模型训练完成并生成模型文件。

针对以上问题的解决方法,你可以按照以下步骤进行:

步骤1:修改`mnist_forward.py`文件
将代码中的`get_weight`和`get_bias`函数的实现修改如下:

  1. def get_weight(shape, regularizer):
  2.     w = tf.Variable(tf.random.truncated_normal(shape, stddev=0.1))
  3.     if regularizer != None:
  4.         tf.add_to_collection("losses", tf.keras.regularizers.l2(regularizer)(w))
  5.     return w

  6. def get_bias(shape):
  7.     b = tf.Variable(tf.zeros(shape))
  8.     return b
复制代码


步骤2:修改`mnist_test.py`文件
将代码中的`test`函数和`main`函数的实现修改如下:

  1. def test(mnist):
  2.     x = tf.placeholder(tf.float32, shape=(None, mnist_forward.INPUT_NODE))
  3.     y_ = tf.placeholder(tf.float32, shape=(None, mnist_forward.OUTPUT_NODE))
  4.     y = mnist_forward.forward(x, None)

  5.     ema = tf.train.ExponentialMovingAverage(mnist_backward.MOVING_AVERAGE_DECAY)
  6.     ema_restore = ema.variables_to_restore()
  7.     saver = tf.train.Saver(ema_restore)

  8.     correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
  9.     accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

  10.     while True:
  11.         latest_checkpoint = tf.train.latest_checkpoint(mnist_backward.MODEL_SAVE_PATH)
  12.         if latest_checkpoint:
  13.             with tf.compat.v1.Session() as sess:
  14.                 saver.restore(sess, latest_checkpoint)
  15.                 global_step = int(latest_checkpoint.split("-")[-1])
  16.                 accuracy_score = sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels})
  17.                 print("After %d training step(s), test accuracy = %g" % (global_step, accuracy_score))
  18.         else:
  19.             print("No checkpoint file found")
  20.             return

  21. def main():
  22.     mnist = tf.keras.datasets.mnist
  23.     (x_train, y_train), (x_test, y_test) = mnist.load_data()
  24.     x_test = x_test.reshape(-1, mnist_forward.INPUT_NODE) / 255.0
  25.     y_test = tf.keras.utils.to_categorical(y_test, mnist_forward.OUTPUT_NODE)
  26.     mnist.test = tf.data.Dataset.from_tensor_slices((x_test, y_test)).batch(10000)
  27.     test(mnist)

  28. if __name__ == "__main__":
  29.     main()
复制代码


步骤3:修改`mnist_app.py`文件
将代码中的`restore_model`函数和`pre_pic`函数的实现修改如下:

  1. def restore_model(testPicArr):
  2.     with tf.Graph().as_default() as g:
  3.         x = tf.placeholder(tf.float32, shape=(None, mnist_forward.INPUT_NODE))
  4.         y = mnist_forward.forward(x, None)
  5.         preValue = tf.argmax(y, 1)

  6.         variable_averages = tf.train.ExponentialMovingAverage(mnist_backward.MOVING_AVERAGE_DECAY)
  7.         variables_to_restore = variable_averages.variables_to_restore()
  8.         saver = tf.train.Saver(variables_to_restore)

  9.         with tf.compat.v1.Session(graph=g) as sess:
  10.             latest_checkpoint = tf.train.latest_checkpoint(mnist_backward.MODEL_SAVE_PATH)
  11.             if latest_checkpoint:
  12.                 saver.restore(sess, latest_checkpoint)
  13.                 preValue = sess.run(preValue, feed_dict={x: [testPicArr]})
  14.                 return preValue[0]
  15.             else:
  16.                 print("No checkpoint file found in", mnist_backward.MODEL_SAVE_PATH)
  17.                 return -1

  18. def pre_pic(picName):
  19.     img = Image.open(picName).convert('L')
  20.     reIm = img.resize((28, 28), Image.LANCZOS)
  21.     im_arr = np.array(reIm)
  22.     threshold = 50
  23.     im_arr = np.where(im_arr < threshold, 0, 255)
  24.     nm_arr = im_arr.reshape(1, -1).astype(np.float32)
  25.     img_ready = nm_arr / 255.0
  26.     return img_ready

  27. def application():
  28.     testNum = int(input("input the number of test pictures:"))
  29.     for i in range(testNum):
  30.         testPic = input("the path of test picture:")
  31.         testPicArr = pre_pic(testPic)
  32.         preValue = restore_model(testPicArr)
  33.         print("The prediction number is:", preValue)

  34. def main():
  35.     application()

  36. if __name__ == "__main__":
  37.     main()
复制代码


最后,确保所有的模型文件和图片路径都正确设置,然后尝试运行代码。希望这些修改能够解决你的问题!如果还有其他问题,请随时提问。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-5-22 21:42

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表