第十四章
14.0- - - 14.11(神经网络基础待编辑)
14.16 编写一个 NumPy 程序,根据查询数组array1和array2之间的公有值,并打印结果。
np.intersect1d(array1, array2))
14.17 numpy找到数组的唯一元素
#np.unique可以很容易地找到数组中唯一的元素。
a = np.array([11, 11, 12, 13, 14, 15, 16, 17, 12, 13, 11, 14, 18, 19, 20])
unique_values = np.unique(a)
print(unique_values)
#解:
[11 12 13 14 15 16 17 18 19 20]
要获取NumPy数组中唯一值的索引(数组中唯一值的第一个索引位置的数组),只需在np.unique()中传递return_index参数:
np.unique(a, return_index=True)
14.18 numpy保存数组到csv
#使用np.savetxt()存数据到本地,使用np.loadtxt()从本地文件读取。
#其中np.savetxt()和np.loadtxt()函数可配置的参数如下:
numpy.savetxt(fname, X, fmt='%.18e', delimiter=' ', newline='\n', header='', footer='', comments='# ', encoding=None)
numpy.loadtxt(fname, dtype=<type 'float'>, comments='#', delimiter=None, converters=None, skiprows=0, usecols=None, unpack=False, ndmin=0)
#文件中的数据小数点后保留太多位,使得数据看起来很凌乱,可以使用格式控制参数‘fmt’进行控制,比如小数点后保留3位。
np.savetxt(r'test.txt', x, fmt='%.3e')
#数据后面还跟着‘e+00’字符,可将此字符串去掉,以浮点数存储,fmt=’%.3f’;也可以整数格式存储,fmt=’%d’。
np.savetxt(r'test.txt', x, fmt='%.3f') # 保留3位小数
np.savetxt(r'test.txt', x, fmt='%d') # 整数
#delimiter参数:每列数据之间的分割符号,默认为空格
#可以使用任何字符,例如使用竖线 ‘|’ 分割,百分号 ‘%’ 分割,任意字符串‘abc’分割。
np.savetxt(r'test.txt', x, fmt='%d', delimiter='|')
np.savetxt(r'test.txt', x, fmt='%d', delimiter='%%')
np.savetxt(r'test.txt', x, fmt='%d', delimiter='abc')
#newline参数:每行数据之间的分割符,默认换行
#随便使用一个字符串‘-|-’作为行分割符,其中列数据之间使用默认的空格作为分割符。
np.savetxt(r'test.txt', x, fmt='%d', newline='-|-')
#header和footer参数:在文件头和文件尾增加的说明语句
np.savetxt(r'test.txt', x, fmt='%d', header='this is begin of arrry data!', footer='this is end of arrry data!')
14.19 numpy查看数组内存大小
print(f"{n.size * n.itemsize} bytes")
14.19 numpy加新维度
np.newaxis 的功能是增加新的维度,但是要注意 np.newaxis 放的位置不同,产生的矩阵形状也不同。
np.newaxis 放在哪个位置,就会给哪个位置增加维度
用途:通常用它将一维的数据转换成一个矩阵,这样就可以与其他矩阵进行相乘。
#修改给定数组arr的形状为(28,28),并增加一个维度(1,28,28)。
import numpy as np
arr = np.arange(784)
print(arr.shape)
arr = arr.reshape((28, 28))
print(arr.shape)
arr = arr[np.newaxis, :, :]
print(arr.shape)