Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Activity
    wang-Jen
    @wang-Jen
    對xd
    Martin老師
    @tpemartin
    其他同學會嗎?
    wang-Jen
    @wang-Jen
    我後來按ENTER然後他就沒事了
    按完ENTER 他會自己跳出學號
    Martin老師
    @tpemartin
    但不應該出現params
    wang-Jen
    @wang-Jen
    然後就之後打都沒有params了
    Martin老師
    @tpemartin
    其他同學如果有相同問題,可以提出,我很好奇什麼狀況下它會出現。老師從沒遇到過
    Tim
    @TimIHsun
    [ dict_finStatement["公司名稱"][i]  for i in range(len(dict_finStatement["營業利益(損失)"] )) if dict_finStatement["營業利益(損失)"][i] < 0]
    Martin老師
    @tpemartin
    1. 找出損失的index
      ```
      profit=list(dict_finStatement.get( '營業利益(損失)').values())

    lossFirmKeys=[index for index in range(len(profit)) if profit[index]<0]

    
    2. 由index進去公司找出名稱

    index=lossFirmKeys[100]
    dict_finStatement.get('公司名稱')[index]
    dict_finStatement.get('公司名稱').get(index)

    [dict_finStatement.get('公司名稱').get(index) for index in lossFirmKeys]

    
    dictionary comprehension 呈現公司名稱:損失金額

    {dict_finStatement.get('公司名稱').get(index): list(dict_finStatement.get( '營業利益(損失)').values())[index] for index in lossFirmKeys}

    
    

    dict_finStatement.get( '營業利益(損失)').values()
    ```

    1. 找出損失的index
      ```{python}
      profit=list(dict_finStatement.get( '營業利益(損失)').values())

    lossFirmKeys=[index for index in range(len(profit)) if profit[index]<0]

    
    2. 由index進去公司找出名稱
    ```{python}
    index=lossFirmKeys[100]
    dict_finStatement.get('公司名稱')[index]
    dict_finStatement.get('公司名稱').get(index)
    
    [dict_finStatement.get('公司名稱').get(index) for index in lossFirmKeys]

    dictionary comprehension 呈現公司名稱:損失金額

    {dict_finStatement.get('公司名稱').get(index): list(dict_finStatement.get( '營業利益(損失)').values())[index] for index in lossFirmKeys}
    dict_finStatement.get( '營業利益(損失)').values()
    Martin老師
    @tpemartin

    listA=[1,2,[3,5]]
    listApart=listA[2]

    listDict=[
    {'A': 1, 'B': 2},
    {'A': 0, 'B': 8}
    ]
    listDictPart=listDict[0]

    只有當list/dictionary, 裡面的元素是單純的atomic types: float, string,....ect. 此時shallow copy無法影響原本的物件。
    Tim
    @TimIHsun
    lenList = list([])
    
    for i in range(len(danceInfo)):
         lenList.append(len(danceInfo[i]["showInfo"]))
    Tim
    @TimIHsun
    sumM = 0
    for i in range(len(M[0])):
        sumM += M[0][i]
    cleverice007
    @cleverice007
    a=list([])
    for i in M[0]:
    a.append(i)
    b=sum(a)
    b
    rickyliu7710
    @rickyliu7710
    a = 0
    for i in range(len(M[0])):
    a += M[0][i]
    print (a)
    cleverice007
    @cleverice007
    for i in range(len(M)):
    for j in M[i]:
    c.append(j)
    d=sum(a)
    d
    rickyliu7710
    @rickyliu7710
    a = 0
    for i in range(len(M)): #知道有幾row
    for j in range(len(M[i])): #取出第一個ROW
    a += M[i][j]
    print (a)
    cleverice007
    @cleverice007
    for i in range(len(M)):
    for j in M[i]:
    c.append(j)
    d=sum(c)
    d
    ningtraveo75
    @ningtraveo75
    a=0
    for i in range(len(covM)):    
        for j in range(len(covM[i])):
            if j<=i:
              a += covM[i][j]
    print(a)
    cleverice007
    @cleverice007

    for i in range(len(covM)):
    for j in range(len(covM[i])):
    if j<= i:
    e.append(covM[i][j])
    f=sum(e)

    f

    Martin老師
    @tpemartin

    Newton's method

    p=lambda x: x**3-x**2-1
    dp=lambda x: 3*x**2-2*x
    
    x0=1
    x1=x0-p(x0)/dp(x0)
    p(x1)
    
    x2=x1-p(x1)/dp(x1)
    p(x2)
    x=1
    if abs(p(x))>1e-10:
        x=x-p(x)/dp(x)
        p(x)
    
    if abs(p(x))>1e-10:
        x=x-p(x)/dp(x)
        p(x)
    
    if abs(p(x))>1e-10:
        x=x-p(x)/dp(x)
        p(x)
    
    if abs(p(x))>1e-10:
        x=x-p(x)/dp(x)
        p(x)
    x=1 
    while abs(p(x))>1e-10:
        x -= p(x)/dp(x)
        #p(x)
    
    x
    p(x)
    p=lambda x: x**3-x**2-1
    dp=lambda x: 3*x**2-2*x
    
    x=1 
    while abs(p(x))>1e-10:
        x -= p(x)/dp(x)
        #p(x)
    
    x
    p(x)
    p=lambda x: x**3-x**2-1
    dp=lambda x: 3*x**2-2*x
    
    x=1
    count=0 # safe guard to avoid infinite loops
    while abs(p(x))>1e-10 and count <= 100:
        x -= p(x)/dp(x)
        count += 1
        #p(x)
    
    x
    p(x)
    Martin老師
    @tpemartin
    $$
    Pt**\left[\begin{array}{c}
    F\\
    T\\
    T\\
    F
    \end{array}\right]=\left[\begin{array}{c}
    Pt**F\\
    Pt**T\\
    Pt**T\\
    Pt**F
    \end{array}\right]=\left[\begin{array}{c}
    Pt**0\\
    Pt**1\\
    Pt**1\\
    Pt**0
    \end{array}\right]
    $$
    Martin老師
    @tpemartin
    y=np.array([[2,3,4,6]]).T
    x=np.array([
    [1,1,1,1],
    [0,-2,4,7]
    ]
    ).T
    
    y
    x
    Tim
    @TimIHsun
    ((x.T@x)^-1)@x.T@y
    Martin老師
    @tpemartin
    def normalPdf(x,mean=0,sigma=1):
        z=-(((x-mean)/sigma)**2)/2
        pdfvalue=np.exp(z)/((2*np.pi*sigma**2)**(0.5))
        return(pdfvalue)
    Martin老師
    @tpemartin
    y=np.array([[2,3,4,6]]).T
    x=np.array([
    [1,1,1,1],
    [0,-2,4,7]
    ]
    ).T
    
    y
    x
    Martin老師
    @tpemartin

    Probability Mass Functions

    import scipy.stats as stat
    bin_1=stat.binom(n=100,p=0.1)
    bin_1.pmf(50)
    
    bin_3=stat.binom(n=100,p=0.3)
    bin_3.pmf(50)
    Martin老師
    @tpemartin
    Suppose there are only two possible p values: 0.1 and 0.3. What would be the likelihood value of a sample with 50 heads and 50 tails?
    import scipy.stats as stat
    bin_1=stat.binom(n=100,p=0.1)
    bin_1.pmf(50) # Likelihood(p=0.1)
    
    bin_3=stat.binom(n=100,p=0.3)
    bin_3.pmf(50) # Likelihood(p=0.3)
    Martin老師
    @tpemartin
    import numpy as np
    import matplotlib.pyplot as plt
    import pandas as pd
    import math # 用math.mathfunction:non vectorized function
    from numpy.random import default_rng
    # 8.8 randon number generator
    # g_rv = defaut_rng() # to initiate a generator object
    from scipy.linalg import inv, solve, det, eig
    Martin老師
    @tpemartin
    class linFamily:
        surname="林"
        def __init__(self,firstname,gender):
            self.firstname=firstname
            self.gender=gender
        def __repr__(self):
            return "我叫{a}{b}性別{c}".format(a=self.surname,b=self.firstname,c=self.gender)
    Martin老師
    @tpemartin
    from numpy.random import default_rng
    g_rv=default_rng(2019)
    
    # x=g_rv.standard_normal(size=100)
    # e=g_rv.standard_normal(size=100)
    (x,e)=g_rv.standard_normal(
      size=(2,100)
    )
    
    y=0.1*x+0.33*e
    x
    y
    from numpy.random import default_rng
    class oneHundredSample:
      g_rv=default_rng()
      (x,e)=g_rv.standard_normal(
          size=(2,100)
          )
      y=0.1*x+0.33*e
    Martin老師
    @tpemartin
    from numpy.random import default_rng
    class mySample:
      g_rv=default_rng()
    
      def __init__(self,sampleSize):
          self.sampleSize=sampleSize
          (self.x,self.e)=\
          self.g_rv.standard_normal(
            size=(2,self.sampleSize))
    
          self.y=0.1*self.x+0.33*self.e
    Martin老師
    @tpemartin
    from numpy.random import default_rng
    
    beta_coeficients = np.array(
    [0.2,0.3,-1.8]
    )
    sampleSize=500
    g_rv=default_rng()
    eX=g_rv.standard_normal(\
      size=(1+beta_coeficients.shape[0],\
      sampleSize)) # 產生1+numBeta x sampleSize的rv matrix
    e=eX[0,:]
    X=eX[1:,:]
    beta=beta_coeficients.reshape(
     1,beta_coeficients.shape[0])
    y=beta@X+e
    Martin老師
    @tpemartin
    def data(beta_coeficients,sampleSize):
        g_rv=default_rng()
        eX=g_rv.standard_normal(\
          size=(1+beta_coeficients.shape[0],\
          sampleSize)) # 產生1+numBeta x sampleSize的rv matrix
        e=eX[0,:]
        X=eX[1:,:]
        beta=beta_coeficients.reshape(
         1,beta_coeficients.shape[0])
        y=beta@X+e
    
        return (y,X)
    
    
    beta_coeficients = np.array(
    [0.2,0.3,-1.8]
    )
    sampleSize=500
    (y,X)=data(beta_coeficients,sampleSize)
    Martin老師
    @tpemartin
    class linearRegression:
        def dataGen(self,beta_coefficients, sampleSize):
            g_rv=default_rng()
            eX=g_rv.standard_normal(\
            size=(1+beta_coeficients.shape[0],\
                sampleSize)) # 產生1+numBeta x sampleSize的rv matrix
            e=eX[0,:]
            X=eX[1:,:]
            beta=beta_coeficients.reshape(
              1,beta_coeficients.shape[0])
            y=beta@X+e
            self.data=(y,X)
            return self
    beta_coefficients = np.array(
    [0.2,0.3,-1.8]
    )
    sampleSize=500
    lr1=linearRegression()
    lr1.dataGen(beta_coefficients,sampleSize)
    lr1=linearRegression() # 創新instance
    lr1.dataGen(beta_coefficients,sampleSize) # 使用dataGen instance method給予此instance data attribute
    Martin老師
    @tpemartin
    # two arguments to use: self.data testSize
    data=lr1.data
    testSize=0.3
    (y,X)=data
    sampleSize=y.shape[1]
    index=np.arange(sampleSize)
    np.random.shuffle(index)
    cutOff=round(testSize*sampleSize)
    testIndex=index[:cutOff]
    trainIndex=index[cutOff:]
    y_test=y[:,testIndex]
    y_train=y[:,trainIndex]
    X_test=X[:,testIndex]
    X_train=X[:,trainIndex]
    test_data=(y_test,X_test)
    train_data=(y_train,X_train)
    Martin老師
    @tpemartin
    class linearRegression:
        def dataGen(self,beta_coefficients, sampleSize):
            g_rv=default_rng()
            eX=g_rv.standard_normal(\
            size=(1+beta_coeficients.shape[0],\
                sampleSize)) # 產生1+numBeta x sampleSize的rv matrix
            e=eX[0,:]
            X=eX[1:,:]
            beta=beta_coeficients.reshape(
              1,beta_coeficients.shape[0])
            y=beta@X+e
            self.data=(y,X)
            return self
    
        def split(self,testSize):
            (y,X)=self.data
            sampleSize=y.shape[1]
            index=np.arange(sampleSize)
            np.random.shuffle(index)
            cutOff=round(testSize*sampleSize)
            testIndex=index[:cutOff]
            trainIndex=index[cutOff:]
            y_test=y[:,testIndex]
            y_train=y[:,trainIndex]
            X_test=X[:,testIndex]
            X_train=X[:,trainIndex]
            test_data=(y_test,X_test)
            train_data=(y_train,X_train)
            self.test_data=test_data
            self.train_data=train_data
            return self
    
    
    beta_coefficients = np.array(
    [0.2,0.3,-1.8]
    )
    sampleSize=500
    lr1=linearRegression() # 創新instance
    lr1.dataGen(beta_coefficients,sampleSize) # 使用dataGen instance method給予此instance data attribute
    lr1.split(0.3)
    回家完成fit, predict兩個instance methods:
    lr1.fit()
    # OLS
    #  self.betaHat
    
    lr1.predict()
    # self.mse
    Martin老師
    @tpemartin
    class linearRegression:
        def __init__(self,beta_coefficients,sampleSize,testSize):
            self.beta_coefficients=beta_coefficients
            self.sampleSize=sampleSize
            self.testSize=testSize
        def dataGen(self):
            beta_coefficients=self.beta_coefficients
            sampleSize=self.sampleSize
            g_rv=default_rng()
            eX=g_rv.standard_normal(\
            size=(1+beta_coefficients.shape[0],\
                sampleSize)) # 產生1+numBeta x sampleSize的rv matrix
            e=eX[0,:]
            X=eX[1:,:]
            beta=beta_coefficients.reshape(
              1,beta_coefficients.shape[0])
            y=beta@X+e
            self.data=(y,X)
        def split(self):
            testSize=self.testSize
            (y,X)=self.data
            sampleSize=y.shape[1]
            index=np.arange(sampleSize)
            np.random.shuffle(index)
            cutOff=round(testSize*sampleSize)
            testIndex=index[:cutOff]
            trainIndex=index[cutOff:]
            y_test=y[:,testIndex]
            y_train=y[:,trainIndex]
            X_test=X[:,testIndex]
            X_train=X[:,trainIndex]
            test_data=(y_test,X_test)
            train_data=(y_train,X_train)
            self.testSize=testSize
            self.test_data=test_data
            self.train_data=train_data
    Martin老師
    @tpemartin

    增加fit method

    ## 將lr1當self測試用
    (y, X)=lr1.train_data
    lr1.beta_hat=inv(X@X.T)@X@y.T
    lr1.yhat=lr1.beta_hat.T@X
    # define fitFun
    def fitFun(self):
        (y, X)=self.train_data
        self.beta_hat=inv(X@X.T)@X@y.T
        self.yhat=self.beta_hat.T@X
    
    linearRegression.fit=fitFun
    # 測試此method
    lr1.fit()
    
    ### => 將fit寫入class定義中
    Martin老師
    @tpemartin
    class inclassPractice:
        def __init__(self,date):
            self.date=date
        def __repr__(self):
            return "課堂練習:"+self.date.strftime("%Y-%m-%d")