1. 程式人生 > >k-近鄰演算法--使用k-近鄰演算法識別手寫數字

k-近鄰演算法--使用k-近鄰演算法識別手寫數字

listdir函式:

os.listdir() 方法用於返回指定的資料夾包含的檔案或資料夾的名字的列表。返回指定路徑下的檔案和資料夾列表。

python文件:

listdir(path=None)
    Return a list containing the names of the files in the directory.
    
    path can be specified as either str or bytes.  If path is bytes,
      the filenames returned will also be bytes; in all other circumstances
      the filenames returned will be str.
    If path is None, uses the path='.'.
    On some platforms, path may also be specified as an open file descriptor;\
      the file descriptor must refer to a directory.
      If this functionality is unavailable, using it raises NotImplementedError.
    
    The list is in arbitrary order.  It does not include the special
    entries '.' and '..' even if they are present in the directory.

舉個栗子:

這就是我用listdir然後查獲我的python_work資料夾中的目錄,裡面的檔案型別還挺複雜的。但是資料夾名是無後綴的,但其他檔案都是由字尾的,比如py、txt等。返回值是一個列表,檔名均已字串的形式體現。

zeros函式

功能挺簡單的,就是根據自己設定的形狀和資料型別構建一個零矩陣。我估計ones之類的應該差不多。

python文件為:

zeros(...)
    zeros(shape, dtype=float, order='C')
    
    Return a new array of given shape and type, filled with zeros.
    
    Parameters
    ----------
    shape : int or sequence of ints
        Shape of the new array, e.g., ``(2, 3)`` or ``2``.
    dtype : data-type, optional
        The desired data-type for the array, e.g., `numpy.int8`.  Default is
        `numpy.float64`.
    order : {'C', 'F'}, optional
        Whether to store multidimensional data in C- or Fortran-contiguous
        (row- or column-wise) order in memory.
    
    Returns
    -------
    out : ndarray
        Array of zeros with the given shape, dtype, and order.
    
    See Also
    --------
    zeros_like : Return an array of zeros with shape and type of input.
    ones_like : Return an array of ones with shape and type of input.
    empty_like : Return an empty array with shape and type of input.
    ones : Return a new array setting values to one.
    empty : Return a new uninitialized array.
    
    Examples
    --------
    >>> np.zeros(5)
    array([ 0.,  0.,  0.,  0.,  0.])
    
    >>> np.zeros((5,), dtype=int)
    array([0, 0, 0, 0, 0])
    
    >>> np.zeros((2, 1))
    array([[ 0.],
           [ 0.]])
    
    >>> s = (2,2)
    >>> np.zeros(s)
    array([[ 0.,  0.],
           [ 0.,  0.]])


    >>> np.zeros((2,), dtype=[('x', 'i4'), ('y', 'i4')]) # custom dtype
    array([(0, 0), (0, 0)],
          dtype=[('x', '<i4'), ('y', '<i4')])

我再寫幾個示例:

為什麼第二個例子錯了,是因為函式預設第二個引數指的是型別。跟我們的本意相違背了。所以應該再4,5外圍再加上一層括號才對

這樣函式才會把(4,5)識別成形狀

下面貼上一下我剛剛憑著自己的理解寫出的程式碼: