- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我是 TensorFlow 的新手。我得到了 mnist 训练样本,我想通过生成检查点来测试图像。我引用了 Tensorflow 文档并生成了检查点,并尝试通过访问 softmax 层来测试样本图像。但是给定图像 number-9 softmax 给了我一个无效的单热编码数组,如 'array([[ 0., 1., 0., 0., 0., 0., 0., 0., 0., 0.] ], dtype=float32)',当我尝试使用
访问 softmax 时softmax = graph.get_tensor_by_name('SOFTMAX:0')。
我尝试使用不同的图像进行测试,但没有给出任何正确的结果。
1.我假设,softmax 会给我一系列概率。我是对的吗?
2.我是否正确保存模型?
3.我是否访问了正确的层来测试输入?
4.我的测试/训练代码中还有什么需要添加的吗?
很抱歉在这里发布所有内容。
这是我的火车代码:
from __future__ import division, print_function, unicode_literals
import tensorflow as tf
from time import time
import numpy as np
import os
import scipy.ndimage as ndimage
from scipy import misc
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
logs_train_dir = '/home/test/Logs'
def weight_variable(shape,name):
initial = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(initial,name=name+'_weight')
def bias_variable(shape,name):
initial = tf.constant(0.1, shape=shape)
return tf.Variable(initial,name=name+'_bias')
def conv2d(x, W):
return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
def max_pool_2x2(x,name):
return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME',name=name+'_max_pool')
# correct labels
y_ = tf.placeholder(tf.float32, [None, 10])
# reshape the input data to image dimensions
x = tf.placeholder(tf.float32, [None, 784],name='X')#Input Tensor
x_image = tf.reshape(x, [-1, 28, 28, 1],name='X_Image')
# build the network
W_conv1 = weight_variable([5, 5, 1, 32],'W_conv1')
b_conv1 = bias_variable([32],'b_conv1')
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1,name='h_conv1')
h_pool1 = max_pool_2x2(h_conv1,'h_pool1')
W_conv2 = weight_variable([5, 5, 32, 64],'W_conv2')
b_conv2 = bias_variable([64],'b_conv2')
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2,name='h_conv2')
h_pool2 = max_pool_2x2(h_conv2,'W_conv2')
W_fc1 = weight_variable([7 * 7 * 64, 1024],name='wc1')
b_fc1 = bias_variable([1024],name='b_fc1')
h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)
keep_prob = tf.placeholder(tf.float32,name='KEEP_PROB')
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
W_fc2 = weight_variable([1024, 10],name='w_fc2')
b_fc2 = bias_variable([10],name='b_fc2')
y_conv=tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2,name='SOFTMAX')#Softmax Tensor
# define the loss function
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y_conv), reduction_indices=[1]),name='CROSS_ENTROPY')
loss_summary = tf.summary.scalar('loss_sc',cross_entropy)
# define training step and accuracy
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1),name='CORRECT_PRED')
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32),name='ACCURACY')
accuracy_summary = tf.summary.scalar('accuracy_sc', accuracy)
# create a saver
saver = tf.train.Saver()
# initialize the graph
init = tf.global_variables_initializer()
summary_op = tf.summary.merge_all()
sess = tf.Session()
train_writer = tf.summary.FileWriter(logs_train_dir, sess.graph)
sess.run(init)
# train
print("Startin Burn-In...")
for i in range(500):
input_images, correct_predictions = mnist.train.next_batch(50)
if i % 100 == 0:
train_accuracy = sess.run(accuracy, feed_dict={x: input_images, y_: correct_predictions, keep_prob: 1.0})
print("step %d, training accuracy_a %g" % (i, train_accuracy))
sess.run(train_step, feed_dict={x: input_images, y_: correct_predictions, keep_prob: 0.5})
print("Starting the training...")
start_time = time()
for i in range(20000):
input_images, correct_predictions = mnist.train.next_batch(50)
if i % 100 == 0:
train_accuracy = sess.run(accuracy, feed_dict={x: input_images, y_: correct_predictions, keep_prob: 1.0})
print("step %d, training accuracy_b %g" % (i, train_accuracy))
sess.run(train_step, feed_dict={x: input_images, y_: correct_predictions, keep_prob: 0.5})
summary_str = sess.run(summary_op,feed_dict={x: input_images, y_: correct_predictions, keep_prob: 0.5})
train_writer.add_summary(summary_str, i)
print('SAVING CHECKPOINTS......i is ',i)
if i % 1000 == 0 or (i+1) == 20000:
checkpoint_path = os.path.join(logs_train_dir,'cnn_new_model.ckpt')
print('checkpoint_path is ',checkpoint_path)
saver.save(sess,checkpoint_path,global_step=i)
print("The training took %.4f seconds." % (time() - start_time))
# validate
print("test accuracy %g" % sess.run(accuracy, feed_dict={
x: mnist.test.images,
y_: mnist.test.labels,
keep_prob: 1.0}))
准确度为 0.97。
这是我的测试代码:
import numpy as np
import tensorflow as tf
import scipy.ndimage as ndimage
from scipy import misc
import cv2 as cv
def get_test_image():
image = cv.imread('/home/test/Downloads/9.png', 0)
resized = cv.resize(image, (28,28), interpolation = cv.INTER_AREA)
image = np.array(resized)
flat = np.ndarray.flatten(image)
reshaped_image = np.reshape(flat,(1, 784))
return reshaped_image
def evaluate_one_image():
image_array = get_test_image()
image_array = image_array.astype(np.float32)
logs_train_dir ='/home/test/Logs'
model_path = logs_train_dir+"/cnn_new_model.ckpt-19999"
detection_graph = tf.Graph()
with tf.Session(graph=detection_graph) as sess:
# Load the graph with the trained states
loader = tf.train.import_meta_graph(model_path+'.meta')
loader.restore(sess, model_path)
# Get the tensors by their variable name
image_tensor = detection_graph.get_tensor_by_name('X:0')
softmax = detection_graph.get_tensor_by_name('SOFTMAX:0')
keep_prob = detection_graph.get_tensor_by_name('KEEP_PROB:0')
# Make prediction
softmax = sess.run(softmax, feed_dict={image_tensor: image_array,keep_prob:0.75})
print('softmax is ', cost_val,'\n\n')
print('softmax maximum val is ', np.argmax(cost_val))
evaluate_one_image()
因此,当我使用数字 9 的图像进行测试时,它给出了以下输出:
softmax 为 [[ 0., 1., 0., 0., 0., 0., 0., 0., 0., 0.]]
softmax 最大值为 1
我不知道我哪里出了问题。任何帮助都会非常有用,并且非常感激。
最佳答案
在评估/预测期间不使用 Dropout。所以你需要设置 keep_prob=1
检查输入图像image_array
的像素值,像素值应在[0, 1]
范围内,否则需要对像素进行归一化减去图像均值并除以图像标准差的值
对于加载图像的功能,您可以添加以下行来标准化
def get_test_image():
...
image = np.array(resized)
mean = image.mean()
std = image.std()
image = np.subtract(image, mean)
image = np.divide(image, std)
image = np.clip(image, 0, 1.000001)
...
关于python - 使用检查点在 Tensorflow Mnist 模型上测试图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45782031/
我想将模型及其各自训练的权重从 tensorflow.js 转换为标准 tensorflow,但无法弄清楚如何做到这一点,tensorflow.js 的文档对此没有任何说明 我有一个 manifest
我有一个运行良好的 TF 模型,它是用 Python 和 TFlearn 构建的。有没有办法在另一个系统上运行这个模型而不安装 Tensorflow?它已经经过预训练,所以我只需要通过它运行数据。 我
当执行 tensorflow_model_server 二进制文件时,它需要一个模型名称命令行参数,model_name。 如何在训练期间指定模型名称,以便在运行 tensorflow_model_s
我一直在 R 中使用标准包进行生存分析。我知道如何在 TensorFlow 中处理分类问题,例如逻辑回归,但我很难将其映射到生存分析问题。在某种程度上,您有两个输出向量而不是一个输出向量(time_t
Torch7 has a library for generating Gaussian Kernels在一个固定的支持。 Tensorflow 中有什么可比的吗?我看到 these distribu
在Keras中我们可以简单的添加回调,如下所示: self.model.fit(X_train,y_train,callbacks=[Custom_callback]) 回调在doc中定义,但我找不到
我正在寻找一种在 tensorflow 中有条件打印节点的方法,使用下面的示例代码行,其中每 10 个循环计数,它应该在控制台中打印一些东西。但这对我不起作用。谁能建议? 谢谢,哈米德雷萨, epsi
我想使用 tensorflow object detection API 创建我自己的 .tfrecord 文件,并将它们用于训练。该记录将是原始数据集的子集,因此模型将仅检测特定类别。我不明白也无法
我在 TensorFlow 中训练了一个聊天机器人,想保存模型以便使用 TensorFlow.js 将其部署到 Web。我有以下内容 checkpoint = "./chatbot_weights.c
我最近开始学习 Tensorflow,特别是我想使用卷积神经网络进行图像分类。我一直在看官方仓库中的android demo,特别是这个例子:https://github.com/tensorflow
我目前正在研究单图像超分辨率,并且我设法卡住了现有的检查点文件并将其转换为 tensorflow lite。但是,使用 .tflite 文件执行推理时,对一张图像进行上采样所需的时间至少是使用 .ck
我注意到 tensorflow 的 api 中已经有批量标准化函数。我不明白的一件事是如何更改训练和测试之间的程序? 批量归一化在测试和训练期间的作用不同。具体来说,在训练期间使用固定的均值和方差。
我创建了一个模型,该模型将 Mobilenet V2 应用于 Google colab 中的卷积基础层。然后我使用这个命令转换它: path_to_h5 = working_dir + '/Tenso
代码取自:- http://adventuresinmachinelearning.com/python-tensorflow-tutorial/ import tensorflow as tf fr
好了,所以我准备在Tensorflow中运行 tf.nn.softmax_cross_entropy_with_logits() 函数。 据我了解,“logit”应该是概率的张量,每个对应于某个像素的
tensorflow 服务构建依赖于大型 tensorflow ;但我已经成功构建了 tensorflow。所以我想用它。我做这些事情:我更改了 tensorflow 服务 WORKSPACE(org
Tensoflow 嵌入层 ( https://www.tensorflow.org/api_docs/python/tf/keras/layers/Embedding ) 易于使用, 并且有大量的文
我正在尝试使用非常大的数据集(比我的内存大得多)训练 Tensorflow 模型。 为了充分利用所有可用的训练数据,我正在考虑将它们分成几个小的“分片”,并一次在一个分片上进行训练。 经过一番研究,我
根据 Sutton 的书 - Reinforcement Learning: An Introduction,网络权重的更新方程为: 其中 et 是资格轨迹。 这类似于带有额外 et 的梯度下降更新。
如何根据条件选择执行图表的一部分? 我的网络有一部分只有在 feed_dict 中提供占位符值时才会执行.如果未提供该值,则采用备用路径。我该如何使用 tensorflow 来实现它? 以下是我的代码
我是一名优秀的程序员,十分优秀!