Python && 機器學習基礎

Python && 機器學習基礎

numpy

numpy 的數據結構

  • import numpy:引入numpy庫
  • numpy.genfromtxt() : 使用numpy打開一個txt文件
  • print(help(numpy.genfromtxt)): 打印genfromtxt()的幫助文檔
  • numpy.array(): 數組結構
    • numpy.array([8, 3, 7, 1]): 創建一維數組
    • numpy.array([[2, 5, 3],[12, 6, 76]]): 創建二維數組
    • numpy.array()屬性:
      • .shape->顯示array的維度;
      • .dtype ->顯示array中的數據類型
      • numpy.array[1, 4]: 取出第一行第四列的元素(index從0開始計算)
      • numpy.array(xxx)[0:3]: 取向量的前三個值(切片,左閉右開)
      • numpy.array(xxx)[ : , 3]: 取多維向量所有樣本的第三個值
      • array中的元素類型要統一,否則numpy會將值的類型自動轉換

numpy的基本操作

  1. 當進行 +-*/==!= 等邏輯判斷時,numpy會對array中所有元素進行判斷。
import numpy
vector = numpy.array([5,10,6,7])
vector == 10
#output: array([False, true, False, False], dtype = bool) 
  1. numpy.array()的判定結果可以被當成是index,從而取得結果爲true的值。
import numpy
vector = numpy.array([2,6,10,9])
#將結果爲true的結果的index賦值給ten變量
ten = (vector == 10)
print(vector[ten])
#output:[10]
  1. &| 邏輯運算
  2. 類型轉換
    • .astype(float):轉換成float類型
  3. 最大值和最小值
    • .min()
    • .max()
  4. 求和
    • .sum(axis = 1): 按行求和,.axis = 0 則按列求和
  5. 矩陣變換
    • .reshape(r, c): reshape the array to r rows and c columns.
  6. 矩陣維度
    • .ndim:輸出矩陣的維度
  7. 矩陣大小
    • .size: 返回矩陣中的元素個數。

矩陣操作

numpy.zeros((a,b)):創建一個 a 行 b 列的 0 矩陣

#創建一個起始值爲10,終止值爲20,步長爲2的矩陣
numpy.arange(10,20,2)
#output:array([10, 12, 14, 16, 18])
#生成2行3列的隨機矩陣,元素值在+1和-1之間
#random.random():在random模塊下使用random函數
numpy.random.random((2,3))
#output:array([[ 0.25712849,  0.52280068,  0.37931522],[ 0.37061583,  0.66376507,  0.33100993]])

.linespace(a, b, c):在起始值 a 與終點值 b 之間平均得到 c 個元素。
**n:取n次方
A*B: 矩陣A和B求內積, 對應項相乘
A.dot(B): 矩陣的點乘
numpy. dot(A, B): 同A.dot(B)

numpy的常用函數

  • numpy.exp(A): 對矩陣A求指數函數
  • numpy.sqrt(A):對矩陣A求根
  • numpy.floor():向下取整
  • A.ravel(): 將A矩陣變換成一個向量
  • A.T: 取矩陣A的轉置
  • numpy.vstack((A,B)):將A和B按照行進行拼接
  • numpy.hstack((A,B)):將A和B按照列進行拼接
  • numpy.hsplit(A,3): 將A矩陣按照列平均分成3份
  • numpy.vsplit(A,3): 將A矩陣按照行平均分成3份
  • numpy.vsplit(A,(3,4)): Split A after 3rd and 4th row
  • numpy.hsplit(A,(3,4)): Split A after 3rd and 4th column

  • array的複製

    • A=B: 將B複製給A, 複製之後A和B的id相同, AB共用一種數據
    • A=B.view(): 將B複製給A, 複製之後A和B的id不同, 但是AB仍然共用一組數據
    • A = B.copy():將B複製給A, 複製之後A和B的id不同, AB不共用一組數據
  • .argmax(axis=0):返回當前array每一行最大的元素的index
  • .argmax(axis=1):返回當前array每一列最大的元素的index
  • .tile(): 複製粘貼
  • A.sort(axis=0):對A的每一行進行從小到大的排序
  • numpy.argsort(A): 按照索引值進行排序

pandas

pandas主要用於數據的處理

pandas數據選擇
  • pandas.read_csv("food_info.csv"): 讀取csv文件
  • .head(n):得到數據的前n行
  • .tail(n): 得到數據的尾n行
  • .columns: 返回列名
  • .shape: 返回行列數
  • .loc[n]: 取得第n行數據
#通過列名索引,得到列的切片
ndb_col = food_info("NDB_NO")
#在food_info文件中查找名稱爲"NDB_NO"的列並返回
  • .endwith(): 取得特定結尾的行
pandas數據類型
  • object: For String values
  • int: For integer values
  • float: For float values
  • datetime: For time values
  • bool: for boolean values
pandas數據預處理
  • .sort_values("column", inplace=True): 以column列爲基準進行排序, inplace= True即新生成結果, 不會替換原有結果, 默認爲升序排列
  • .sort_values("column", inplace=True ascending = False): 同上, 但是爲降序排列
  • .isnull(): 判斷是否有缺失值
  • len():統計個數
  • .mean():求平均值, 忽略缺失值
  • pivot_table(index="basic standard", values="statistic", aggfunc= way): 以 basic standard爲基準, 通過way的方式統計 statistic 數據, aggfunc默認爲mean
  • dropna(axis = 1):去掉指定列的缺失值樣本
  • .apply():執行一個自定義的函數, 用於調用函數
def hundredth_row(column):
    #Extract the hundredth item
    hundredth_item = column.loc[99]
    return hundredth_item

hundredth_row = titanic_survival.apply(hundredth_row)
print hundredth_row

Matplotlib

Matplotlib畫折線圖
imoprt pandas
#import the pyplot library in matplotlib
import matplotlib.pyplot as plot
#read the .csv file
unrate = pandas.read_csv('unrate.csv')
#transfer the DATE column in .csv file to datetime version by using the function to_datetime
unrate['DATE'] = pandas.to_datetime(unrate['DATE'])
#plot nothing
plot.plot()
#show the canvas
plot.show()
figure = unrate[0: 12]
plot.plot(figure['DATE'], figure['VALUE'])
plot.show()
plot.xticks(rotation = 45)

.plot(x , y): 畫折線圖, 以 x 參數爲 x 軸, 以 y 參數爲 y 軸
.xticks(rotation = XX): 變換座標的角度, 轉換XX角度
xlable('XXXX'): add lable to x-axis which indicates the name of x - axis
ylable('XXXX'): add lable to y-axis which indicates the name of y - axis
.title('XXXX'): add the title to the whole chart

Matplotlib 畫子圖

.add_subplot(r, c, x): 添加 r 行, c 列個子圖, 並選擇第 x 個子圖畫圖
figure(figsize = (3,3)):指定子圖的長和寬
.plot(x, y, c='', lable = label): c 參數指定畫出折現的color, 當需要在同一個子圖中華多個折線時, 只需要 plot 多次即可, 使用lable參數爲每個單獨的折線添加label, 但是此時label並不會立即顯示
.legend(loc = 'XXX'): 將plot中的label顯示在折線圖的XXX位置

Matplotlib散點圖和柱形圖
  1. 柱形圖
    .bar(position, height, width):生成柱形圖, 以positon作爲柱形圖中每個柱離遠點的距離, 以height作爲每個柱的高度, width作爲每個柱的寬度
    .barh(position, height, width):畫橫向柱形圖
  2. 散點圖
    .scatter(x,y): x作爲x軸參數, y作爲y軸參數畫散點圖
Matplotlib柱形圖與盒圖
  1. 柱形圖
    .hist(XXX, bins= ): 畫出區間數量爲bins的柱形圖, bins的默認值爲10
    .set_ylim(a,b):設定y軸的區間爲[a: b]
  2. 盒圖
    boxplot():畫盒圖
Matplotlib細節設置

tick_param(bottom="", top="", left="", right=""):去掉軸標線
(a/255, b/255, c/255):獲取值爲abc的顏色參數

Reference

以上內容, 摘自
http://edu.csdn.net/course/play/6108/114224

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章