跳到主要內容

Python Study (2) - Concept

 
  • Study travel beginning
       Execute your first code Hollow World
        >>> print("Hollow World")
         Hollow World


    Python's core Data Type
           We understand  data type before studying any program. Python has built-in object types


    Data Type(Object type) Example
    Numbers int, float, long, complex
    Strings  
    Lists  
    Dictionaries  
    Tuples  
    Files  
    Sets set, frozenset
    Primitive types boolean,
    Program unit types Functions, modules, classes
    Implementation-related types compiled code, stack tracebacks


    1. Number
        Example: real number, float, double ...
    >>> 333 + 555
        888
    >>> 333 / 111
       3.0
    >>> 333 * 9
       2997
    >>> "happy " * 2 + " birthday"
       'happy happy  birthday'

    Module : math and random
    >>> import math
    >>> math.pi
    3.141592653589793
    >>> import random
    >>> random.random()
    0.7082048489415967
    >>> random.choice([2,4,6,8])
    4
    Note : intelligent complement => tab

     

    2. String
    (1) String is a array of char

    >>> S = 'Money'
    >>> S[0]
    'M'
    >>> S[-1]
    'y'
    >>> S[0:-1]
    'Mone'
    >>> len(S)
    5
    >>> S[:]
    'Money'
    >>> S[1:]
    'oney'
    >>> S[:3]
    'Mon'

    (2) Unicode String
    https://docs.python.org/2/howto/unicode.html.
    Unicode is a computing industry standard for the consistent encoding, representation and handling of text expressed.Python’s strings also come with full Unicode support  required for processing text in internationalized character sets.
     
    Python 2.X  
         In python 2.X, All Strings represent a collection of bytes, Python is default ASCII
         script. If you want change non-ASCII script for the script, you need put first line
         to declare encoding declaration.
       
         * Use Python Script edit the code and run . Ref: Use IDLE
          
         The length of the string is not 2 but rather 4, because each chinese word
         contain 2 bytes. len() function return length of bytes
       

    # coding=big5
    text = "哈囉"   #The word is a Chinese word than meas "hello"
    print len(text)

    4  # the result after run


        What does it happen when use encoding declaration. The result return 2 length
        of the string.

    # coding=big5   #encoding declaration
    text = u"哈囉"      #python 2.x use “u” to represent Unicode
    print len(text)

    2  # the result after run

     
         Note:  Python 2.x need to declarate encoding declaration.
         Both 3.X and 2.X use  “\x” hexadecimal  and  “\u” to represent Unicode

    >>> text = u’哈囉’
    >>> text
    u'\xab\xa2\xc5o'

     


    Python 3.x        
        Python 3.x all strings are unicode encode.

    text = "哈囉"   #The word is a Chinese word than meas "hello"
    print(len(text))

    4  # the result after run
              

    Encode and decode

    function description example
    unichr(int ) return unicode

    >>> unichr(80)
    u'P'

    chr(int ) return integer

    >>> chr(80)
    'P'

    ord(str ) return ASCII or Unicode

    >>> ord(u'A')
    65

    encode(str) return encode string >>>
    decode(str) return decode string  
    unicode return unicode string  

    (3) Pattern Matching
    Module : re


    >>>import re
              

    3. Lists
    Lists are ordered arbitrary collection of objects and they have no fixed size.they are sequence objetcs

    >>> L = ["toast", 10, "toast with egg", 12.5, "toast with ham", 15]
    >>> len(L)
    6

    >>> L[0:2]
    ['toast', 10]

    >>>L[:-1]
    ['toast', 10, 'toast with egg', 12.5, 'toast with ham']

    >>>L + ["toast with vegetable", 20]
    ['toast', 10, 'toast with egg', 12.5, 'toast with ham', 15, 'toast with vegetable', 20]
              
    List functions
    function description example
    append add object at end of list >>> L.append(“toast with vegetable”)
    >>> L
    ['toast', 10, 'toast with egg', 12.5, 'toast with ham', 15, 'toast with vegetable']
    pop get object and remove >>> L.pop(-1)
    >>> L
    ['toast', 10, 'toast with egg', 12.5, 'toast with ham', 15]
    sort sort

    >>> M = ["Banana","Apple","Orange"]
    >>> M.sort()
    >>> M
    ['Apple', 'Banana', 'Orange']

    reverse  

    >>> M.reverse()
    >>> M
    ['Orange', 'Banana', 'Apple']

    keys return keys of the list  
    values return values of the list  

    List Arrary

    >>> L= [ [ 'toast','toast with egg','toast with ham','toast with vegetable'],
             [10,12.5,15,20]]
    >>> L[0]
    ['toast', 'toast with egg', 'toast with ham', 'toast with vegetable']

    >>> [row[1] for row in L]
    ['toast with egg', 12.5]
              
    range(int) : A built-in function is used to generate integers

    >>>List(range(5))
    [0,1,2,3,4]

    >>>for i in range(4):
                print(i)

    0
    1
    3
    4

    >>> list(range(1,4))
    [1,2,3]

    >>> list(range(1,8,2))
    [1, 3, 5, 7]
              
    map(function, iterable, ...) : map is a build-in function. Apply function to every item of iterable and return a list of the results.


    >>>List(range(5))

    >>> list1 = [1,2,3]
    >>> list2 = [1,2,3]
    >>> def sum(a,b):
        return a+b

    >>> list(map(sum, list1, list2))  #python 3.x use a list to store map 
    [2, 4, 6]
    >>>

              

    Dictionaries
    (1) kye/value
    (2) sequence


    >>> food = {"toast": 10, "toast with egg": 13.5, "toast with ham":15}
    >>> food["toast with egg"]
    13.5

    >>> food["toast with egg"]+=1
    >>> food["toast with egg"]
    14.5

    >>> food["toast with vegetable"] = 20
    >>> food["toast with vegetable"]
    20

              
    Dictionaries function

    dict : It is a name=value format and make dictionaries

    >>> newfood = dict(toast=15, toast_with_egg=20, toast_with_ham=25)}>>> newfood[toast_with_egg]
    Traceback (most recent call last):
      File "<pyshell#19>", line 1, in <module>
        newfood[toast_with_egg]
    NameError: name 'toast_with_egg' is not defined


    >>> newfood["toast_with_egg"]
    20

              

    zip :
    function :  zip([key1, key2, key3….], [value1, value2, value3…])

    >>>  dict(zip(['toast','toast with egg','toast with ham'],[10,12.5,15]))
    >>> newfood2["toast"]
    10

              
    build-in function

    >>> food= [ [ 'toast','toast with egg','toast with ham','toast with vegetable'],
             [10,12.5,15,20]]

            
    function description example
    keys show keys of the list

    >>> food.keys()
    ['toast', 'toast with ham', 'toast with vegetable', 'toast with egg']

    sort sort value of the list

    >>> foodMoney = list(food.values())
    >>> foodMoney.sort()
    >>> foodMoney
    [10, 14.5, 15, 20]

    values get values of the list

    >>> foodMoney = list(food.values())
    >>> foodMoney
    [10, 15, 20, 14.5]

    reverse  

    >>> foodMoney = list(food.values())
    >>> foodMoney.reverse()
    >>> foodMoney
    [20, 15, 14.5, 10]

       


    Tuples
    (1) sequence
    (2) fixed size
    (3) immutable (when the tuple is created, it connot be changed)

    >>> fruit = ("apple","organe","grape","banana")
    >>> fruit
    ('apple', 'organe', 'grape', 'banana')

    >>> fruit[0]
    'apple'

              
    built-in function

    >>> fruit = ("apple","organe","grape","banana")
    >>> fruit
    ('apple', 'organe', 'grape', 'banana')

    >>> fruit[0] = "tomato"
    Traceback (most recent call last):
      File "<pyshell#86>", line 1, in <module>
        fruit[0] = "tomato"
    TypeError: 'tuple' object does not support item assignment

              
    function description example
    index(object) return index of the tuple

    >>> fruit.index("banana")
    3

    count(object) return times of appear object in the tuple

    >>> fruit.count("apple")
    1









     

  • 留言

    這個網誌中的熱門文章

    淺談機器學習原理-Nonlinear Transform

    Nonlinear Transform 淺談機器學習原理-Nonlinear Transform Nonlinear Transform *通用能力 gerneralization : 就是將訓練好的模型,放到正式環境可以正常的運作,通常Linear Model的gerneralization會比較好,因為線性模型解決的問題比較單純。缺點是應用侷限比較大。 參考Chih-Chung Chang老師的範例:縣性與非線性分類範例 https://www.csie.ntu.edu.tw/~cjlin/libsvm/ 非線性問題 當如果今天假設要圈出裡面小圈圈的資料,我們就無法使用線性的模型,我們可以用非線性解像圈圈的方程式 s i g n ( − x 1 2 − x 2 2 + r ) sign(-x1^2-x2^2+r) s i g n ( − x 1 2 − x 2 2 + r ) 來解決,在演算法我們利用reduce來將不會的問題透過已知的問題來解決,所以在這個問題 我們將圈圈的方程式(非線性模型)reduce成線性模型來解決。 Reduce 方法論 我們調整圓形的方程式改為 z 0 z_0 z 0 ​ , z 1 z_1 z 1 ​ , z 2 z_2 z 2 ​ 來轉換線性方程式, { ( x n , y n ) } \{{(x_n,y_n)}\} { ( x n ​ , y n ​ ) } => { ( z n , y n ) } \{{(z_n,y_n)}\} { ( z n ​ , y n ​ ) } 在這空間資料中只要能找線,就可將不同的分類區分,圖中可以線性可以線去做分類。 透過向量方式來轉換成線性方程式 我們找到一個方式將非線性資料X透過向量轉換為Z後,希望透過線性方程式方式來學習,得到正解。 當我們Nonlinear transform轉換成線性方程式,當有新的資料進來我們無法使用invertiable(逆向工程)的方式去轉回非線...

    Python AI-問題集

    Python AI-問題集 問題集 Jupyter Notebook執行ipywidgets會出現kernel死掉的錯誤發生(The kernel appears to have died) 解決方法 (1) 根據log檔來判斷問題: 例如:log訊息出現OMP: Error #15: Initializing libiomp5.dylib, but found libiomp5.dylib already initialized. (2) 根據問題關鍵字找出問題所在: 利用google查詢所遭遇到的問題,例如我把上面的問題上google查詢可以找到這篇的解法 https://blog.csdn.net/bingjianIT/article/details/86182096 (3)實作解法: 我實作下面解法後,就可以順利執行手寫辨識的程式. //在Python宣告時加入 import os os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE" 參考 https://blog.csdn.net/bingjianIT/article/details/86182096

    淺談機器學習原理-Linear Model

    Linear Regession 淺談機器學習原理-Linear Model Linear Regession 需要預測數值,輸出為實數的數值,我們就稱為它是regession的任務。 範例:Netflix百萬獎金比賽,有100萬筆的rating資料與480K的使用者給17.7k的電影來評分,預測使用者評分電影的星星*數量。 (1) 定義問題是否需要使用ML : 預測使用者評分電影的星星*數量,算是一個複雜的問題。且知道評分結果為1~5星,可以知道這是一個regression的任務 (2) 收集資料 : Netflix有100萬筆的rating資料與 (3) 定義模型 :假設它是regession問題,我們可以知道hypothesis: h(x) = w T ∗ x w^T *x w T ∗ x 的方程式。我們可以與分類Perceptron的公式來比較。 Linear Regession :用來找到最接近實際目標值,也就是最小誤差error的值 (4) 測量誤差 : squared error : ( 預測值 − 真實的值 ) 2 (預測值-真實的值)^2 ( 預測值 − 真實的值 ) 2 ,我們算出誤差值後,如何得到最小的誤差min(Error(x)) 理想化的誤差值 我們可以假設誤差接近於0值為球體的位置,是在曲線的最下方也就是偏微分等於0的位置,我們要找的讓W偏微分等於零。 Statistics vs Machine Learning Statistics: 統計比較著重在數學的推論 Machine Learning: 機器學習比較著重在資料計算,統計工具對機器學習領域是很有幫助 Logistic Regression 邏輯回歸 需要預測機率,輸出為小數點,我們就稱為它Logistic Regression任務。資料輸出為+1,-1的值,可以預測為機率發生,可以由公式可以知道x在發生+1的機率是多少。範例: 疾病預測、鐵達尼的死完的機率 機...