markdown stringlengths 0 1.02M | code stringlengths 0 832k | output stringlengths 0 1.02M | license stringlengths 3 36 | path stringlengths 6 265 | repo_name stringlengths 6 127 |
|---|---|---|---|---|---|
Store the data in .csv file | file=open("toronto-data.csv","wb")
file.write(bytes(tabela1,encoding="ascii",errors="ignore")) | _____no_output_____ | MIT | Exploring-the-neighborhoods-in-Toronto.ipynb | Gabriellavoura/Coursera_Capstone |
Converting into dataframe and assigning column names | import pandas as pd
df = pd.read_csv('toronto-data.csv',header=None)
df.columns=["Postalcode","Borough","Neighbourhood"]
df.head(10) | _____no_output_____ | MIT | Exploring-the-neighborhoods-in-Toronto.ipynb | Gabriellavoura/Coursera_Capstone |
Drop row where borough is "Not assigned" | # Get names of indexes for which column Borough has value "Not assigned"
indexNames = df[ df['Borough'] =='Not assigned'].index
# Delete these row indexes from dataFrame
df.drop(indexNames , inplace=True)
df.head(10) | _____no_output_____ | MIT | Exploring-the-neighborhoods-in-Toronto.ipynb | Gabriellavoura/Coursera_Capstone |
If a cell has a borough but a Not assigned neighborhood, then the neighborhood will be the same as the borough | df.loc[df['Neighbourhood'] =='Not assigned' , 'Neighbourhood'] = df['Borough']
df.head(10) | _____no_output_____ | MIT | Exploring-the-neighborhoods-in-Toronto.ipynb | Gabriellavoura/Coursera_Capstone |
Rows will be same postalcode will combined into one row with the neighborhoods separated with a comma | result = df.groupby(['Postalcode','Borough'], sort=False).agg( ', '.join)
df_new=result.reset_index()
df_new.head(10) | _____no_output_____ | MIT | Exploring-the-neighborhoods-in-Toronto.ipynb | Gabriellavoura/Coursera_Capstone |
Store data in new .csv with clean data. | df_new.to_csv(r'Toronto-data-processed.csv', index = False, header = True) | _____no_output_____ | MIT | Exploring-the-neighborhoods-in-Toronto.ipynb | Gabriellavoura/Coursera_Capstone |
Daily Return Distribution (For 15 years) | daily_returns = (nifty_data['Close']/nifty_data['Close'].shift(1) - 1)*100
daily_returns = daily_returns.dropna()
daily_returns.describe()
plt.figure(figsize=[8,7])
plt.style.use("bmh")
plt.hist(daily_returns, density = True, bins=20, color='#2ab0ff',alpha=0.55)
plt.xlabel('% return', fontsize=15)
plt.xticks(fontsize... | _____no_output_____ | Apache-2.0 | notebooks/Daily and Weekly Returns.ipynb | yantraguru/niftystats |
Weekly Return Distribution (For 15 years) | weekly_nifty_data = nifty_data.resample('W').agg(niftyutils.OHLC_CONVERSION_DICT)
weekly_nifty_data.index = weekly_nifty_data.index - to_offset('6D')
weekly_returns = (weekly_nifty_data['Close']/weekly_nifty_data['Close'].shift(1) - 1)*100
weekly_returns = weekly_returns.dropna().rename('returns')
weekly_returns.descri... | _____no_output_____ | Apache-2.0 | notebooks/Daily and Weekly Returns.ipynb | yantraguru/niftystats |
Writing Reusable Code using Functions in Python Part 4 of "Data Analysis with Python: Zero to Pandas" This tutorial covers the following topics:- Creating and using functions in Python- Local variables, return values, and optional arguments- Reusing functions and using Python librar... | today = "Saturday"
print("Today is", today) | Today is Saturday
| MIT | src/Next Steps with Python/.ipynb_checkpoints/Writing Reusable Code using Functions in Python-checkpoint.ipynb | sahanashetty31/Data-Analysis-with-Python-Zero-to-Pandas |
You can define a new function using the `def` keyword. | def say_hello():
print('Hello there!')
print('How are you?') | _____no_output_____ | MIT | src/Next Steps with Python/.ipynb_checkpoints/Writing Reusable Code using Functions in Python-checkpoint.ipynb | sahanashetty31/Data-Analysis-with-Python-Zero-to-Pandas |
Note the round brackets or parentheses `()` and colon `:` after the function's name. Both are essential parts of the syntax. The function's *body* contains an indented block of statements. The statements inside a function's body are not executed when the function is defined. To execute the statements, we need to *call*... | say_hello() | Hello there!
How are you?
| MIT | src/Next Steps with Python/.ipynb_checkpoints/Writing Reusable Code using Functions in Python-checkpoint.ipynb | sahanashetty31/Data-Analysis-with-Python-Zero-to-Pandas |
Function argumentsFunctions can accept zero or more values as *inputs* (also knows as *arguments* or *parameters*). Arguments help us write flexible functions that can perform the same operations on different values. Further, functions can return a result that can be stored in a variable or used in other expressions.H... | def say_hello(name):
print('Hello {}'.format(name))
say_hello("John")
say_hello("Jane")
def filter_even(number_list):
result_list = []
for number in number_list:
if number % 2 == 0:
result_list.append(number)
return result_list | _____no_output_____ | MIT | src/Next Steps with Python/.ipynb_checkpoints/Writing Reusable Code using Functions in Python-checkpoint.ipynb | sahanashetty31/Data-Analysis-with-Python-Zero-to-Pandas |
Can you understand what the function does by looking at the code? If not, try executing each line of the function's body separately within a code cell with an actual list of numbers in place of `number_list`. | even_list = filter_even([1, 2, 3, 4, 5, 6, 7])
even_list
filter_even([1, 3, 5, 7]) | _____no_output_____ | MIT | src/Next Steps with Python/.ipynb_checkpoints/Writing Reusable Code using Functions in Python-checkpoint.ipynb | sahanashetty31/Data-Analysis-with-Python-Zero-to-Pandas |
Writing great functions in PythonAs a programmer, you will spend most of your time writing and using functions. Python offers many features to make your functions powerful and flexible. Let's explore some of these by solving a problem:> Radha is planning to buy a house that costs `$1,260,000`. She considering two opti... | def loan_emi(amount):
emi = amount / 12
print('The EMI is ${}'.format(emi))
loan_emi(12_60_000) | The EMI is $105000.0
| MIT | src/Next Steps with Python/.ipynb_checkpoints/Writing Reusable Code using Functions in Python-checkpoint.ipynb | sahanashetty31/Data-Analysis-with-Python-Zero-to-Pandas |
Local variables and scopeLet's add a second argument to account for the duration of the loan in months. | def loan_emi(amount, duration):
emi = amount / duration
print('The EMI is ${}'.format(emi))
| _____no_output_____ | MIT | src/Next Steps with Python/.ipynb_checkpoints/Writing Reusable Code using Functions in Python-checkpoint.ipynb | sahanashetty31/Data-Analysis-with-Python-Zero-to-Pandas |
Note that the variable `emi` defined inside the function is not accessible outside. The same is true for the parameters `amount` and `duration`. These are all *local variables* that lie within the *scope* of the function.> **Scope**: Scope refers to the region within the code where a particular variable is visible. Eve... | emi
amount
duration | _____no_output_____ | MIT | src/Next Steps with Python/.ipynb_checkpoints/Writing Reusable Code using Functions in Python-checkpoint.ipynb | sahanashetty31/Data-Analysis-with-Python-Zero-to-Pandas |
because above variables are all the local variables We can now compare a 6-year loan vs. a 10-year loan (assuming no down payment or interest). | loan_emi(12_60_600, 8*12)
loan_emi(12_60_000, 10*12) | The EMI is $10500.0
| MIT | src/Next Steps with Python/.ipynb_checkpoints/Writing Reusable Code using Functions in Python-checkpoint.ipynb | sahanashetty31/Data-Analysis-with-Python-Zero-to-Pandas |
Return valuesAs you might expect, the EMI for the 6-year loan is higher compared to the 10-year loan. Right now, we're printing out the result. It would be better to return it and store the results in variables for easier comparison. We can do this using the `return` statement | def loan_emi(amount, duration):
emi = amount / duration
return emi
emi1 = loan_emi(12_60_000, 8*12)
emi2 = loan_emi(12_60_000, 10*12)
emi1
emi2
emi1 - emi2 | _____no_output_____ | MIT | src/Next Steps with Python/.ipynb_checkpoints/Writing Reusable Code using Functions in Python-checkpoint.ipynb | sahanashetty31/Data-Analysis-with-Python-Zero-to-Pandas |
Optional argumentsNext, let's add another argument to account for the immediate down payment. We'll make this an *optional argument* with a default value of 0. | def loan_emi(amount, duration, down_payment=0):
loan_amount = amount - down_payment
emi = amount / duration
return emi
emi1 = loan_emi(12_60_000, 8*12, 3e5)
emi1
emi2 = loan_emi(12_60_000, 10*12)
emi2 | _____no_output_____ | MIT | src/Next Steps with Python/.ipynb_checkpoints/Writing Reusable Code using Functions in Python-checkpoint.ipynb | sahanashetty31/Data-Analysis-with-Python-Zero-to-Pandas |
Next, let's add the interest calculation into the function. Here's the formula used to calculate the EMI for a loan:where:* `P` is the loan amount (principal)* `n` is the no. of months* `r` is the rate of interest per monthThe derivation of this formula is beyond the scope of this tutorial. See this video for an explan... | def loan_emi(amount, duration, rate, down_payment=0):
loan_amount = amount - down_payment
emi = loan_amount * rate * ((1 + rate)**duration) / (((1 + rate)**duration)-1)
return emi | _____no_output_____ | MIT | src/Next Steps with Python/.ipynb_checkpoints/Writing Reusable Code using Functions in Python-checkpoint.ipynb | sahanashetty31/Data-Analysis-with-Python-Zero-to-Pandas |
Note that while defining the function, required arguments like `cost`, `duration` and `rate` must appear before optional arguments like `down_payment`.Let's calculate the EMI for Option 1 | loan_emi(12_60_000, 8*12, 0.1/12, 3e5) | _____no_output_____ | MIT | src/Next Steps with Python/.ipynb_checkpoints/Writing Reusable Code using Functions in Python-checkpoint.ipynb | sahanashetty31/Data-Analysis-with-Python-Zero-to-Pandas |
While calculating the EMI for Option 2, we need not include the `down_payment` argument. | loan_emi(12_60_000,10*12, 0.08/12) | _____no_output_____ | MIT | src/Next Steps with Python/.ipynb_checkpoints/Writing Reusable Code using Functions in Python-checkpoint.ipynb | sahanashetty31/Data-Analysis-with-Python-Zero-to-Pandas |
Named argumentsInvoking a function with many arguments can often get confusing and is prone to human errors. Python provides the option of invoking functions with *named* arguments for better clarity. You can also split function invocation into multiple lines. | emi1 = loan_emi(
amount = 12_60_000,
duration=8*12,
rate=0.1/12,
down_payment=3e5
)
emi1
emi2 = loan_emi(amount=1260000, duration=10*12, rate=0.08/12)
emi2
def round_up(x):
emi2 = loan_emi(amount=1260000, duration=10*12, rate=0.08/12)
return round(emi2)
round_up(emi2) | _____no_output_____ | MIT | src/Next Steps with Python/.ipynb_checkpoints/Writing Reusable Code using Functions in Python-checkpoint.ipynb | sahanashetty31/Data-Analysis-with-Python-Zero-to-Pandas |
Modules and library functionsWe can already see that the EMI for Option 1 is lower than the EMI for Option 2. However, it would be nice to round up the amount to full dollars, rather than showing digits after the decimal. To achieve this, we might want to write a function that can take a number and round it up to the ... | import math
help(math.ceil)
math.ceil(1.2) | _____no_output_____ | MIT | src/Next Steps with Python/.ipynb_checkpoints/Writing Reusable Code using Functions in Python-checkpoint.ipynb | sahanashetty31/Data-Analysis-with-Python-Zero-to-Pandas |
Let's now use the `math.ceil` function within the `home_loan_emi` function to round up the EMI amount. > Using functions to build other functions is a great way to reuse code and implement complex business logic while still keeping the code small, understandable, and manageable. Ideally, a function should do one thing ... | def loan_emi(amount, duration, rate, down_payment=0):
loan_amount = amount - down_payment
emi = loan_amount * rate * ((1+rate)**duration) / (((1+rate)**duration)-1)
emi = math.ceil(emi)
return emi
emi1 = loan_emi(
amount=1260000,
duration=8*12,
rate=0.1/12,
down_payment=3e5
)
emi1
emi... | _____no_output_____ | MIT | src/Next Steps with Python/.ipynb_checkpoints/Writing Reusable Code using Functions in Python-checkpoint.ipynb | sahanashetty31/Data-Analysis-with-Python-Zero-to-Pandas |
Let's compare the EMIs and display a message for the option with the lower EMI. | if emi1 < emi2:
print('Option 1 has the lower EMI: ${}'.format(emi1))
else:
print('Option 2 has the lower EMI: ${}'.format(emi2)) | Option 1 has the lower EMI: $14568
| MIT | src/Next Steps with Python/.ipynb_checkpoints/Writing Reusable Code using Functions in Python-checkpoint.ipynb | sahanashetty31/Data-Analysis-with-Python-Zero-to-Pandas |
Reusing and improving functions Now we know for sure that "Option 1" has the lower EMI among the two options. But what's even better is that we now have a handy function `loan_emi` that we can use to solve many other similar problems with just a few lines of code. Let's try it with a couple more questions. > **Q**: Sh... | cost_of_the_house = 800000
home_loan_duration = 6*12 #months
home_loan_rate = 0.07/12 #monthly
home_down_payment = .25 * 800000
emi_house = loan_emi(amount=cost_of_the_house,
duration=home_loan_duration,
rate=home_loan_rate,
down_payment=home_down_payment)... | Shaun makes a total monthly payment of $96632 towards loan repayments.
| MIT | src/Next Steps with Python/.ipynb_checkpoints/Writing Reusable Code using Functions in Python-checkpoint.ipynb | sahanashetty31/Data-Analysis-with-Python-Zero-to-Pandas |
Exceptions and `try`-`except`> Q: If you borrow `$100,000` using a 10-year loan with an interest rate of 9% per annum, what is the total amount you end up paying as interest?One way to solve this problem is to compare the EMIs for two loans: one with the given rate of interest and another with a 0% rate of interest. T... | emi_with_interest = loan_emi(amount=100000, duration=10*12, rate=0.09/12)
emi_with_interest
emi_without_interest = loan_emi(amount=100000, duration=10*12, rate=0./12)
emi_without_interest | _____no_output_____ | MIT | src/Next Steps with Python/.ipynb_checkpoints/Writing Reusable Code using Functions in Python-checkpoint.ipynb | sahanashetty31/Data-Analysis-with-Python-Zero-to-Pandas |
Something seems to have gone wrong! If you look at the error message above carefully, Python tells us precisely what is wrong. Python *throws* a `ZeroDivisionError` with a message indicating that we're trying to divide a number by zero. `ZeroDivisonError` is an *exception* that stops further execution of the program.> ... | try:
print("Now computing the result..")
result = 5 / 0
print("Computation was completed successfully")
except ZeroDivisionError:
print("Failed to compute result because you were trying to divide by zero")
result = None
print(result) | Now computing the result..
Failed to compute result because you were trying to divide by zero
None
| MIT | src/Next Steps with Python/.ipynb_checkpoints/Writing Reusable Code using Functions in Python-checkpoint.ipynb | sahanashetty31/Data-Analysis-with-Python-Zero-to-Pandas |
When an exception occurs inside a `try` block, the block's remaining statements are skipped. The `except` block is executed if the type of exception thrown matches that of the exception being handled. After executing the `except` block, the program execution returns to the normal flow.You can also handle more than one ... | def loan_emi(amount, duration, rate, down_payment=0):
loan_amount = amount - down_payment
try:
emi = loan_amount * rate * ((1+rate)**duration) / (((1+rate)**duration)-1)
except ZeroDivisionError:
emi = loan_amount / duration
emi = math.ceil(emi)
return emi | _____no_output_____ | MIT | src/Next Steps with Python/.ipynb_checkpoints/Writing Reusable Code using Functions in Python-checkpoint.ipynb | sahanashetty31/Data-Analysis-with-Python-Zero-to-Pandas |
We can use the updated `loan_emi` function to solve our problem.> **Q**: If you borrow `$100,000` using a 10-year loan with an interest rate of 9% per annum, what is the total amount you end up paying as interest? | emi_with_interest = loan_emi(amount=100000, duration=10*12, rate=0.09/12)
emi_with_interest
emi_without_interest = loan_emi(amount=100000, duration=10*12, rate=0)
emi_without_interest
total_interest = (emi_with_interest - emi_without_interest) * 10*12
print("The total interest paid is ${}.".format(total_interest)) | The total interest paid is $51960.
| MIT | src/Next Steps with Python/.ipynb_checkpoints/Writing Reusable Code using Functions in Python-checkpoint.ipynb | sahanashetty31/Data-Analysis-with-Python-Zero-to-Pandas |
Documenting functions using DocstringsWe can add some documentation within our function using a *docstring*. A docstring is simply a string that appears as the first statement within the function body, and is used by the `help` function. A good docstring describes what the function does, and provides some explanation ... | def loan_emi(amount, duration, rate, down_payment=0):
"""Calculates the equal montly installment (EMI) for a loan.
Arguments:
amount - Total amount to be spent (loan + down payment)
duration - Duration of the loan (in months)
rate - Rate of interest (monthly)
down_payment (o... | _____no_output_____ | MIT | src/Next Steps with Python/.ipynb_checkpoints/Writing Reusable Code using Functions in Python-checkpoint.ipynb | sahanashetty31/Data-Analysis-with-Python-Zero-to-Pandas |
In the docstring above, we've provided some additional information that the `duration` and `rate` are measured in months. You might even consider naming the arguments `duration_months` and `rate_monthly`, to avoid any confusion whatsoever. Can you think of some other ways to improve the function? | help(loan_emi) | Help on function loan_emi in module __main__:
loan_emi(amount, duration, rate, down_payment=0)
Calculates the equal montly installment (EMI) for a loan.
Arguments:
amount - Total amount to be spent (loan + down payment)
duration - Duration of the loan (in months)
rate - Rate of int... | MIT | src/Next Steps with Python/.ipynb_checkpoints/Writing Reusable Code using Functions in Python-checkpoint.ipynb | sahanashetty31/Data-Analysis-with-Python-Zero-to-Pandas |
Exercise - Data Analysis for Vacation PlanningYou're planning a vacation, and you need to decide which city you want to visit. You have shortlisted four cities and identified the return flight cost, daily hotel cost, and weekly car rental cost. While renting a car, you need to pay for entire weeks, even if you return ... | # Use these cells to answer the question - build the function step-by-step
paris_dict = dict(city="Paris", cost_return_flight=200, cost_hotel_per_night=20, cost_car_rental_weekly=200)
london_dict = dict(city="London", cost_return_flight=250, cost_hotel_per_night=30, cost_car_rental_weekly=120)
dubai_dict = dict(city="D... | (1140, 17, 3)
(910, 14, 2)
(850, 16, 3)
(1430, 49, 7)
| MIT | src/Next Steps with Python/.ipynb_checkpoints/Writing Reusable Code using Functions in Python-checkpoint.ipynb | sahanashetty31/Data-Analysis-with-Python-Zero-to-Pandas |
Region MaskingIn last excersize we were able to identify lane lines but that is not enough because there were many more objects/pixels we identified and they were not all lane lines.In this notebook, lets define the region of interest and identify lane lines from there. Its basically a way to make sure your camera see... | import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
image = mpimg.imread('../img/test.jpg')
print('This image is: ', type(image),
'with dimensions:', image.shape)
# Pull out the x and y sizes and make a copy of the image
ysize = image.shape[0]
xsize = image.shape[1]
region_se... | This image is: <class 'numpy.ndarray'> with dimensions: (540, 960, 3)
| MIT | 01-Computer-Vision-Fundamentals/.ipynb_checkpoints/2 Region Masking-checkpoint.ipynb | vyasparthm/AutonomousDriving |
Masking the ImageNow that we have been able to pick threshold colors in last quiz, let's go one step further and mark the region of interest in the given image. | import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
image = mpimg.imread('../img/test.jpg')
print('This image is: ', type(image),
'with dimensions:', image.shape)
# Pull out the x and y sizes and make a copy of the image
ysize = image.shape[0]
xsize = image.shape[1]
region_se... | This image is: <class 'numpy.ndarray'> with dimensions: (540, 960, 3)
| MIT | 01-Computer-Vision-Fundamentals/.ipynb_checkpoints/2 Region Masking-checkpoint.ipynb | vyasparthm/AutonomousDriving |
Modeling and Simulation in PythonChapter 3Copyright 2017 Allen DowneyLicense: [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0) | # Configure Jupyter so figures appear in the notebook
%matplotlib inline
# Configure Jupyter to display the assigned value after an assignment
%config InteractiveShell.ast_node_interactivity='last_expr_or_assign'
# import functions from the modsim library
from modsim import *
# set the random number generator
np.ran... | _____no_output_____ | MIT | soln/chap03soln.ipynb | pmalo46/ModSimPy |
More than one State objectHere's the code from the previous chapter, with two changes:1. I've added DocStrings that explain what each function does, and what parameters it takes.2. I've added a parameter named `state` to the functions so they work with whatever `State` object we give them, instead of always using `bik... | def step(state, p1, p2):
"""Simulate one minute of time.
state: bikeshare State object
p1: probability of an Olin->Wellesley customer arrival
p2: probability of a Wellesley->Olin customer arrival
"""
if flip(p1):
bike_to_wellesley(state)
if flip(p2):
bike_to_olin(st... | _____no_output_____ | MIT | soln/chap03soln.ipynb | pmalo46/ModSimPy |
And here's `run_simulation`, which is a solution to the exercise at the end of the previous notebook. | def run_simulation(state, p1, p2, num_steps):
"""Simulate the given number of time steps.
state: State object
p1: probability of an Olin->Wellesley customer arrival
p2: probability of a Wellesley->Olin customer arrival
num_steps: number of time steps
"""
results = TimeSeries()
f... | _____no_output_____ | MIT | soln/chap03soln.ipynb | pmalo46/ModSimPy |
Now we can create more than one `State` object: | bikeshare1 = State(olin=10, wellesley=2)
bikeshare2 = State(olin=2, wellesley=10) | _____no_output_____ | MIT | soln/chap03soln.ipynb | pmalo46/ModSimPy |
Whenever we call a function, we indicate which `State` object to work with: | bike_to_olin(bikeshare1)
bike_to_wellesley(bikeshare2) | _____no_output_____ | MIT | soln/chap03soln.ipynb | pmalo46/ModSimPy |
And you can confirm that the different objects are getting updated independently: | bikeshare1
bikeshare2 | _____no_output_____ | MIT | soln/chap03soln.ipynb | pmalo46/ModSimPy |
Negative bikes In the code we have so far, the number of bikes at one of the locations can go negative, and the number of bikes at the other location can exceed the actual number of bikes in the system.If you run this simulation a few times, it happens often. | bikeshare = State(olin=10, wellesley=2)
run_simulation(bikeshare, 0.4, 0.2, 60)
decorate_bikeshare() | _____no_output_____ | MIT | soln/chap03soln.ipynb | pmalo46/ModSimPy |
We can fix this problem using the `return` statement to exit the function early if an update would cause negative bikes. | def bike_to_wellesley(state):
"""Move one bike from Olin to Wellesley.
state: bikeshare State object
"""
if state.olin == 0:
return
state.olin -= 1
state.wellesley += 1
def bike_to_olin(state):
"""Move one bike from Wellesley to Olin.
state: bikeshare State object
... | _____no_output_____ | MIT | soln/chap03soln.ipynb | pmalo46/ModSimPy |
Now if you run the simulation again, it should behave. | bikeshare = State(olin=10, wellesley=2)
run_simulation(bikeshare, 0.4, 0.2, 60)
decorate_bikeshare() | _____no_output_____ | MIT | soln/chap03soln.ipynb | pmalo46/ModSimPy |
Comparison operators The `if` statements in the previous section used the comparison operator `==`. The other comparison operators are listed in the book.It is easy to confuse the comparison operator `==` with the assignment operator `=`.Remember that `=` creates a variable or gives an existing variable a new value. | x = 5 | _____no_output_____ | MIT | soln/chap03soln.ipynb | pmalo46/ModSimPy |
Whereas `==` compares two values and returns `True` if they are equal. | x == 5 | _____no_output_____ | MIT | soln/chap03soln.ipynb | pmalo46/ModSimPy |
You can use `==` in an `if` statement. | if x == 5:
print('yes, x is 5') | yes, x is 5
| MIT | soln/chap03soln.ipynb | pmalo46/ModSimPy |
But if you use `=` in an `if` statement, you get an error. | # If you remove the # from the if statement and run it, you'll get
# SyntaxError: invalid syntax
#if x = 5:
# print('yes, x is 5') | _____no_output_____ | MIT | soln/chap03soln.ipynb | pmalo46/ModSimPy |
**Exercise:** Add an `else` clause to the `if` statement above, and print an appropriate message.Replace the `==` operator with one or two of the other comparison operators, and confirm they do what you expect. Metrics Now that we have a working simulation, we'll use it to evaluate alternative designs and see how good... | bikeshare = State(olin=10, wellesley=2,
olin_empty=0, wellesley_empty=0) | _____no_output_____ | MIT | soln/chap03soln.ipynb | pmalo46/ModSimPy |
Next we need versions of `bike_to_wellesley` and `bike_to_olin` that update the metrics. | def bike_to_wellesley(state):
"""Move one bike from Olin to Wellesley.
state: bikeshare State object
"""
if state.olin == 0:
state.olin_empty += 1
return
state.olin -= 1
state.wellesley += 1
def bike_to_olin(state):
"""Move one bike from Wellesley to Olin.
... | _____no_output_____ | MIT | soln/chap03soln.ipynb | pmalo46/ModSimPy |
Now when we run a simulation, it keeps track of unhappy customers. | run_simulation(bikeshare, 0.4, 0.2, 60)
decorate_bikeshare() | _____no_output_____ | MIT | soln/chap03soln.ipynb | pmalo46/ModSimPy |
After the simulation, we can print the number of unhappy customers at each location. | bikeshare.olin_empty
bikeshare.wellesley_empty | _____no_output_____ | MIT | soln/chap03soln.ipynb | pmalo46/ModSimPy |
Exercises**Exercise:** As another metric, we might be interested in the time until the first customer arrives and doesn't find a bike. To make that work, we have to add a "clock" to keep track of how many time steps have elapsed:1. Create a new `State` object with an additional state variable, `clock`, initialized to... | bikeshare = State(olin=10, wellesley=2,
olin_empty=0, wellesley_empty=0,
clock=0)
# Solution
def step(state, p1, p2):
"""Simulate one minute of time.
state: bikeshare State object
p1: probability of an Olin->Wellesley customer arrival
p2: probability of a Welle... | _____no_output_____ | MIT | soln/chap03soln.ipynb | pmalo46/ModSimPy |
**Exercise:** Continuing the previous exercise, let's record the time when the first customer arrives and doesn't find a bike.1. Create a new `State` object with an additional state variable, `t_first_empty`, initialized to -1 as a special value to indicate that it has not been set. 2. Write a modified version of `step... | # Solution
bikeshare = State(olin=10, wellesley=2,
olin_empty=0, wellesley_empty=0,
clock=0, t_first_empty=-1)
# Solution
def step(state, p1, p2):
"""Simulate one minute of time.
state: bikeshare State object
p1: probability of an Olin->Wellesley customer arrival
... | _____no_output_____ | MIT | soln/chap03soln.ipynb | pmalo46/ModSimPy |
Tutorial: PyTorch | __author__ = "Ignacio Cases"
__version__ = "CS224u, Stanford, Spring 2021" | _____no_output_____ | Apache-2.0 | tutorial_pytorch.ipynb | feifang24/cs224u-spr2021 |
Contents1. [Motivation](Motivation)1. [Importing PyTorch](Importing-PyTorch)1. [Tensors](Tensors) 1. [Tensor creation](Tensor-creation) 1. [Operations on tensors](Operations-on-tensors)1. [GPU computation](GPU-computation)1. [Neural network foundations](Neural-network-foundations) 1. [Automatic differentiation](Aut... | import torch | _____no_output_____ | Apache-2.0 | tutorial_pytorch.ipynb | feifang24/cs224u-spr2021 |
**Side note**: why not `import pytorch`? The name of the package is `torch` for historical reasons: `torch` is the orginal name of the ancestor of the PyTorch library that got started back in 2002 as a C library with Lua scripting. It was only much later that the original `torch` was ported to Python. The PyTorch proje... | print("PyTorch version {}".format(torch.__version__))
print("GPU-enabled installation? {}".format(torch.cuda.is_available())) | PyTorch version 1.8.0
GPU-enabled installation? False
| Apache-2.0 | tutorial_pytorch.ipynb | feifang24/cs224u-spr2021 |
PyTorch has good [documentation](https://pytorch.org/docs/stable/index.html) but it can take some time to familiarize oneself with the structure of the package; it's worth the effort to do so!We will also make use of other imports: | import numpy as np | _____no_output_____ | Apache-2.0 | tutorial_pytorch.ipynb | feifang24/cs224u-spr2021 |
Tensors Tensors collections of numbers represented as an array, and are the basic building blocks in PyTorch.You are probably already familiar with several types of tensors: - A scalar, a single number, is a zero-th order tensor. - A column vector $v$ of dimensionality $d_c \times 1$ is a tensor of order 1. -... | t = torch.FloatTensor(2, 3)
print(t)
print(t.size()) | tensor([[9.8091e-45, 0.0000e+00, 0.0000e+00],
[0.0000e+00, 0.0000e+00, 0.0000e+00]])
torch.Size([2, 3])
| Apache-2.0 | tutorial_pytorch.ipynb | feifang24/cs224u-spr2021 |
Note that we specified the dimensions as the arguments to the constructor by passing the numbers directly – and not a list or a tuple, which would have very different outcomes as we will see below! We can always inspect the size of the tensor using the `size()` method.The constructor method allocates space in memory fo... | t.zero_() | _____no_output_____ | Apache-2.0 | tutorial_pytorch.ipynb | feifang24/cs224u-spr2021 |
The underscore after the method name is important: it means that the operation happens _in place_: the returned object is the same object but now with different content. A very handy way to construct a tensor using the constructor happens when we have available the content we want to put in the tensor in the form of a ... | torch.FloatTensor([[1, 2, 3], [4, 5, 6]]) | _____no_output_____ | Apache-2.0 | tutorial_pytorch.ipynb | feifang24/cs224u-spr2021 |
Calling a method in the torch module A very convenient way to create tensors, in addition to using the constructor method, is to use one of the multiple methods provided in the `torch` module. In particular, the `tensor` method allows us to pass a number or iterable as the argument to get the appropriately typed tenso... | tl = torch.tensor([1, 2, 3])
t = torch.tensor([1., 2., 3.])
print("A 64-bit integer tensor: {}, {}".format(tl, tl.type()))
print("A 32-bit float tensor: {}, {}".format(t, t.type())) | A 64-bit integer tensor: tensor([1, 2, 3]), torch.LongTensor
A 32-bit float tensor: tensor([1., 2., 3.]), torch.FloatTensor
| Apache-2.0 | tutorial_pytorch.ipynb | feifang24/cs224u-spr2021 |
We can create a similar 2x3 tensor to the one above by using the `torch.zeros()` method, passing a sequence of dimensions to it: | t = torch.zeros(2, 3)
print(t) | tensor([[0., 0., 0.],
[0., 0., 0.]])
| Apache-2.0 | tutorial_pytorch.ipynb | feifang24/cs224u-spr2021 |
There are many methods for creating tensors. We list some useful ones: | t_zeros = torch.zeros_like(t) # zeros_like returns a new tensor
t_ones = torch.ones(2, 3) # creates a tensor with 1s
t_fives = torch.empty(2, 3).fill_(5) # creates a non-initialized tensor and fills it with 5
t_random = torch.rand(2, 3) # creates a uniform random tensor
t_normal = torch.randn... | tensor([[0., 0., 0.],
[0., 0., 0.]])
tensor([[1., 1., 1.],
[1., 1., 1.]])
tensor([[5., 5., 5.],
[5., 5., 5.]])
tensor([[0.2930, 0.9685, 0.0458],
[0.9844, 0.1271, 0.2497]])
tensor([[-0.4341, 0.1566, -0.7059],
[ 0.5371, 0.0399, 0.5803]])
| Apache-2.0 | tutorial_pytorch.ipynb | feifang24/cs224u-spr2021 |
We now see emerging two important paradigms in PyTorch. The _imperative_ approach to performing operations, using _inplace_ methods, is in marked contrast with an additional paradigm also used in PyTorch, the _functional_ approach, where the returned object is a copy of the original object. Both paradigms have their sp... | # creates a new copy of the tensor that is still linked to
# the computational graph (see below)
t1 = torch.clone(t)
assert id(t) != id(t1), 'Functional methods create a new copy of the tensor'
# To create a new _independent_ copy, we do need to detach
# from the graph
t1 = torch.clone(t).detach() | _____no_output_____ | Apache-2.0 | tutorial_pytorch.ipynb | feifang24/cs224u-spr2021 |
Using the PyTorch–NumPy bridge A quite useful feature of PyTorch is its almost seamless integration with NumPy, which allows us to perform operations on NumPy and interact from PyTorch with the large number of NumPy libraries as well. Converting a NumPy multi-dimensional array into a PyTorch tensor is very simple: we ... | # Create a new multi-dimensional array in NumPy with the np datatype (np.float32)
a = np.array([1., 2., 3.])
# Convert the array to a torch tensor
t = torch.tensor(a)
print("NumPy array: {}, type: {}".format(a, a.dtype))
print("Torch tensor: {}, type: {}".format(t, t.dtype)) | NumPy array: [1. 2. 3.], type: float64
Torch tensor: tensor([1., 2., 3.], dtype=torch.float64), type: torch.float64
| Apache-2.0 | tutorial_pytorch.ipynb | feifang24/cs224u-spr2021 |
We can also seamlessly convert a PyTorch tensor into a NumPy array: | t.numpy() | _____no_output_____ | Apache-2.0 | tutorial_pytorch.ipynb | feifang24/cs224u-spr2021 |
**Side note**: why not `torch.from_numpy(a)`? The `from_numpy()` method is depecrated in favor of `tensor()`, which is a more capable method in the torch package. `from_numpy()` is only there for backwards compatibility. It can be a little bit quirky, so I recommend using the newer method in PyTorch >= 0.4. Indexing I... | t = torch.randn(2, 3)
t[ : , 0] | _____no_output_____ | Apache-2.0 | tutorial_pytorch.ipynb | feifang24/cs224u-spr2021 |
PyTorch also supports indexing using long tensors, for example: | t = torch.randn(5, 6)
print(t)
i = torch.tensor([1, 3])
j = torch.tensor([4, 5])
print(t[i]) # selects rows 1 and 3
print(t[i, j]) # selects (1, 4) and (3, 5) | tensor([[ 0.0421, 0.0713, -2.1790, 0.3855, 1.8714, -0.2528],
[-0.3344, 0.8028, -0.2878, -0.2721, 1.0514, -1.3336],
[-1.3506, 0.5657, 1.4540, -0.7039, -0.6878, 0.9614],
[ 0.3845, 0.4493, -0.8910, -1.4512, 0.1300, 1.5551],
[ 0.9192, 0.3812, -1.3167, 0.4005, -0.0778, 1.5110]])... | Apache-2.0 | tutorial_pytorch.ipynb | feifang24/cs224u-spr2021 |
Type conversion Each tensor has a set of convenient methods to convert types. For example, if we want to convert the tensor above to a 32-bit float tensor, we use the method `.float()`: | t = t.float() # converts to 32-bit float
print(t)
t = t.double() # converts to 64-bit float
print(t)
t = t.byte() # converts to unsigned 8-bit integer
print(t) | tensor([[ 0.0421, 0.0713, -2.1790, 0.3855, 1.8714, -0.2528],
[-0.3344, 0.8028, -0.2878, -0.2721, 1.0514, -1.3336],
[-1.3506, 0.5657, 1.4540, -0.7039, -0.6878, 0.9614],
[ 0.3845, 0.4493, -0.8910, -1.4512, 0.1300, 1.5551],
[ 0.9192, 0.3812, -1.3167, 0.4005, -0.0778, 1.5110]])... | Apache-2.0 | tutorial_pytorch.ipynb | feifang24/cs224u-spr2021 |
Operations on tensors Now that we know how to create tensors, let's create some of the fundamental tensors and see some common operations on them: | # Scalars =: creates a tensor with a scalar
# (zero-th order tensor, i.e. just a number)
s = torch.tensor(42)
print(s) | tensor(42)
| Apache-2.0 | tutorial_pytorch.ipynb | feifang24/cs224u-spr2021 |
**Tip**: a very convenient to access scalars is with `.item()`: | s.item() | _____no_output_____ | Apache-2.0 | tutorial_pytorch.ipynb | feifang24/cs224u-spr2021 |
Let's see higher-order tensors – remember we can always inspect the dimensionality of a tensor using the `.size()` method: | # Row vector
x = torch.randn(1,3)
print("Row vector\n{}\nwith size {}".format(x, x.size()))
# Column vector
v = torch.randn(3,1)
print("Column vector\n{}\nwith size {}".format(v, v.size()))
# Matrix
A = torch.randn(3, 3)
print("Matrix\n{}\nwith size {}".format(A, A.size())) | Row vector
tensor([[ 1.5811, -0.0148, -2.1993]])
with size torch.Size([1, 3])
Column vector
tensor([[-0.5085],
[ 1.1261],
[ 0.2023]])
with size torch.Size([3, 1])
Matrix
tensor([[-1.6138, 0.5316, -0.6007],
[ 0.8608, -0.9427, 0.0111],
[-0.7028, -1.2223, 1.1992]])
with size torch.Size([... | Apache-2.0 | tutorial_pytorch.ipynb | feifang24/cs224u-spr2021 |
A common operation is matrix-vector multiplication (and in general tensor-tensor multiplication). For example, the product $\mathbf{A}\mathbf{v} + \mathbf{b}$ is as follows: | u = torch.matmul(A, v)
print(u)
b = torch.randn(3,1)
y = u + b # we can also do torch.add(u, b)
print(y) | tensor([[ 1.2978],
[-1.4971],
[-0.7765]])
tensor([[ 0.6784],
[-2.1156],
[ 0.5897]])
| Apache-2.0 | tutorial_pytorch.ipynb | feifang24/cs224u-spr2021 |
where we retrieve the expected result (a column vector of dimensions 3x1). We can of course compose operations: | s = torch.matmul(x, torch.matmul(A, v))
print(s.item()) | 3.781867027282715
| Apache-2.0 | tutorial_pytorch.ipynb | feifang24/cs224u-spr2021 |
There are many functions implemented for every tensor, and we encourage you to study the documentation. Some of the most common ones: | # common tensor methods (they also have the counterpart in
# the torch package, e.g. as torch.sum(t))
t = torch.randn(2,3)
t.sum(dim=0)
t.t() # transpose
t.numel() # number of elements in tensor
t.nonzero() # indices of non-zero elements
t.view(-1, 2) # reorganizes ... | _____no_output_____ | Apache-2.0 | tutorial_pytorch.ipynb | feifang24/cs224u-spr2021 |
GPU computation Deep Learning frameworks take advantage of the powerful computational capabilities of modern graphic processing units (GPUs). GPUs were originally designed to perform frequent operations for graphics very efficiently and fast, such as linear algebra operations, which makes them ideal for our interests.... | try:
t_gpu = torch.cuda.FloatTensor(3, 3) # creation of a GPU tensor
t_gpu.zero_() # initialization to zero
except TypeError as err:
print(err) | type torch.cuda.FloatTensor not available. Torch not compiled with CUDA enabled.
| Apache-2.0 | tutorial_pytorch.ipynb | feifang24/cs224u-spr2021 |
However, a more common approach that gives us flexibility is through the use of devices. A device in PyTorch refers to either the CPU (indicated by the string "cpu") or one of the possible GPU cards in the machine (indicated by the string "cuda:$n$", where $n$ is the index of the card). Let's create a random gaussian m... | try:
t_gpu = torch.randn(3, 3, device="cuda:0")
except AssertionError as err:
print(err)
t_gpu = None
t_gpu | Torch not compiled with CUDA enabled
| Apache-2.0 | tutorial_pytorch.ipynb | feifang24/cs224u-spr2021 |
As you can notice, the tensor now has the explicit device set to be a CUDA device, not a CPU device. Let's now create a tensor in the CPU and move it to the GPU: | # we could also state explicitly the device to be the
# CPU with torch.randn(3,3,device="cpu")
t = torch.randn(3, 3)
t | _____no_output_____ | Apache-2.0 | tutorial_pytorch.ipynb | feifang24/cs224u-spr2021 |
In this case, the device is the CPU, but PyTorch does not explicitly say that given that this is the default behavior. To copy the tensor to the GPU we use the `.to()` method that every tensor implements, passing the device as an argument. This method creates a copy in the specified device or, if the tensor already res... | try:
t_gpu = t.to("cuda:0") # copies the tensor from CPU to GPU
# note that if we do now t_to_gpu.to("cuda:0") it will
# return the same tensor without doing anything else
# as this tensor already resides on the GPU
print(t_gpu)
print(t_gpu.device)
except AssertionError as err:
print(err) | Torch not compiled with CUDA enabled
| Apache-2.0 | tutorial_pytorch.ipynb | feifang24/cs224u-spr2021 |
**Tip**: When we program PyTorch models, we will have to specify the device in several places (not so many, but definitely more than once). A good practice that is consistent accross the implementation and makes the code more portable is to declare early in the code a device variable by querying the framework if there ... | device = torch.device("cuda:0") if torch.cuda.is_available() else torch.device("cpu")
print(device) | cpu
| Apache-2.0 | tutorial_pytorch.ipynb | feifang24/cs224u-spr2021 |
We can then use `device` as an argument of the `.to()` method in the rest of our code: | # moves t to the device (this code will **not** fail if the
# local machine has not access to a GPU)
t.to(device) | _____no_output_____ | Apache-2.0 | tutorial_pytorch.ipynb | feifang24/cs224u-spr2021 |
**Side note**: having good GPU backend support is a critical aspect of a deep learning framework. Some models depend crucially on performing computations on a GPU. Most frameworks, including PyTorch, only provide good support for GPUs manufactured by Nvidia. This is mostly due to the heavy investment this company made ... | import torch.nn as nn | _____no_output_____ | Apache-2.0 | tutorial_pytorch.ipynb | feifang24/cs224u-spr2021 |
All our models subclass this base `nn.Module` class, which provides an interface to important methods used for constructing and working with our models, and which contains sensible initializations for our models. Modules can contain other modules (and usually do).Let's see a simple, custom implementation of a multi-lay... | class MyCustomModule(nn.Module):
def __init__(self, n_inputs, n_hidden, n_output_classes):
# call super to initialize the class above in the hierarchy
super(MyCustomModule, self).__init__()
# first affine transformation
self.W = nn.Linear(n_inputs, n_hidden)
# non-linearity (... | _____no_output_____ | Apache-2.0 | tutorial_pytorch.ipynb | feifang24/cs224u-spr2021 |
Then, we can use our new module as follows: | # set the network's architectural parameters
n_inputs = 3
n_hidden= 4
n_output_classes = 2
# instantiate the model
model = MyCustomModule(n_inputs, n_hidden, n_output_classes)
# create a simple input tensor
# size is [1,3]: a mini-batch of one example,
# this example having dimension 3
x = torch.FloatTensor([[0.3, 0.... | tensor([[0.2473, 0.1775]], grad_fn=<AddmmBackward>)
| Apache-2.0 | tutorial_pytorch.ipynb | feifang24/cs224u-spr2021 |
As we see, the output is a tensor with its gradient function attached – Autograd tracks it for us. **Tip**: modules overrides the `__call__()` method, where the framework does some work. Thus, instead of directly calling the `forward()` method, we apply the input to the model instead. Sequential A powerful class in th... | class MyCustomModule(nn.Module):
def __init__(self, n_inputs, n_hidden, n_output_classes):
super(MyCustomModule, self).__init__()
self.network = nn.Sequential(
nn.Linear(n_inputs, n_hidden),
nn.ReLU(),
nn.Linear(n_hidden, n_output_classes))
def forward(self, ... | _____no_output_____ | Apache-2.0 | tutorial_pytorch.ipynb | feifang24/cs224u-spr2021 |
As you can imagine, this can be handy when we have a large number of layers for which the actual names are not that meaningful. It also improves readability: | class MyCustomModule(nn.Module):
def __init__(self, n_inputs, n_hidden, n_output_classes):
super(MyCustomModule, self).__init__()
self.p_keep = 0.7
self.network = nn.Sequential(
nn.Linear(n_inputs, n_hidden),
nn.ReLU(),
nn.Linear(n_hidden, 2*n_hidden),
... | _____no_output_____ | Apache-2.0 | tutorial_pytorch.ipynb | feifang24/cs224u-spr2021 |
**Side note**: Another important package in `torch.nn` is `Functional`, typically imported as `F`. Functional contains many useful functions, from non-linear activations to convolutional, dropout, and even distance functions. Many of these functions have counterpart implementations as layers in the `nn` package so that... | import torch.nn.functional as F
y = F.relu(torch.FloatTensor([[-5, -1, 0, 5]]))
y | _____no_output_____ | Apache-2.0 | tutorial_pytorch.ipynb | feifang24/cs224u-spr2021 |
Criteria and loss functions PyTorch has implementations for the most common criteria in the `torch.nn` package. You may notice that, as with many of the other functions, there are two implementations of loss functions: the reference functions in `torch.nn.functional` and practical class in `torch.nn`, which are the on... | # the true label (in this case, 2) from our dataset wrapped
# as a tensor of minibatch size of 1
y_gold = torch.tensor([1])
# our simple classification criterion for this simple example
criterion = nn.CrossEntropyLoss()
# forward pass of our model (remember, using apply instead of forward)
y = model(x)
# apply the c... | tensor(0.7287, grad_fn=<NllLossBackward>)
| Apache-2.0 | tutorial_pytorch.ipynb | feifang24/cs224u-spr2021 |
Optimization Once we have computed the loss for a training example or minibatch of examples, we update the parameters of the model guided by the information contained in the gradient. The role of updating the parameters belongs to the optimizer, and PyTorch has a number of implementations available right away – and if... | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.data as data
import numpy as np
import matplotlib.pyplot as plt
import math | _____no_output_____ | Apache-2.0 | tutorial_pytorch.ipynb | feifang24/cs224u-spr2021 |
Early on the code, we define the device that we want to use: | device = torch.device("cuda:0") if torch.cuda.is_available() else torch.device("cpu") | _____no_output_____ | Apache-2.0 | tutorial_pytorch.ipynb | feifang24/cs224u-spr2021 |
Let's fix $a=1$, $\phi=1$ and generate traning data in the interval $x \in [0,2\pi)$ using NumPy: | M = 1200
# sample from the x axis M points
x = np.random.rand(M) * 2*math.pi
# add noise
eta = np.random.rand(M) * 0.01
# compute the function
y = np.sin(x) + eta
# plot
_ = plt.scatter(x,y)
# use the NumPy-PyTorch bridge
x_train = torch.tensor(x[0:1000]).float().view(-1, 1).to(device)
y_train = torch.tensor(y[0:10... | 0.005281522491713986
| Apache-2.0 | tutorial_pytorch.ipynb | feifang24/cs224u-spr2021 |
Reproducibility | def enforce_reproducibility(seed=42):
# Sets seed manually for both CPU and CUDA
torch.manual_seed(seed)
# For atomic operations there is currently
# no simple way to enforce determinism, as
# the order of parallel operations is not known.
#
# CUDNN
torch.backends.cudnn.deterministic = T... | _____no_output_____ | Apache-2.0 | tutorial_pytorch.ipynb | feifang24/cs224u-spr2021 |
Default exception blockHandle any type off exception | enter first no5
enter second now
error occured
end
| MIT | mod_07/mod_07_01.ipynb | merazlab/python | |
Single try with multiple except block | try:
x = int(input("enter first no"))
y = int(input("enter second no"))
z = x / y
print("result", z)
except(ZeroDivisionError):
print("second value is not zero")
except(ValueError):
print("Value eroor")
except:
print("error occured")
print("end")
| enter first no7
enter second nof
Value eroor
end
| MIT | mod_07/mod_07_01.ipynb | merazlab/python |
Raise exception-Default exception block is last block always | try:
x = int(input("enter first no"))
y = int(input("enter second no"))
z = x / y
print("result", z)
raise KeyError
except(ZeroDivisionError):
print("second value is not zero")
except(ValueError):
print("Value eroor")
except:
print("error occured")
print("end") | enter first no4
enter second no3
result 1.3333333333333333
error occured
end
| MIT | mod_07/mod_07_01.ipynb | merazlab/python |
finally The sets of statements which are compulsary to exectute whether exception is raised or not raisedException- Only user frienly statement Resource releasing statemnet are written in finally group | try:
x = int(input("enter first no"))
y = int(input("enter second no"))
z = x / y
print("result", z)
except(ZeroDivisionError):
print("second value is not zero")
finally: #run exception raised or not raised
print("bye")
print("end")
x = open("myfile.txt")
print(x.read())
x.write("meraz")
x.close()
print(... | _____no_output_____ | MIT | mod_07/mod_07_01.ipynb | merazlab/python |
How to create Popups Simple popupsYou can define your popup at the feature creation, but you can also overwrite them afterwards: | import folium
m = folium.Map([45, 0], zoom_start=4)
folium.Marker([45, -30], popup="inline implicit popup").add_to(m)
folium.CircleMarker(
location=[45, -10],
radius=25,
fill=True,
popup=folium.Popup("inline explicit Popup"),
).add_to(m)
ls = folium.PolyLine(
locations=[[43, 7], [43, 13], [47, ... | _____no_output_____ | MIT | examples/Popups.ipynb | uni-3/folium |
Vega PopupYou may know that it's possible to create awesome Vega charts with (or without) `vincent`. If you're willing to put one inside a popup, it's possible thanks to `folium.Vega`. | import json
import numpy as np
import vincent
scatter_points = {
"x": np.random.uniform(size=(100,)),
"y": np.random.uniform(size=(100,)),
}
# Let's create the vincent chart.
scatter_chart = vincent.Scatter(scatter_points, iter_idx="x", width=600, height=300)
# Let's convert it to JSON.
scatter_json = scatt... | _____no_output_____ | MIT | examples/Popups.ipynb | uni-3/folium |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.