机器学习实战 chapter2 笔记

Numpy包

mat( )函数可以将数组转化为矩阵

randMat=mat(random.rand(4,4))

.I表示求逆

randMat.I

from numpy import *

import operator

tile用法:

Signature: tile(A, reps)Docstring:

Construct an array by repeating A the number of times given by reps.

If `reps` has length ``d``, the result will have dimension of

``max(d, A.ndim)``.

If ``A.ndim < d``, `A` is promoted to be d-dimensional by prepending new

axes. So a shape (3,) array is promoted to (1, 3) for 2-D replication,

or shape (1, 1, 3) for 3-D replication. If this is not the desired

behavior, promote `A` to d-dimensions manually before calling this

function.

If ``A.ndim > d``, `reps` is promoted to `A`.ndim by pre-pending 1's to it.

Thus for an `A` of shape (2, 3, 4, 5), a `reps` of (2, 2) is treated as

(1, 1, 2, 2).

Note : Although tile may be used for broadcasting, it is strongly

recommended to use numpy's broadcasting operations and functions.

Parameters

----------

A : array_like

The input array.

reps : array_like

The number of repetitions of `A` along each axis.

Returns

-------

c : ndarray

The tiled output array.

See Also

--------

repeat : Repeat elements of an array.

broadcast_to : Broadcast an array to a new shape

Examples

--------

>>> a = np.array([0, 1, 2])

>>> np.tile(a, 2)

array([0, 1, 2, 0, 1, 2])

>>> np.tile(a, (2, 2))

array([[0, 1, 2, 0, 1, 2],

[0, 1, 2, 0, 1, 2]])

>>> np.tile(a, (2, 1, 2))

array([[[0, 1, 2, 0, 1, 2]],

[[0, 1, 2, 0, 1, 2]]])

>>> b = np.array([[1, 2], [3, 4]])

>>> np.tile(b, 2)

array([[1, 2, 1, 2],

[3, 4, 3, 4]])

>>> np.tile(b, (2, 1))

array([[1, 2],

[3, 4],

[1, 2],

[3, 4]])

>>> c = np.array([1,2,3,4])

>>> np.tile(c,(4,1))

array([[1, 2, 3, 4],

[1, 2, 3, 4],

[1, 2, 3, 4],

[1, 2, 3, 4]])

File:      d:\anaconda3\lib\site-packages\numpy\lib\shape_base.py

Type:      function

argsort用法:

Signature: argsort(a, axis=-1, kind='quicksort', order=None)Docstring:

Returns the indices that would sort an array.

Perform an indirect sort along the given axis using the algorithm specified

by the `kind` keyword. It returns an array of indices of the same shape as

`a` that index data along the given axis in sorted order.

Parameters

----------

a : array_like

Array to sort.

axis : int or None, optional

Axis along which to sort.  The default is -1 (the last axis). If None,

the flattened array is used.

kind : {'quicksort', 'mergesort', 'heapsort'}, optional

Sorting algorithm.

order : str or list of str, optional

When `a` is an array with fields defined, this argument specifies

which fields to compare first, second, etc.  A single field can

be specified as a string, and not all fields need be specified,

but unspecified fields will still be used, in the order in which

they come up in the dtype, to break ties.

Returns

-------

index_array : ndarray, int

Array of indices that sort `a` along the specified axis.

If `a` is one-dimensional, ``a[index_array]`` yields a sorted `a`.

See Also

--------

sort : Describes sorting algorithms used.

lexsort : Indirect stable sort with multiple keys.

ndarray.sort : Inplace sort.

argpartition : Indirect partial sort.

Notes

-----

See `sort` for notes on the different sorting algorithms.

As of NumPy 1.4.0 `argsort` works with real/complex arrays containing

nan values. The enhanced sort order is documented in `sort`.

Examples

--------

One dimensional array:

>>> x = np.array([3, 1, 2])

>>> np.argsort(x)

array([1, 2, 0])

Two-dimensional array:

>>> x = np.array([[0, 3], [2, 2]])

>>> x

array([[0, 3],

[2, 2]])

>>> np.argsort(x, axis=0)

array([[0, 1],

[1, 0]])

>>> np.argsort(x, axis=1)

array([[0, 1],

[0, 1]])

Sorting with keys:

>>> x = np.array([(1, 0), (0, 1)], dtype=[('x', '

>>> x

array([(1, 0), (0, 1)],

dtype=[('x', '

>>> np.argsort(x, order=('x','y'))

array([1, 0])

>>> np.argsort(x, order=('y','x'))

array([0, 1])

File:      d:\anaconda3\lib\site-packages\numpy\core\fromnumeric.py

Type:      function

 operator.itemgetter:

Init signature: operator.itemgetter(self, /, *args, **kwargs)Docstring:

itemgetter(item, ...) --> itemgetter object

Return a callable object that fetches the given item(s) from its operand.

After f = itemgetter(2), the call f(r) returns r[2].

After g = itemgetter(2, 5, 3), the call g(r) returns (r[2], r[5], r[3])

File:           d:\anaconda3\lib\operator.py

Type:           type

sorted:

Signature: sorted(iterable, /, *, key=None, reverse=False)Docstring:

Return a new list containing all items from the iterable in ascending order.

A custom key function can be supplied to customize the sort order, and the

reverse flag can be set to request the result in descending order.

Type:      builtin_function_or_method

 classCount={}

花括号表示字典

    for i in range(3):

        voteIlabel = labels[sortedDistIndicies[i]]

        classCount[voteIlabel] = classCount.get(voteIlabel,0)+1

AttributeError: 'dict' object has no attribute 'iteritems'

Python3.5中:iteritems变为items

===============

文件读取

def file2matrix(filename):

    fr = open(filename)

    arrayOlines=fr.readlines()

    numberOfLines = len(arrayOlines)

    returnMat = zeros((numberOfLines,3))

    classLabelVector = []

    index = 0

    for line in arrayOlines:

        line = line.strip()

        listFromLine = line.split('\t')

        returnMat[index,:]=listFromLine[0:3]

        classLabelVector.append(int(listFromLine[-1]))

        index += 1

    return returnMat,classLabelVector

line = line.strip():截掉回车符

==================================

使用Matplotlib制作原始数据的散点图:

import matplotlib

import matplotlib.pyplot as plt

fig = plt.figure()

ax = fig.add_subplot(111)

ax.scatter(datingDataMat[:,1],datingDataMat[:,2])

plt.show()

=========

ax.scatter(datingDataMat[:,1],datingDataMat[:,2],15.0*array(datingLabels),15.0*array(datingLabels))

使区分

==============================

def autoNorm(dataSet):

    minVals = dataSet.min(0)

    maxVals = dataSet.max(0)

    ranges = maxVals - minVals

    normDataSet = zeros(shape(dataSet))

    m = dataSet.shape[0]

    normDataSet = dataSet - tile(minVals, (m,1))

    normDataSet = normDataSet/tile(ranges,(m,1))

    return normDataSet,ranges,minVals

============

normDataSet = normDataSet/tile(ranges,(m,1))不是矩阵除法,在NumPy库中,矩阵除法需要使用函数linalg.solve(matA,matB)

========

reload:

import importlib

importlib.reload(kNN)

=================================

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,242评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,769评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,484评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,133评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,007评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,080评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,496评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,190评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,464评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,549评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,330评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,205评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,567评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,889评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,160评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,475评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,650评论 2 335

推荐阅读更多精彩内容