Python: DeprecationWarning: elementwise == 比较失败; 这将在未来引发错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44574679/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python: DeprecationWarning: elementwise == comparison failed; this will raise an error in the future
提问by Arslan Thobani
While trying out the udacity course deep learning assignment, I came across a problem with comparing the predictions of my model with the labels of training set
在尝试 udacity 课程深度学习作业时,我遇到了将模型的预测与训练集的标签进行比较的问题
from __future__ import print_function
import numpy as np
import tensorflow as tf
from six.moves import cPickle as pickle
from six.moves import range
pickle_file = 'notMNIST.pickle'
with open(pickle_file, 'rb') as f:
save = pickle.load(f)
train_dataset = save['train_dataset']
train_labels = save['train_labels']
valid_dataset = save['valid_dataset']
valid_labels = save['valid_labels']
test_dataset = save['test_dataset']
test_labels = save['test_labels']
del save # hint to help gc free up memory
print('Training set', train_dataset.shape, train_labels.shape)
print('Validation set', valid_dataset.shape, valid_labels.shape)
print('Test set', test_dataset.shape, test_labels.shape)
This gives output as:
Training set (200000, 28, 28) (200000,)
Validation set (10000, 28, 28) (10000,)
Test set (10000, 28, 28) (10000,)
输出如下:
训练集 (200000, 28, 28) (200000,)
验证集 (10000, 28, 28) (10000,)
测试集 (10000, 28, 28) (10000,)
# With gradient descent training, even this much data is prohibitive.
# Subset the training data for faster turnaround.
train_subset = 10000
graph = tf.Graph()
with graph.as_default():
# Input data.
# Load the training, validation and test data into constants that are
# attached to the graph.
tf_train_dataset = tf.constant(train_dataset[:train_subset, :])
tf_train_labels = tf.constant(train_labels[:train_subset])
tf_valid_dataset = tf.constant(valid_dataset)
tf_test_dataset = tf.constant(test_dataset)
# Variables.
# These are the parameters that we are going to be training. The weight
# matrix will be initialized using random values following a (truncated)
# normal distribution. The biases get initialized to zero.
weights = tf.Variable(
tf.truncated_normal([image_size * image_size, num_labels]))
biases = tf.Variable(tf.zeros([num_labels]))
# Training computation.
# We multiply the inputs with the weight matrix, and add biases. We compute
# the softmax and cross-entropy (it's one operation in TensorFlow, because
# it's very common, and it can be optimized). We take the average of this
# cross-entropy across all training examples: that's our loss.
logits = tf.matmul(tf_train_dataset, weights) + biases
loss = tf.reduce_mean(
tf.nn.softmax_cross_entropy_with_logits(labels=tf_train_labels, logits=logits))
# Optimizer.
# We are going to find the minimum of this loss using gradient descent.
optimizer = tf.train.GradientDescentOptimizer(0.5).minimize(loss)
# Predictions for the training, validation, and test data.
# These are not part of training, but merely here so that we can report
# accuracy figures as we train.
train_prediction = tf.nn.softmax(logits)
valid_prediction = tf.nn.softmax(
tf.matmul(tf_valid_dataset, weights) + biases)
test_prediction = tf.nn.softmax(tf.matmul(tf_test_dataset, weights) + biases)
num_steps = 801
def accuracy(predictions, labels):
return (100.0 * np.sum(np.argmax(predictions, 1) == np.argmax(labels, 1))
/ predictions.shape[0])
with tf.Session(graph=graph) as session:
# This is a one-time operation which ensures the parameters get initialized as
# we described in the graph: random weights for the matrix, zeros for the
# biases.
tf.global_variables_initializer().run()
print('Initialized')
for step in range(num_steps):
# Run the computations. We tell .run() that we want to run the optimizer,
# and get the loss value and the training predictions returned as numpy
# arrays.
_, l, predictions = session.run([optimizer, loss, train_prediction])
if (step % 100 == 0):
print('Loss at step %d: %f' % (step, l))
print('Training accuracy: %.1f%%' % accuracy(
predictions, train_labels[:train_subset, :]))
# Calling .eval() on valid_prediction is basically like calling run(), but
# just to get that one numpy array. Note that it recomputes all its graph
# dependencies.
print('Validation accuracy: %.1f%%' % accuracy(
valid_prediction.eval(), valid_labels))
print('Test accuracy: %.1f%%' % accuracy(test_prediction.eval(), test_labels))
it outputs:
它输出:
C:\Users\Arslan\Anaconda3\lib\site-packages\ipykernel_launcher.py:5: DeprecationWarning: elementwise == comparison failed; this will raise an error in the future. """
C:\Users\Arslan\Anaconda3\lib\site-packages\ipykernel_launcher.py:5: DeprecationWarning: elementwise == 比较失败;这将在未来引发错误。"""
And it gives the accuracy as 0% for all datasets.
I think we cannot compare the arrays using '=='.
Any help would be appreciated
它为所有数据集提供了 0% 的准确度。我认为我们不能使用“==”来比较数组。
任何帮助,将不胜感激
回答by hpaulj
I assume the error occurs in this expression:
我假设错误发生在这个表达式中:
np.sum(np.argmax(predictions, 1) == np.argmax(labels, 1))
can you tell us something about the 2 arrays, predictions
, labels
? The usual stuff - dtype, shape, some sample values. Maybe go the extra step and show the np.argmax(...)
for each.
你能告诉我们一些关于2个阵列,predictions
,labels
?通常的东西 - dtype,形状,一些示例值。也许多走一步并显示np.argmax(...)
每个。
In numpy
you can compare arrays of the same size, but it has become pickier about comparing arrays that don't match in size:
在numpy
你可以比较相同大小的数组,但它已成为有关比较不中大小相匹配阵列挑剔:
In [522]: np.arange(10)==np.arange(5,15)
Out[522]: array([False, False, False, False, False, False, False, False, False, False], dtype=bool)
In [523]: np.arange(10)==np.arange(5,14)
/usr/local/bin/ipython3:1: DeprecationWarning: elementwise == comparison failed; this will raise an error in the future.
#!/usr/bin/python3
Out[523]: False
回答by Christian Morbidoni
I solved this by upgrading python to 3.6.4 (latest)
我通过将 python 升级到 3.6.4(最新)解决了这个问题
conda update python