我爱编程

机器学习实战 chapter2 笔记

2018-03-31  本文已影响0人  慢慢喜欢学习

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)

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

上一篇下一篇

猜你喜欢

热点阅读