【发布时间】:2020-12-29 02:11:28
【问题描述】:
我一直认为x /= y 等于x = x / y。但是现在我面临的情况是,当我使用/= 时会出错,但在使用x = x / y 时不会出错。所以绝对它们在 python 中不应该是一样的。
代码是这样的。 (是 Tensorflow 中的一个简单的深度学习代码,阅读代码 cmets 了解一些细节)。
import tensorflow as tf
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.fashion_mnist.load_data()
# x_train is a (60000, 28, 28) numpy matrix
x_train /= 1 # this will raise error "ValueError: output array is read-only"
x_train = x_train / 1 # but this will work fine
ValueError Traceback (most recent call last) <ipython-input-44-fceb080f135a> in <module>() 1 ----> 2 x_train /= 1 ValueError: output array is read-only
我想问他们之间的区别。为什么我从/= 收到此错误?
【问题讨论】:
-
什么错误?请堆栈跟踪。一般来说,错误信息是不言自明的。
-
/=正在尝试进行 in-place 更改,该更改仅适用于可变值。x_train = x_train / 1正在将一个对 不同 不可变值的引用放入变量中。所以正如疯狂物理学家所说——错误信息本身可以很好地告诉你到底是什么问题。 -
为什么会有numpy标签?你不使用 tf 吗?
-
@MadPhysicist tf 使用 NumPy 并且 x_train 是一个 NumPy 数组。它写在代码的注释中。
-
有趣的事实:在
x=x/1的结果上调用x/=1可能会正常工作。