Giter Club home page Giter Club logo

lectures-2019's Introduction

lectures-2019's People

Contributors

andersmunkn avatar andreasnoack avatar elben10 avatar jeppedruedahl avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

lectures-2019's Issues

How to substitute a function with its input, but keeping the derivative

Hi

We have run into a problem when solving our model. At one point we maximize and end up with an expression containing a function and the derivative of that function (something like: a + f'(x) + b/f(x) = 0). Then we want to substitute in the input of f(x), but keeping f'(x) as it is. Just using "subs" both f(x) and f'(x) gets substituted. We believe this is because python writes the derivative as d/dxf(x) and thus cannot distinguish between the two functions.
We have also tried to use "replace" and then indicating that only the last element should be replaced, but that does not work either.

Does anyone have a suggestion to what else we can try? :)

NameError when assigning a to b

I get a NameError when assigning b to a

>>> a = b
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'b' is not defined

How to submit dataproject? Group not on NumEconCopenhagen

Hi

In your mail from 27th of March it says:
3. Remember to get GitHub working before the last minute. See how to get your group repository in the bottom of lecture 5 (under "Group sign-up"). Additionally, see step 2 and 3 in the guide on git.
But when pressing the link in Lecture 5 I just get to the assignment and not a guide on how to sign up as a group. We do not have a repostitory on: github.com/NumEconCopenhagen/ so we are rather confused on where to upload our dataproject

Regards, Jacob

Selecting specefic variables in a dataframe

Hello!

Is it possible to lock a column to multiple specific variables in your dataframe?
We want to select the variables called "Y" and "Y_L". We can't find a simple way to select these variables. The way we do it now works, but it is a troublesome way to do it. We are right now dropping every variable that we don't need. It works when you don't have that many variables, but it is not that effective when you have a lot.

It would be nice if we could write something like:
"samle1234=samle1234[samle1234.variable==["Y" & "Y_L"]]
But unfortunately this doesn't work.

The code:
image
output:
image

We hope that you can help
Best regards

Problem set 1: Optimization solvers results based on initial guess

I couldn't raise an issue in the PS1 exercise repository, so I am creating it here instead. Feel free to (re)move the post if necessary.

My issue/question is regarding the solvers in PS1: As the utility is dependent on the initial guess how should we define the initial guess so it is robust to a large variance in the denominator?

To illustrate consider the following:

from scipy import optimize

def utility_function(x,alpha):
    u = 1
    for x_now,alpha_now in zip(x,alpha):
        u *= np.max(x_now,0)**alpha_now
    return u

def expenditures(x,p):
    E = 0
    for x_now,p_now in zip(x,p):
        E += p_now*x_now
    return E

def print_solution(x,alpha,I,p):
    
    # a. x values
    text = 'x = ['
    for x_now in x:
        text += f'{x_now:.2f} '
    text += f']\n'
    
    # b. utility
    u = utility_function(x,alpha)    
    text += f'utility = {u:.3f}\n'
    
    # c. expenditure vs. income
    E =  expenditures(x,p)
    text += f'E = {E:.2f} <= I = {I:.2f}\n'
    
    # d. expenditure shares
    e = p*x/I
    text += 'expenditure shares = ['
    for e_now in e:
        text += f'{e_now:.2f} '
    text += f']'        
        
    print(text)

alpha = np.ones(5)/5
p = np.array([1,2,3,4,5])
I = 10

Solution using a constrained optimizer:

# a. contraint function (negative if violated)
constraints = ({'type': 'ineq', 'fun': lambda x:  I-expenditures(x,p)})
bounds = [(0,I/p_now) for p_now in p]

# b. call optimizer
initial_guess = (I/p)/100# some guess
res = optimize.minimize(
    lambda x: -utility_function(x,alpha),initial_guess,
    method='SLSQP',bounds=bounds,constraints=constraints)

# c. print result
print_solution(res.x,alpha,I,p)

Changing initial_guess = (I/p)/100 to initial_guess = (I/p)/1 changes
the utility from 0.768 to 0.000.

Conversely, for the solution using an unconstrained optimizer:

# a. define objective function
def unconstrained_objective(x,alpha,I,p):
    
    penalty = 0
    E = expenditures(x,p)
    if E >= I:
        ratio = I/E
        x *= ratio # now p*x = I
        penalty = 1000*(E-I)**2
    
    u = utility_function(x,alpha)
    return -u + penalty

# b. call optimizer
initial_guess = (I/p)/10000
res = optimize.minimize(
    unconstrained_objective,initial_guess,
    method='Nelder-Mead',args=(alpha,I,p))

# c. print result
print_solution(res.x,alpha,I,p)  

Changing the code from initial_guess = (I/p)/1 to initial_guess = (I/p)/10000 changes the utility from 0.768 to 0.000

Looking instead at the loops we consider the code snippet using raw loops:

N = 15 # number of points in each dimension
fac = np.linspace(0,1,N) # vector betweein 0 and 1
x_max = I/p # maximum x so E = I

u_best = -np.inf
x_best = np.empty(5)
for x1 in fac:
    for x2 in fac:
        for x3 in fac:
            for x4 in fac:
                for x5 in fac:
                    x = np.array([x1,x2,x3,x4,x5])*x_max
                    E = expenditures(x,p)
                    if E <= I:
                        u_now = utility_function(x,alpha)
                        if u_now > u_best:
                            x_best = x
                            u_best = u_now

print_solution(x_best,alpha,I,p)

If we change the original value N = 15 to N = 6 the utility changes from 0.758 to 0.768 (same as the the solvers above), however changing it to N = 5 yields a utility of 0.000.
How do we determine the "optimal" or correct number of points in each dimension for our linespacing?

Groups

Write here if you are searching for other students to form a group with.

Mistake in exam?

Hi Jeppe,
In the first assignment you set rho to 2. This seems to give negative utility of consumtion no matter what. Is this a mistake? It makes more sense if it is 0.2.

A new column in dataframe

Hello

We use data from DST which we have converted into a Dataframe. We want to create a new column called NX which is the net export: NX=X-M.

But how do you do that? We can't figure it out...

image

code:
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import pydst
dst = pydst.Dst(lang = 'da')

columns_dict = {}
columns_dict['TRANSAKT'] = 'variable'
columns_dict['PRISENHED'] = 'unit'
columns_dict['TID'] = 'year'
columns_dict['INDHOLD'] = 'value'

var_dict = {} # var is for variable
#var_dict['P.1 Output'] = 'Y'
#var_dict['P.3 Final consumption expenditure'] = 'C'
#var_dict['P.3 Government consumption expenditure'] = 'G'
#var_dict['P.5 Gross capital formation'] = 'I'
#var_dict['P.6 Export of goods and services'] = 'X'
#var_dict['P.7 Import of goods and services'] = 'M'

#VARIABLES
var_dict['B.1*g Bruttpmationalprodukt, BNP'] = 'Y'
var_dict['P.31 Privatforbrug'] = 'C'
var_dict['P.31 Forbrugsudgifter i non-profit institutioner rettet mod husholdninger (NPISH)'] = 'NPISH'
var_dict['P.3 Offentlige forbrugsudgifter'] = 'G'
var_dict['P.5g Bruttoinvesteringer'] = 'I'
var_dict['P.6 Eksport af varer og tjenester'] = 'X'
var_dict['P.7 Import af varer og tjenester'] = 'M'

#UNITS
unit_dict = {}
#unit_dict['2010-prices, chained values'] = 'real'
#unit_dict['Current prices'] = 'nominal'
unit_dict['2010-priser, kædede værdier'] = 'realle'
unit_dict['løbende priser'] = 'nominelle'

#CODE
nan1 = dst.get_data(table_id = 'NAN1', variables={'TRANSAKT':[''], 'PRISENHED':[''], 'TID':['*']})
nan1.rename(columns = columns_dict, inplace = True)

for key,value in var_dict.items():
nan1.variable.replace(key,value,inplace=True)

for key,value in unit_dict.items():
nan1.unit.replace(key,value, inplace=True)

I = False
for key,value in var_dict.items():
I = I | (nan1.variable == value)
nan1 = nan1[I]

nan1.groupby(['variable','unit']).describe()

X = nan1["year"]>2000 #laver en ny variabel hvor X inderholder en variabel year som er større end 2000. giver nan1= nan1[x] for at sige at den skal være lig med det.
nan1 = nan1[X]

Y=nan1["unit"]=="Pr. indbygger, løbende priser, (1000 kr.)"
nan1 = nan1[Y]

df=pd.DataFrame(data=nan1)

df.sort_values(by=["year","variable"])

print(df)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.