Numpy學習
阿新 • • 發佈:2018-08-27
struct src 最簡 fur -- 二維 兩個 matrix pandas
決定陸陸續續寫一些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,‘\n‘,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,‘\n‘,‘-‘*10,‘\n‘,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.]])
Numpy學習