• Numpy学习


    决定陆陆续续写一些Numpy的例子。。

    1.

    如果想表示e的x次,就可以这样用,下面直接写一个sigmod函数:

    def sigmoid(z):
        return 1 / (1 + np.exp(-z))

    2.

    numpy也可以来进行矩阵运算

    最简单的如下:

    ①、首先是一位数组之间的相乘

    import random
    d1 = np.arange(9)
    random.shuffle(d1)
    d2 = np.arange(9)
    random.shuffle(d2)
    print(d1,'
    ',d2)

    #
    [5 2 8 0 1 7 6 4 3] 
    [1 6 5 3 4 8 0 7 2]

    产生两个维度一样的数组,顺便复习一下random的用法

    接下来

    np.dot(d1,d2)
    
    #151

    也就是向量的内积

    ②、接下来是矩阵的相乘,先产生两个矩阵,一个2乘3,一个3乘4

    d1 = np.arange(1,7).reshape(2,3)
    d2 = np.arange(2,14).reshape(3,4)
    print(d1,' ','-'*10,' ',d2)



    #[[1 2 3]
     [4 5 6]] 
     ---------- 
     [[ 2  3  4  5]
     [ 6  7  8  9]
     [10 11 12 13]]
    np.dot(d1,d2)

    #
    array([[ 44,  50,  56,  62],
           [ 98, 113, 128, 143]])

    得到2乘4的矩阵,注意这里d1和d2的顺序一旦相反,矩阵相乘的结果也不一样了

    3.

    这个例子我们讲一下用pandas和numpy共同对数据进行处理

    首先我们的数据是这样子的:

    import os
    import numpy as np
    import pandas as pd
    path = 'data' + os.sep + 'LogiReg_data.txt'
    pdData = pd.read_csv(path, header=None, names=['Exam 1', 'Exam 2', 'Admitted'])
    pdData.head()

    我们需要的操作是:给数据增加一列全为1(加在第一列),然后分为X和Y两部分,其中X是一个三行100列(数据一共100个样本)的矩阵,第一列是1,第二列是Exam1,第二列是Exam2,Y是一个列向量,也就是Admitted,好了,开始操作:

    pdData.insert(0, 'Ones', 1) # in a try / except structure so as not to return an error if the block si executed several times
    
    # set X (training data) and y (target variable)
    orig_data = pdData.as_matrix() # convert the Pandas representation of the data to an array useful for further computations
    cols = orig_data.shape[1]
    X = orig_data[:,0:cols-1]
    y = orig_data[:,cols-1:cols]
    
    # convert to numpy arrays and initalize the parameter array theta
    #X = np.matrix(X.values)
    #y = np.matrix(data.iloc[:,3:4].values) #np.array(y.values)
    theta = np.zeros([1, 3])

    第一行代码就是给原数据第一列加上名称为'Ones’且值全为1的列,如果要删除,需要这样:

    pdData.drop('Ones', axis=1,inplace=True #其中inplace的值为True代表对原数据进行了改动,而如果不加inpalce或者为False,则表示将删除结果作为另外的返回值,原数组没有变化

    第二行代码表示将pandas的这个数据转为numpy里的数组,也就是

    numpy.ndarray
    第三行代码表示取数组里第二维度的大小,也就是列的大小(0是行)
    接下来的代码应该不用解释了吧,看一下数据的结果:
    X[:5]
    
    #array([[ 1.        , 34.62365962, 78.02469282],
           [ 1.        , 30.28671077, 43.89499752],
           [ 1.        , 35.84740877, 72.90219803],
           [ 1.        , 60.18259939, 86.3085521 ],
           [ 1.        , 79.03273605, 75.34437644]])
    y[:5]
    
    #array([[0.],
           [0.],
           [0.],
           [1.],
           [1.]])
    theta
    
    #array([[ 0.,  0.,  0.]])
    人生苦短,何不用python
  • 相关阅读:
    函数式编程语言
    Http
    小解_beginthreadex与_beginthreadex和CreateThread的区别
    Ring0句柄表遍历
    异步读写(ReadFileEx和ReadFile)之overlapped
    异步读写之利用完成历程
    windows核心编程第17章 一个文件两个缓存
    windows核心编程第17章 一个文件一个缓存
    windows核心编程第17章 一个文件 0个缓存
    进程间通信之利用CreateFilemapping()
  • 原文地址:https://www.cnblogs.com/yqpy/p/9538987.html
Copyright © 2020-2023  润新知