美文网首页我爱编程
机器学习实战 chapter2 笔记

机器学习实战 chapter2 笔记

作者: 慢慢喜欢学习 | 来源:发表于2018-03-31 20:02 被阅读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)

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

相关文章

  • 机器学习实战 chapter2 笔记

    Numpy包 mat( )函数可以将数组转化为矩阵 randMat=mat(random.rand(4,4)) ....

  • 机器学习实战-knn

    机器学习实战笔记-knn算法实战 本文内容源于《机器学习实战》一书,主要介绍了knn(k-nearest neig...

  • 思维导图

    《机器学习实战》思维导图 过完书后可以查漏补缺,温故知新。 《机器学习实战》读书笔记

  • 机器学习实战之KNN算法

    本系列教程为《机器学习实战》的读书笔记。首先,讲讲写本系列教程的原因:第一,《机器学习实战》的代码由Python2...

  • 机器学习实战(一)

    学习笔记(机器学习实战:基于Scikit-Learn和TensorFlow) 材料(代码示例、练习题等)可在此链接...

  • K-Means算法

    参考链接:1. python机器学习实战之K均值聚类2. 机器学习实战之K-Means算法3.《机器学习实战》(十...

  • 机器学习实战中文版 pdf高清+源代码

    机器学习实战中文版 pdf高清+源代码 《机器学习实战》介绍并实现机器学习的主流算法,面向日常任务的高效实战内容,...

  • 机器学习实战-学习笔记

    AiLearning之机器学习基础总结 Logsitic回归 sigmoid阶跃函数: Tanh函数:sigmoi...

  • python之k-近邻算法(非sklearn版)

    为了能够熟悉不能机器学习算法的原理,所以在此将学习《机器学习实战》这本书的笔记给记录下来,因为此书使用python...

  • 课程学习笔记(一)环境搭建、回归问题等

    本篇学习笔记总结自唐宇迪老师的《【决胜AI系列】机器学习&深度学习系统实战》。 1.环境搭建——Anaconda在...

网友评论

    本文标题:机器学习实战 chapter2 笔记

    本文链接:https://www.haomeiwen.com/subject/djomxftx.html