码迷,mamicode.com
首页 > 编程语言 > 详细

python机器学期的常用库

时间:2018-09-18 00:18:03      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:dimens   传递   参数   对象   complex   内存   shape   lex   机器   

Numpy:
  标准Python的列表(list)中,元素本质是对象。
  如:L = [1, 2, 3],需要3个指针和三个整数对象,对于数值运算比较浪费内存和CPU,因此才有了Numpy中的ndarray
  因此,Numpy提供了ndarray(N-dimensional array object)对象:存储单一数据类型的多维数组。
 1.使用array创建

通过array函数传递list对象
  L = [1, 2, 3, 4, 5, 6]
  print "L = ", L
  a = np.array(L)
  print "a = ", a
  print type(a)     # 此时a为 numpy的ndarray类型

 若传递的是多层嵌套的list,将创建多维数组
  b = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
  print b  # 此时b为二维数组
数组大小可以通过其shape属性获得
  print a.shape  # (6L,)

  print b.shape  #(3L, 4L)

也可以强制修改shape
  b.shape = 4, 3
  print b
  # # # 注:从(3,4)改为(4,3)并不是对数组进行转置,而只是改变每个轴的大小,数组元素在内存中的位置并没有改变

 当某个轴为-1时,将根据数组元素的个数自动计算此轴的长度
  b.shape = 2, -1
  print b
  print b.shape
b.shape = 3, 4
使用reshape方法,可以创建改变了尺寸的新数组,原数组的shape保持不变
  c = b.reshape((4, -1))
  print "b = \n", b
  print ‘c = \n‘, c
数组b和c共享内存,修改任意一个将影响另外一个
  b[0][1] = 20
  print "b = \n", b
  print "c = \n", c

  注:c,和 b指向的是同意内存空间的数组,因此修改b会影响c
数组的元素类型可以通过dtype属性获得
  print a.dtype
  print b.dtype
可以通过dtype参数在创建时指定元素类型
  d = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]], dtype=np.float)
  f = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]], dtype=np.complex)
  print d
  print f
如果更改元素类型,可以使用astype安全的转换
  f = d.astype(np.int)
  print f
不要强制仅修改元素类型,如下面这句,将会以int来解释单精度float类型
  d.dtype = np.int
  print d


  

python机器学期的常用库

标签:dimens   传递   参数   对象   complex   内存   shape   lex   机器   

原文地址:https://www.cnblogs.com/bianjing/p/9665531.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!