当我打印一个numpy数组时,我得到一个截断的表示,但我想要完整的数组.
有没有办法做到这一点?
例子:
>>> numpy.arange(10000)
array([ 0, 1, 2, ..., 9997, 9998, 9999])
>>> numpy.arange(10000).reshape(250,40)
array([[ 0, 1, 2, ..., 37, 38, 39],
[ 40, 41, 42, ..., 77, 78, 79],
[ 80, 81, 82, ..., 117, 118, 119],
...,
[9880, 9881, 9882, ..., 9917, 9918, 9919],
[9920, 9921, 9922, ..., 9957, 9958, 9959],
[9960, 9961, 9962, ..., 9997, 9998, 9999]])
Run Code Online (Sandbox Code Playgroud) 我有一个浮点数组,我已经规范化为一个(即数组中最大的数字是1),我想用它作为图形的颜色索引.在使用matplotlib来使用灰度时,这需要使用0到1之间的字符串,所以我想将浮点数组转换为字符串数组.我试图通过使用"astype('str')"来做到这一点,但这似乎创造了一些与原件不同(甚至接近)的值.
我注意到这一点,因为matplotlib抱怨在数组中找到数字8,这很奇怪,因为它被归一化为1!
简而言之,我有一个float64的数组phis,这样:
numpy.where(phis.astype('str').astype('float64') != phis)
Run Code Online (Sandbox Code Playgroud)
是非空的.这是令人费解的(希望天真)它似乎是一个numpy的错误,有什么我可以做错导致这个?
编辑:调查后,这似乎是由于字符串函数处理高精度浮点数的方式.使用向量化的toString函数(从robbles回答),情况也是如此,但是如果lambda函数是:
lambda x: "%.2f" % x
Run Code Online (Sandbox Code Playgroud)
然后图形工作 - curiouser和curiouser.(显然,阵列不再相等!)
我有一个二维numpy数组,看起来像这样:
[[a b c]
[d e f]
[g h i]]
Run Code Online (Sandbox Code Playgroud)
我想打印它没有通常带有阵列的任何默认的符号绒毛; 即[,]和元素之间的空间.像这样的东西:
abc
def
ghi
Run Code Online (Sandbox Code Playgroud)
是否有可能做这样的事情(当然没有一个微不足道的,可能是昂贵的Python循环)?
我看过numpy.set_printoptions但看起来它只设置元素显示方式的表示选项,而不是两者之间的字符.
编辑:阵列中的元件具有字符串表示,可以是任何东西,包括[,]和空白.如何构建这样一个数组的最小例子:
class custom(object):
def __repr__(self):
return 'a'
a = numpy.empty((5, 5), custom)
a.fill(custom())
print a
Run Code Online (Sandbox Code Playgroud) 我尝试在keras博客文章中运行代码。
该代码将写入.npy文件,如下所示:
bottleneck_features_train = model.predict_generator(generator, nb_train_samples // batch_size)
np.save(open('bottleneck_features_train.npy', 'w'),bottleneck_features_train)
Run Code Online (Sandbox Code Playgroud)
然后从该文件读取:
def train_top_model():
train_data = np.load(open('bottleneck_features_train.npy'))
Run Code Online (Sandbox Code Playgroud)
现在我得到一个错误,说:
Found 2000 images belonging to 2 classes.
Traceback (most recent call last):
File "kerasbottleneck.py", line 103, in <module>
save_bottlebeck_features()
File "kerasbottleneck.py", line 69, in save_bottlebeck_features
np.save(open('bottleneck_features_train.npy', 'w'),bottleneck_features_train)
File "/opt/anaconda3/lib/python3.6/site-packages/numpy/lib/npyio.py", line 511, in save
pickle_kwargs=pickle_kwargs)
File "/opt/anaconda3/lib/python3.6/site-packages/numpy/lib/format.py", line 565, in write_array
version)
File "/opt/anaconda3/lib/python3.6/site-packages/numpy/lib/format.py", line 335, in _write_array_header
fp.write(header_prefix)
TypeError: write() argument must be str, not bytes
Run Code Online (Sandbox Code Playgroud)
之后,我尝试将文件模式从“ w”更改为“ wb”。这导致在读取文件时出错: …