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 |
|---|---|---|---|---|---|
Run the evaluation stepUse the checkpointed model to run the evaluation step. | estimator_eval = RLEstimator(
role=role,
source_dir="src/",
dependencies=["common/sagemaker_rl"],
toolkit=RLToolkit.COACH,
toolkit_version="1.0.0",
framework=RLFramework.TENSORFLOW,
entry_point="evaluate-coach.py",
instance_count=1,
instance_type=instance_type,
base_job_name=job_... | _____no_output_____ | Apache-2.0 | reinforcement_learning/rl_traveling_salesman_vehicle_routing_coach/rl_traveling_salesman_vehicle_routing_coach.ipynb | Amirosimani/amazon-sagemaker-examples |
Medium version of TSP We make the problem much harder in this version by randomizing the location of destiations each episode. Hence, RL agent has to come up with a general strategy to navigate the grid. Parameters, states, actions, and rewards are identical to the Easy version of TSP. StatesAt each time step, our age... | %%time
# run in local mode?
local_mode = False
# create unique job name
job_name_prefix = "rl-tsp-medium"
%%time
if local_mode:
instance_type = "local"
else:
instance_type = "ml.m4.4xlarge"
estimator = RLEstimator(
entry_point="train-coach.py",
source_dir="src",
dependencies=["common/sagemaker_r... | _____no_output_____ | Apache-2.0 | reinforcement_learning/rl_traveling_salesman_vehicle_routing_coach/rl_traveling_salesman_vehicle_routing_coach.ipynb | Amirosimani/amazon-sagemaker-examples |
Visualize, Compare with Baseline and EvaluateYou can follow the same set of code used for TSP easy version. Vehicle Routing Problem with Reinforcement Learning Vehicle Routing Problem (VRP) is a similar problem where the algorithm optimizes the movement of a fleet of vehicles. Our VRP formulation is a bit different, ... | %%time
# run in local mode?
local_mode = False
# create unique job name
job_name_prefix = "rl-vrp-easy"
%%time
if local_mode:
instance_type = "local"
else:
instance_type = "ml.m4.4xlarge"
estimator = RLEstimator(
entry_point="train-coach.py",
source_dir="src",
dependencies=["common/sagemaker_rl"... | _____no_output_____ | Apache-2.0 | reinforcement_learning/rl_traveling_salesman_vehicle_routing_coach/rl_traveling_salesman_vehicle_routing_coach.ipynb | Amirosimani/amazon-sagemaker-examples |
!pip install tf-nightly-2.0-preview
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
print(tf.__version__)
dataset = tf.data.Dataset.range(10)
for val in dataset:
print(val.numpy())
dataset = tf.data.Dataset.range(10)
dataset = dataset.window(5, shift=1)
for window_dataset in dataset:
f... | x = [[0 1 2 3]
[4 5 6 7]]
y = [[4]
[8]]
x = [[2 3 4 5]
[3 4 5 6]]
y = [[6]
[7]]
x = [[5 6 7 8]
[1 2 3 4]]
y = [[9]
[5]]
| Apache-2.0 | S+P_Week_2_Lesson_1.ipynb | EgorBEremeev/SoloLearmML-coursera-deeplearning.ai | |
MEDC0106: Bioinformatics in Applied Biomedical Science --------------------------------------------------------------- 06 - Introduction to Pandas*Written by:* Oliver Scott**This notebook provides a general introduction to Pandas.**Do not be afraid to make changes to the code cells to explore how things work! What ... | import pandas as pd
s = pd.Series([1.0, 2.0, 3.0, 5.0])
s | _____no_output_____ | CC-BY-4.0 | workshop/session_2/06_introduction_to_pandas.ipynb | MEDC0106/PythonWorkshop |
Core ComponentsPandas has two core components, the `Series` and the `DataFrame`.The `Series` can be imagined as a single column in a data table, whereas the `DataFrame` can be imagined as a full data table made up of multiple `Series`. Both types have a similar interface allowing a user to perform similar operations. ... | # This is or dictionary containing the raw data
data = {
'PatientID': [556785, 998764, 477822, 678329, 675859],
'Gender': ['M', 'F', 'M', 'M', 'F'],
'Age': [19, 38, 54, 22, 41],
'Outcome': ['Negative', 'Poisitive', 'Positive', 'Negative', 'Negative']
}
# We can now construct a DataFrame like so:
df = p... | _____no_output_____ | CC-BY-4.0 | workshop/session_2/06_introduction_to_pandas.ipynb | MEDC0106/PythonWorkshop |
Often you will be working with very large tables of data making it impractical to view the whole table. Pandas provides a method `.head()` to display the first few n items or `.tail()` for the last few: | # Display the first three rows
df.head(n=3)
# Display the last two rows
df.tail(n=2) | _____no_output_____ | CC-BY-4.0 | workshop/session_2/06_introduction_to_pandas.ipynb | MEDC0106/PythonWorkshop |
Accessing an individual column is easy using the same syntax as a Python dictionary `dict`: | gender_column = df['Gender']
gender_column | _____no_output_____ | CC-BY-4.0 | workshop/session_2/06_introduction_to_pandas.ipynb | MEDC0106/PythonWorkshop |
If the column label is a string you may also use **dot-syntax** to access the column: | age_column = df.Age
age_column | _____no_output_____ | CC-BY-4.0 | workshop/session_2/06_introduction_to_pandas.ipynb | MEDC0106/PythonWorkshop |
Reading DataReading and writing data from/to files in multiple formats is an essential part of the data analysis pipeline. Pandas can read data from file including; CSV, JSON, Excel, SQL and [many more](https://pandas.pydata.org/pandas-docs/stable/reference/io.html).In the folder `data` we have provided a dataset down... | cv_data_path = './data/data_2021-Oct-31.csv' # This is the path to our data
cv_data = pd.read_csv(cv_data_path)
cv_data.head(n=10) | _____no_output_____ | CC-BY-4.0 | workshop/session_2/06_introduction_to_pandas.ipynb | MEDC0106/PythonWorkshop |
We could also easily write this DataFrame to a new CSV file using the method `df.to_csv()`:```pythoncv_data.to_csv('./data/coronavirus_testing_results.csv')```Give it a go. Maybe also saving to a different [format](https://pandas.pydata.org/pandas-docs/stable/reference/io.html)! Essential OperationsNow that we have lo... | cv_data.info() | _____no_output_____ | CC-BY-4.0 | workshop/session_2/06_introduction_to_pandas.ipynb | MEDC0106/PythonWorkshop |
Notice that we have 6 columns of which four are of type `object` (this could be something like a string) and two that are `int64` (integers) (these types correspond the the types used in NumPy). The info also tells us that we have 2466 non-null values and no null-values in this case. Knowing the datatype of ourt column... | cv_data.shape | _____no_output_____ | CC-BY-4.0 | workshop/session_2/06_introduction_to_pandas.ipynb | MEDC0106/PythonWorkshop |
Removing duplicate dataOften input data is noisy and needs cleaning up before we do any further analysis. It is often the case that data contains duplicated rows which is not great when we are trying to do statitical analysis. Luckily Pandas has utilities for dealing with this problem easily. The data we have read doe... | duplicated = cv_data.append(cv_data) # here we have copied the data and added it to itself
duplicated.shape | _____no_output_____ | CC-BY-4.0 | workshop/session_2/06_introduction_to_pandas.ipynb | MEDC0106/PythonWorkshop |
Notice that we have to assign the result of the `append` to a new variable. Here we have copied the data so we wont do anything to the original DataFrame. We can now easily drop the duplicates using the `.drop_duplicates()` [method](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.drop_duplicates.html). It... | duplicated = duplicated.drop_duplicates()
duplicated.shape | _____no_output_____ | CC-BY-4.0 | workshop/session_2/06_introduction_to_pandas.ipynb | MEDC0106/PythonWorkshop |
Notice that the shape is now the same as the original data. Also notice that again we assigned the result to a new variable (with the same name). This technique can get quite annoying so Pandas often offers an argument `inplace` which if we set to `True` allows pandas to perform the operation modifying the original dat... | import numpy as np
n_rows = cv_data.shape[0]
# p is for weighting the choice here it is more likely to choose 1 than None
null_containing_data = np.random.choice([None, 1], n_rows, p=[0.2, 0.8])
null_containing_data | _____no_output_____ | CC-BY-4.0 | workshop/session_2/06_introduction_to_pandas.ipynb | MEDC0106/PythonWorkshop |
Now add a row to the data containing our constructed data: | cv_data['RandomData'] = null_containing_data # make a colum called 'RandomData'
cv_data.head(10) | _____no_output_____ | CC-BY-4.0 | workshop/session_2/06_introduction_to_pandas.ipynb | MEDC0106/PythonWorkshop |
We can also see now that we have null values: | cv_data.info() | _____no_output_____ | CC-BY-4.0 | workshop/session_2/06_introduction_to_pandas.ipynb | MEDC0106/PythonWorkshop |
We can also check the number of null values in each column using `.isnull()`. This returns a dataframe with boolean columns where `True` indicated a null value. We can then use `.sum()` to count the number of `True` values in each column: | cv_data.isnull().sum() | _____no_output_____ | CC-BY-4.0 | workshop/session_2/06_introduction_to_pandas.ipynb | MEDC0106/PythonWorkshop |
When performing data analysis you often have to make the choice to remove missing values or impute them in some way. Removing data is only really recommended if the number of missing data points is relatively small. To remove null values you can simply use the [method](https://pandas.pydata.org/pandas-docs/stable/refer... | # First lets remove rows with null values
remove_rows = cv_data.dropna()
remove_rows.head(10)
remove_rows.shape | _____no_output_____ | CC-BY-4.0 | workshop/session_2/06_introduction_to_pandas.ipynb | MEDC0106/PythonWorkshop |
Now lets change the axis and remove the colum we injected: | cv_data.dropna(axis=1, inplace=True) # We can do it inplace since we do not care about this column
cv_data.head(10) | _____no_output_____ | CC-BY-4.0 | workshop/session_2/06_introduction_to_pandas.ipynb | MEDC0106/PythonWorkshop |
Understanding DataNow that your data is clean(er) than when we started, it is time to do some basic stats to understand the data that we have in each column. This may help inform us how to continue with our analysis and maybe how to plot the data. Pandas provides us with an easy way to get a quick summary of the distr... | cv_data.describe() | _____no_output_____ | CC-BY-4.0 | workshop/session_2/06_introduction_to_pandas.ipynb | MEDC0106/PythonWorkshop |
We can also do the same for categorical columns but we will have to do it seperately: | cv_data.areaName.describe() | _____no_output_____ | CC-BY-4.0 | workshop/session_2/06_introduction_to_pandas.ipynb | MEDC0106/PythonWorkshop |
This shows us that in this dataset there are four unique area names with 'England' being the most frequent with a frequency of 640. We can also check the unique values using the `.unique()` method: | cv_data.areaName.unique() | _____no_output_____ | CC-BY-4.0 | workshop/session_2/06_introduction_to_pandas.ipynb | MEDC0106/PythonWorkshop |
We can see that the dataset contains data for:- England- Northern Ireland- Scotland- WalesBut how many times are these values recorded? We can use the method `.value_counts()` to find out: | cv_data.areaName.value_counts() | _____no_output_____ | CC-BY-4.0 | workshop/session_2/06_introduction_to_pandas.ipynb | MEDC0106/PythonWorkshop |
Slicing and SelectingIn the previous section we saw how to produce summaries of the entire data which is useful however, sometimes we will want to perform analysis on certain subsets of data. We have already seen how to extract a column of data using square brackets and dot-syntax `df['col'] / df.col` and now we will ... | type(cv_data['areaName']) | _____no_output_____ | CC-BY-4.0 | workshop/session_2/06_introduction_to_pandas.ipynb | MEDC0106/PythonWorkshop |
If you wish to access it as a dataframe you can supply the column name as a list: | type(cv_data[['areaName']]) | _____no_output_____ | CC-BY-4.0 | workshop/session_2/06_introduction_to_pandas.ipynb | MEDC0106/PythonWorkshop |
Adding another column to our selection is a simple as adding another column name to the list. Obviosuly inh this case our code will return a `DataFrame`: | selection = cv_data[['areaName', 'areaCode']]
selection.head(5) | _____no_output_____ | CC-BY-4.0 | workshop/session_2/06_introduction_to_pandas.ipynb | MEDC0106/PythonWorkshop |
Selecting by rowsSelecting rows is a little trickier with two methods:- `.loc`: locate by name- `.iloc`: locate by numerical indexConsidering that our data has a numerical index it makes sense for us to use `.iloc`. If our data has an index using strings `.loc` would be the correct solution if we want to select using... | cv_data.loc[222] # Return the row with index 222 | _____no_output_____ | CC-BY-4.0 | workshop/session_2/06_introduction_to_pandas.ipynb | MEDC0106/PythonWorkshop |
Since Pandas is backed by NumPy we can also use slices to select a range of data: | cv_data.loc[222:226] | _____no_output_____ | CC-BY-4.0 | workshop/session_2/06_introduction_to_pandas.ipynb | MEDC0106/PythonWorkshop |
Conditional SelectionsSelecting data by index can be useful, but if we do not know what dat the indexes correspond too this can be limiting. Perhaps we are only interested in the data from Wales, we can use conditional selections to make informed selections.Pandas like numpy can be indexed using a boolean array/Series... | ind = cv_data['areaName'] == 'Wales' # A boolean Series
ind.tail(5) | _____no_output_____ | CC-BY-4.0 | workshop/session_2/06_introduction_to_pandas.ipynb | MEDC0106/PythonWorkshop |
Using this boolean Series we can index the DataFrame! | wales_data = cv_data[ind]
wales_data.head(5) | _____no_output_____ | CC-BY-4.0 | workshop/session_2/06_introduction_to_pandas.ipynb | MEDC0106/PythonWorkshop |
We can simplify this quite nicely into a one line expression: | wales_data = cv_data[cv_data['areaName'] == 'Wales']
wales_data.head(5) | _____no_output_____ | CC-BY-4.0 | workshop/session_2/06_introduction_to_pandas.ipynb | MEDC0106/PythonWorkshop |
Of course we can apply this to numerical columns also: | # Select rows where reported positives is less than 100
cv_data[cv_data['newCasesByPublishDate'] < 100].head(5) | _____no_output_____ | CC-BY-4.0 | workshop/session_2/06_introduction_to_pandas.ipynb | MEDC0106/PythonWorkshop |
Chaining conditional expressions allows us to create powerful selections. For this we can use the logical operators `|` and `&`. Remeber to put seperate conditions in brackets! | # Count dates in england with reported positive results > 10,000
cv_data[(cv_data['areaName'] == 'England') & (cv_data['newCasesByPublishDate'] > 10000)].shape | _____no_output_____ | CC-BY-4.0 | workshop/session_2/06_introduction_to_pandas.ipynb | MEDC0106/PythonWorkshop |
ArithmeticBasic arithmentic operations can be applied in the same way as NumPy arrays, so we will quickly brush over it: | cv_data.newCasesByPublishDate / 100 # divide a column by 100 return a Series | _____no_output_____ | CC-BY-4.0 | workshop/session_2/06_introduction_to_pandas.ipynb | MEDC0106/PythonWorkshop |
You may also perform arithmetic between columns: | cv_data.newCasesByPublishDate + cv_data.cumCasesByPublishDate | _____no_output_____ | CC-BY-4.0 | workshop/session_2/06_introduction_to_pandas.ipynb | MEDC0106/PythonWorkshop |
You can insert a new column with the result: | cv_data['Rubbish'] = cv_data.newCasesByPublishDate * 0.3 / cv_data.cumCasesByPublishDate
cv_data.head(5) | _____no_output_____ | CC-BY-4.0 | workshop/session_2/06_introduction_to_pandas.ipynb | MEDC0106/PythonWorkshop |
Pandas also provides some handy utility functions: | print(cv_data.newCasesByPublishDate.mean())
print(cv_data.newCasesByPublishDate.std()) | _____no_output_____ | CC-BY-4.0 | workshop/session_2/06_introduction_to_pandas.ipynb | MEDC0106/PythonWorkshop |
Applying FunctionsWhile it is possible to iterate over a DataFrame/Series like a NumPy array, it is slow in Python so instead we can use the `.apply()` function to apply a function to each element in a column or across columns. We can also save this result to a new column. Let's create an arbritary function that we ca... | def categorize_cases(x):
if x >= 10000:
return 'High'
elif x <= 200:
return 'Low'
else:
return 'Medium' | _____no_output_____ | CC-BY-4.0 | workshop/session_2/06_introduction_to_pandas.ipynb | MEDC0106/PythonWorkshop |
The above function categorises a case count into arbritarty categories: 'High', 'Medium' and 'Low'. Now we can apply this to the column 'newCasesByPublishDate': | cv_data['Category'] = cv_data['newCasesByPublishDate'].apply(categorize_cases)
cv_data.head(10) | _____no_output_____ | CC-BY-4.0 | workshop/session_2/06_introduction_to_pandas.ipynb | MEDC0106/PythonWorkshop |
Users often will use anonymous functions instead of defining an explicit function like above: | cv_data['newCategory'] = cv_data['newCasesByPublishDate'].apply(lambda x: 'Red' if x >= 20000 else 'Amber')
cv_data.head(10) | _____no_output_____ | CC-BY-4.0 | workshop/session_2/06_introduction_to_pandas.ipynb | MEDC0106/PythonWorkshop |
Time-SeriesSome of you may have notices that one of the columns contains dates as a string (object). This isnt paticularly useful to us in this form. Pandas however has a datetime type which we can use to make some more intelligent selections based on time spans. First we need to tell pandas that our column is a datet... | cv_data['date'] = pd.to_datetime(cv_data['date'])
cv_data.info() | _____no_output_____ | CC-BY-4.0 | workshop/session_2/06_introduction_to_pandas.ipynb | MEDC0106/PythonWorkshop |
Now we have the date in this form we can make selections within time ranges using the `.between()` method: | # Lets select data between the 20th and the 30th October 2021 and restrict it to England
selection = cv_data[(cv_data.date.between('2021-10-20','2021-10-30')) & (cv_data.areaName == 'England')]
selection.head(10) | _____no_output_____ | CC-BY-4.0 | workshop/session_2/06_introduction_to_pandas.ipynb | MEDC0106/PythonWorkshop |
Working with time-series data is even more powerful if we use the time as our index. Lets first only consider 'Scotland' in our analysis | scotland_data = pd.DataFrame(cv_data[cv_data.areaName == 'Scotland']) # also copy into a new DataFrame | _____no_output_____ | CC-BY-4.0 | workshop/session_2/06_introduction_to_pandas.ipynb | MEDC0106/PythonWorkshop |
Now we can set the index of the 'scotland_data' DataFrame as the index: | scotland_data.set_index('date', inplace=True)
scotland_data.head(5) | _____no_output_____ | CC-BY-4.0 | workshop/session_2/06_introduction_to_pandas.ipynb | MEDC0106/PythonWorkshop |
You may have noticed that the data is in time-decending order, often we we will want to reverse this ordering. Now that the index is the date we can sort it easilt using the `.sort_index()` method: | scotland_data.sort_index(inplace=True)
scotland_data.head(5) | _____no_output_____ | CC-BY-4.0 | workshop/session_2/06_introduction_to_pandas.ipynb | MEDC0106/PythonWorkshop |
Also we can simply use slicing to select a data range with `.loc`! | scotland_data.loc['2021-10-20':'2021-10-30'] | _____no_output_____ | CC-BY-4.0 | workshop/session_2/06_introduction_to_pandas.ipynb | MEDC0106/PythonWorkshop |
We can resample time-series data into different intervals and get a mean value for that interval. Below we resmaple the data into 10-day intervals and calculate the mean of 'newCasesByPublishDate': | scotland_data.resample(rule='10d')['newCasesByPublishDate'].mean() | _____no_output_____ | CC-BY-4.0 | workshop/session_2/06_introduction_to_pandas.ipynb | MEDC0106/PythonWorkshop |
Instead of mean you could use other functions such as `min()`, `max()`, `sum()` etc. Indeed you can also calculate a rolling statistic using `.rolling()` and a window size. Here we will calculate a rolling average using a ten day window: | scotland_data['rollingAvgTenDay'] = scotland_data.rolling(10)['newCasesByPublishDate'].mean()
scotland_data.head(20) | _____no_output_____ | CC-BY-4.0 | workshop/session_2/06_introduction_to_pandas.ipynb | MEDC0106/PythonWorkshop |
PlottingPandas allows the visualisation of data in DataFrames/Series interfacing with the plotting package [matplotlib](https://matplotlib.org/). Displaying the plots will first require that import matplotlib: | # We also add this 'Jupyter magic' to display plots in the notebook.
%matplotlib inline
import matplotlib.pyplot as plt | _____no_output_____ | CC-BY-4.0 | workshop/session_2/06_introduction_to_pandas.ipynb | MEDC0106/PythonWorkshop |
Now creating a plot with pandas is as simple as calling `.plot()` on some selected data! | scotland_data.newCasesByPublishDate.plot(); # We also add the semicolon when plotting in Jupyter | _____no_output_____ | CC-BY-4.0 | workshop/session_2/06_introduction_to_pandas.ipynb | MEDC0106/PythonWorkshop |
We could have also achieved the same result using the syntax:```pythonscotland_data.newCasesByPublishDate.plot.line()```These plotting functions also have many [arguments](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.plot.html) which you can specify to tune the look of your plots. Thes arguments are pa... | # Select a time window (1-month)
window = scotland_data['2021-09-30':'2021-10-30']
window.newCasesByPublishDate.plot.box(); | _____no_output_____ | CC-BY-4.0 | workshop/session_2/06_introduction_to_pandas.ipynb | MEDC0106/PythonWorkshop |
How about we plot the raw data along with the 10 day rolling average: | scotland_data.newCasesByPublishDate.plot(figsize=(12, 8)) # also specify the size!
scotland_data.rollingAvgTenDay.plot()
plt.legend(); # We can also add a legend using matplotlib! | _____no_output_____ | CC-BY-4.0 | workshop/session_2/06_introduction_to_pandas.ipynb | MEDC0106/PythonWorkshop |
We can also save figures using `.savefig()`, check the data directory! | figure = scotland_data.newCasesByPublishDate.plot(figsize=(12, 8)).get_figure()
figure.savefig('./data/Scotland_2021-Oct-31.png'); | _____no_output_____ | CC-BY-4.0 | workshop/session_2/06_introduction_to_pandas.ipynb | MEDC0106/PythonWorkshop |
Introduction to GalSim HubAuthors: [@EiffL](https://github.com/EiffL)This notebook contains a short introduction to using GalSim-Hub for samplingrandomly generated galaxy light profiles, and drawing them using GalSim. Setting up the environmentBesides GalSim, GalSim-Hub requires TensorFlow (version 1.15, for stabili... | # Activating TensorFlow v1.15 environment on Colab
%tensorflow_version 1.x
# Installing and updating conda for Python 3.6
!wget https://repo.continuum.io/miniconda/Miniconda3-4.5.4-Linux-x86_64.sh && bash Miniconda3-4.5.4-Linux-x86_64.sh -bfp /usr/local
!conda install --channel defaults conda python=3.6 --yes
!conda up... | _____no_output_____ | MIT | notebooks/GalsimHubDemo.ipynb | Hbretonniere/galsim_hub |
And finally, installing GalSim Hub itself: | !pip install --no-deps git+https://github.com/McWilliamsCenter/galsim_hub.git | _____no_output_____ | MIT | notebooks/GalsimHubDemo.ipynb | Hbretonniere/galsim_hub |
Loading and Using generative models from PythonThe first step is to load a generative model. This is done by creating an instance of the `galsim_hub.GenerativeGalaxyModel` class, either by providing a local path to a model directory, or much more conveniently, byusing the `hub:xxxxxx` syntax, where `xxxxxx` is the nam... | import galsim
import galsim_hub
model = galsim_hub.GenerativeGalaxyModel('hub:Lanusse2020') | _____no_output_____ | MIT | notebooks/GalsimHubDemo.ipynb | Hbretonniere/galsim_hub |
Behind the scene, the generative model has been downloaded from the repository,and is now ready to use.Models can be conditional, i.e. generating a light profile given some particular attributes as inputs. To introspect the model, and see what inputs are expected, you can use the `quantities` attribute: | model.quantities | _____no_output_____ | MIT | notebooks/GalsimHubDemo.ipynb | Hbretonniere/galsim_hub |
We see that this model generates light profiles, given a particular magnitude, redshift, and size.Other interesting properties saved with the model (but knowledge of which is not necessary) are the native stamp size, and native pixel size at which the generative model is producing light profiles: | # Pixel size, in arcsec
model.pixel_size
# Stamp size
model.stamp_size | _____no_output_____ | MIT | notebooks/GalsimHubDemo.ipynb | Hbretonniere/galsim_hub |
Now that the model is loaded, and that we know what inputs it expects, we can create a catalog listing some desired input quantities: | from astropy.table import Table
catalog = Table([[5., 10. ,20.], [24., 24., 24.], [0.5, 0.5, 0.5] ],
names=['flux_radius', 'mag_auto', 'zphot']) | _____no_output_____ | MIT | notebooks/GalsimHubDemo.ipynb | Hbretonniere/galsim_hub |
In this example, we want 3 galaxies, all at the same i-band magnitude of 24, and redshift 0.5, but with different and increasing size.We can now sample actual GalSim light profiles with those properties from the model using the `sample()` method: | # Sample light profiles for these parameters
profiles = model.sample(catalog) | _____no_output_____ | MIT | notebooks/GalsimHubDemo.ipynb | Hbretonniere/galsim_hub |
This returns a list of 3 profiles, represented by `galsim.InterpolatedImage` objects: | profiles[0] | _____no_output_____ | MIT | notebooks/GalsimHubDemo.ipynb | Hbretonniere/galsim_hub |
**These objects can now be manipulated inside GalSim as any other light profile.**For instance, we can convolve these images with a PSF and add some observational noise: | %pylab inline
PSF = galsim.Gaussian(fwhm=0.06)
figure(figsize=(10,5))
for i in range(3):
# Convolving light profile with PSF
gal = galsim.Convolve(profiles[i], PSF)
# Drawing postage stamp of any desired size and pixel scale
im = gal.drawImage(nx=96, ny=96, scale=0.03)
# Adding some noise for realism
... | Populating the interactive namespace from numpy and matplotlib
| MIT | notebooks/GalsimHubDemo.ipynb | Hbretonniere/galsim_hub |
And voila! Using generative models directly from YamlGalSim Hub also provides a driver for using generative models direclty from a GalSim Yaml script. In this section, we will illustrate how to write such a script and execute it from the command line.Let's retrieve a script from the example folder of GalSim Hub: | !wget -q https://raw.githubusercontent.com/McWilliamsCenter/galsim_hub/master/examples/demo14.yaml
!cat demo14.yaml | modules:
- galsim_hub
psf :
type : Gaussian
sigma : 0.06 # arcsec
# Define the galaxy profile
gal :
type : GenerativeModelGalaxy
flux_radius : { type : Random , min : 5, max : 10 }
mag_auto : { type : Random , min : 24., max : 25. }
# The image field specifies some other information about th... | MIT | notebooks/GalsimHubDemo.ipynb | Hbretonniere/galsim_hub |
Note the following points that are directly related to generative models: - In the preamble of the file, we load the `galsim_hub` module - In the galaxy section, we use the `GenerativeModelGalaxy` type, and provide some input distributions for the input quantities used by the model - In the `input` section, we provi... | !python /galsim demo14.yaml | _____no_output_____ | MIT | notebooks/GalsimHubDemo.ipynb | Hbretonniere/galsim_hub |
This should generate a fits file corresponding to the Yaml description. Unfortunately, couldn't manage to get it to work yet on this hybrid conda/google environment... Suggestions welcome :-) | _____no_output_____ | MIT | notebooks/GalsimHubDemo.ipynb | Hbretonniere/galsim_hub | |
CST_ALL_PTMs_NormalizationThis notebook will make the case for normalizing the distributions of PTM levels in all cell lines. I will combine the PTM data from all cell lines and look at the average properties of all PTM distributions in all cell lines. imports and function definitions | # imports and plotting defaults
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
import matplotlib
matplotlib.style.use('ggplot')
from copy import deepcopy
# use clustergrammer module to load/process (source code in clustergrammer directory)
from clustergrammer import Network
... | _____no_output_____ | MIT | notebooks/CST_ALL_PTMs_Normalization.ipynb | MaayanLab/cst_drug_treatment |
Load all PTM data and combine into single dataframe | filename = '../lung_cellline_3_1_16/lung_cl_all_ptm/all_ptm_ratios.tsv'
df_all = load_data(filename)
df_all.count().sort_values().plot(kind='bar', figsize=(10,2))
plot_cl_boxplot_with_missing_data(df_all) | _____no_output_____ | MIT | notebooks/CST_ALL_PTMs_Normalization.ipynb | MaayanLab/cst_drug_treatment |
Merge Plex-duplicate cell lines | filename = '../lung_cellline_3_1_16/lung_cl_all_ptm/all_ptm_ratios_uni_cl.tsv'
df_all = load_data(filename)
df_all.count().sort_values().plot(kind='bar', figsize=(10,2))
plot_cl_boxplot_with_missing_data(df_all) | _____no_output_____ | MIT | notebooks/CST_ALL_PTMs_Normalization.ipynb | MaayanLab/cst_drug_treatment |
Zscore rows | df_tmp = deepcopy(df_all)
df_tmp = df_tmp.transpose()
zdf_all = (df_tmp - df_tmp.mean())/df_tmp.std()
zdf_all = zdf_all.transpose()
print(zdf_all.shape)
zdf_all.count().sort_values().plot(kind='bar', figsize=(10,2))
plot_cl_boxplot_with_missing_data(zdf_all) | _____no_output_____ | MIT | notebooks/CST_ALL_PTMs_Normalization.ipynb | MaayanLab/cst_drug_treatment |
Run the following cell to generate an index sorted alphabetically by lowercase term local name. Omit this index if the terms have opaque local names. | # generate the index of terms grouped by category and sorted alphabetically by lowercase term local name
text = '### 3.1 Index By Term Name\n\n'
text += '(See also [3.2 Index By Label](#32-index-by-label))\n\n'
for category in range(0,len(display_order)):
text += '**' + display_label[category] + '**\n'
text +=... | _____no_output_____ | CC-BY-4.0 | code/build_format_cv/build-page-categories.ipynb | edwbaker/ac |
Run the following cell to generate an index by term label | text = '\n\n'
# Comment out the following two lines if there is no index by local names
#text = '### 3.2 Index By Label\n\n'
#text += '(See also [3.1 Index By Term Name](#31-index-by-term-name))\n\n'
for category in range(0,len(display_order)):
if organized_in_categories:
text += '**' + display_label[categ... | _____no_output_____ | CC-BY-4.0 | code/build_format_cv/build-page-categories.ipynb | edwbaker/ac |
Modify to display the indices that you want | text = index_by_label + term_table
#text = index_by_name + index_by_label + term_table
# read in header and footer, merge with terms table, and output
headerObject = open(headerFileName, 'rt', encoding='utf-8')
header = headerObject.read()
headerObject.close()
footerObject = open(footerFileName, 'rt', encoding='utf-8... | _____no_output_____ | CC-BY-4.0 | code/build_format_cv/build-page-categories.ipynb | edwbaker/ac |
**Download** (right-click, save target as ...) this page as a jupyterlab notebook from: [Lab14](http://54.243.252.9/engr-1330-webroot/8-Labs/Lab14/Lab14.ipynb)___ Laboratory 14: Causality, Simulation, and Probability LAST NAME, FIRST NAMER00000000ENGR 1330 Laboratory 14 - In-Lab | # Preamble script block to identify host, user, and kernel
import sys
! hostname
! whoami
print(sys.executable)
print(sys.version)
print(sys.version_info) | atomickitty
sensei
/opt/jupyterhub/bin/python3
3.8.10 (default, Sep 28 2021, 16:10:42)
[GCC 9.3.0]
sys.version_info(major=3, minor=8, micro=10, releaselevel='final', serial=0)
| CC0-1.0 | 8-Labs/Lab14/old_src/.ipynb_checkpoints/Lab14-checkpoint.ipynb | dustykat/engr-1330-psuedo-course |
--- Python for Simulation What is Russian roulette?>Russian roulette (Russian: русская рулетка, russkaya ruletka) is a lethal game of chance in which a player places a single round in a revolver, spins the cylinder, places the muzzle against their head, and pulls the trigger in hopes that the loaded chamber does not a... | import numpy as np #import numpy
revolver = np.array([1,0,0,0,0,0]) #create a numpy array with 1 bullet and 5 empty chambers
print(np.random.choice(revolver,2)) #randomly select a value from revolver - simulation
print(np.random.choice(revolver,5))
print(np.random.choice(revolver,10... | [0 0 0 1 0 0 0 0 0 0]
| CC0-1.0 | 8-Labs/Lab14/old_src/.ipynb_checkpoints/Lab14-checkpoint.ipynb | dustykat/engr-1330-psuedo-course |
 ___ Example: Simulate the results of throwing a D6 (regular dice) for 10 times. | import numpy as np #import numpy
dice = np.array([1,2,3,4,5,6]) #create a numpy array with values of a D6
np.random.choice(dice,10) #randomly selecting a value from dice for 10 times- simulation | _____no_output_____ | CC0-1.0 | 8-Labs/Lab14/old_src/.ipynb_checkpoints/Lab14-checkpoint.ipynb | dustykat/engr-1330-psuedo-course |
___ Example: Assume the following rules:- If the dice shows 1 or 2 spots, my net gain is -1 dollar.- If the dice shows 3 or 4 spots, my net gain is 0 dollars.- If the dice shows 5 or 6 spots, my net gain is 1 dollar.__Define a function to simulate a game with the above rules, assuming a D6, and compute the net gain of ... | def D6game(nrolls):
import numpy as np #import numpy
dice = np.array([1,2,3,4,5,6]) #create a numpy array with values of a D6
rolls = np.random.choice(dice,nrolls) #randomly selecting a value from dice for nrolls times- simulation
gainlist =[] #crea... | _____no_output_____ | CC0-1.0 | 8-Labs/Lab14/old_src/.ipynb_checkpoints/Lab14-checkpoint.ipynb | dustykat/engr-1330-psuedo-course |
 Let's Make A Deal Game Show and Monty Hall Problem __The Monty Hall problem is a brain teaser, in the form of a probability puzzle, loosely based on the American television game show Let's Make... | def othergoat(x): #Define a function to return "the other goat"!
if x == "Goat 1":
return "Goat 2"
elif x == "Goat 2":
return "Goat 1"
Doors = np.array(["Car","Goat 1","Goat 2"]) #Define a list for objects behind the doors
goats = np.array(["Goat 1" , "Goat 2"]) #Define a li... | _____no_output_____ | CC0-1.0 | 8-Labs/Lab14/old_src/.ipynb_checkpoints/Lab14-checkpoint.ipynb | dustykat/engr-1330-psuedo-course |
__According to the plot, it is statitically beneficial for the players to switch doors because the initial chance for being correct is only 1/3__  Python for Probability  Important Terminology: __Experimen... | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt | _____no_output_____ | CC0-1.0 | 8-Labs/Lab14/old_src/.ipynb_checkpoints/Lab14-checkpoint.ipynb | dustykat/engr-1330-psuedo-course |
___ Example: In a game of Russian Roulette, the chance of surviving each round is 5/6 which is almost 83%. Using a for loop, compute probability of surviving - For 2 rounds- For 5 rounds- For 10 rounds | nrounds =[]
probs =[]
for i in range(3):
nrounds.append(i)
probs.append((5/6)**i) #probability of surviving- not getting the bullet!
RRDF = pd.DataFrame({"# of Rounds": nrounds, "Probability of Surviving": probs})
RRDF
nrounds =[]
probs =[]
for i in range(6):
nrounds.append(i)
probs.append((5/6)**i) ... | _____no_output_____ | CC0-1.0 | 8-Labs/Lab14/old_src/.ipynb_checkpoints/Lab14-checkpoint.ipynb | dustykat/engr-1330-psuedo-course |
___ Example: What will be the probability of constantly throwing an even number with a D20 in- For 2 rolls- For 5 rolls- For 10 rolls- For 15 rolls | nrolls =[]
probs =[]
for i in range(1,16,1):
nrolls.append(i)
probs.append((1/2)**i) #probability of throwing an even number-10/20 or 1/2
DRDF = pd.DataFrame({"# of Rolls": nrolls, "Probability of constantly throwing an even number": probs})
DRDF
DRDF.plot.scatter(x="# of Rolls", y="Probability of constantly ... | _____no_output_____ | CC0-1.0 | 8-Labs/Lab14/old_src/.ipynb_checkpoints/Lab14-checkpoint.ipynb | dustykat/engr-1330-psuedo-course |
___ Example: What will be the probability of throwing at least one 6 with a D6:- For 2 rolls- For 5 rolls- For 10 rolls- For 50 rolls - Make a scatter plot for this one! | nRolls =[]
probs =[]
for i in range(1,3,1):
nRolls.append(i)
probs.append(1-(5/6)**i) #probability of at least one 6: 1-(5/6)
rollsDF = pd.DataFrame({"# of Rolls": nRolls, "Probability of rolling at least one 6": probs})
rollsDF
nRolls =[]
probs =[]
for i in range(1,6,1):
nRolls.append(i)
probs.appen... | _____no_output_____ | CC0-1.0 | 8-Labs/Lab14/old_src/.ipynb_checkpoints/Lab14-checkpoint.ipynb | dustykat/engr-1330-psuedo-course |
___ Example: What is the probability of drawing an ace at least once (with replacement):- in 2 tries- in 5 tries- in 10 tries- in 20 tries - make a scatter plot. | nDraws =[]
probs =[]
for i in range(1,3,1):
nDraws.append(i)
probs.append(1-(48/52)**i) #probability of drawing an ace least once : 1-(48/52)
DrawsDF = pd.DataFrame({"# of Draws": nDraws, "Probability of drawing an ace at least once": probs})
DrawsDF
nDraws =[]
probs =[]
for i in range(1,6,1):
nDraws.app... | _____no_output_____ | CC0-1.0 | 8-Labs/Lab14/old_src/.ipynb_checkpoints/Lab14-checkpoint.ipynb | dustykat/engr-1330-psuedo-course |
___ Example: - A) Write a function to find the probability of an event in percentage form based on given outcomes and sample space- B) Use the function and compute the probability of rolling a 4 with a D6- C) Use the function and compute the probability of drawing a King from a standard deck of cards- D) Use the functi... | # A
# Create function that returns probability percent rounded to one decimal place
def Prob(outcome, sampspace):
probability = (outcome / sampspace) * 100
return round(probability, 1)
# B
outcome = 1 #Rolling a 4 is only one of the possible outcomes
space = 6 #Rolling a D6 can have 6 different ou... | Probability of drawing a royal flush is 1.5473203199999998e-06 %
| CC0-1.0 | 8-Labs/Lab14/old_src/.ipynb_checkpoints/Lab14-checkpoint.ipynb | dustykat/engr-1330-psuedo-course |
___ Example: Two unbiased dice are thrown once and the total score is observed. Define an appropriate function and use a simulation to find the estimated probability that :- the total score is greater than 10?- the total score is even and greater than 7?__This problem is designed based on an example by *Elliott Saslow*... | import numpy as np
def DiceRoll1(nSimulation):
count =0
dice = np.array([1,2,3,4,5,6]) #create a numpy array with values of a D6
for i in range(nSimulation):
die1 = np.random.choice(dice,1) #randomly selecting a value from dice - throw the D6 once
die2 = np.random.choice(dice,1) ... | The probability of rolling an even number and greater than 7 after 10000 rolls is: 24.77 %
| CC0-1.0 | 8-Labs/Lab14/old_src/.ipynb_checkpoints/Lab14-checkpoint.ipynb | dustykat/engr-1330-psuedo-course |
___ Example: An urn contains 10 white balls, 20 reds and 30 greens. We want to draw 5 balls with replacement. Use a simulation (10000 trials) to find the estimated probability that:- we draw 3 white and 2 red balls- we draw 5 balls of the same color__This problem is designed based on an example by *Elliott Saslow*from ... | # A
import numpy as np
import random
d = {} #Create an empty dictionary to associate numbers and colors
for i in range(0,60,1): #total of 60 balls
if i <10: #10 white balls
d[i]="White"
elif i>9 and i<30: #20 red balls
d[i]="Red"
else: ... | The probability of drawing 3 white and 2 red balls is 0.53 %
The probability of drawing 5 balls of the same color is 3.8 %
| CC0-1.0 | 8-Labs/Lab14/old_src/.ipynb_checkpoints/Lab14-checkpoint.ipynb | dustykat/engr-1330-psuedo-course |
NOMIS API DevelopmentShortly after this paper was accepted, I received a very helpful reply from NOMIS relating to the fact that I couldn't seem to get their API helper to give me the query needed to retrieve each of the data sets used in this research directly (which would make replication much, much faster and easie... | # 2011 TTW Data (need a different geography TYPE304 for 2001)
url = ('http://www.nomisweb.co.uk/api/v01/dataset/',
'NM_568_1.bulk.csv?',
'date=latest&',
'geography=2013265927TYPE298&',
'rural_urban=0&',
'cell=0...12&',
'measures=20100&',
'select=date_name,geography_name,... | http://www.nomisweb.co.uk/api/v01/dataset/NM_568_1.bulk.csv?date=latest&geography=2013265927TYPE304&rural_urban=0&cell=0...12&measures=20100&select=date_name,geography_name,geography_code,rural_urban_name,cell_name,measures_name,obs_value,obs_status_name
| MIT | NOMIS API Test.ipynb | FoxyAI/urb-studies-predicting-gentrification |
Exercise 1 - Toffoli gate | from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit import IBMQ, Aer, execute
from ibm_quantum_widgets import CircuitComposer
editorEx = CircuitComposer()
editorEx
import math
pi=math.pi
# You can also build your circuit programmatically using Qiskit code
circuit = QuantumCircuit(3)
theta... | _____no_output_____ | Apache-2.0 | solutions by participants/ex1/ex1-InnanNouhaila-79cost.ipynb | fazliberkordek/ibm-quantum-challenge-2021 |
1. Load data- I'm using the files that were updated at **April 21st**- ref : https://github.com/jihoo-kim/Data-Science-for-COVID-19- datasets - Region.csv → Region_sido_addPop_addHospital.csv - PatientInfo.csv - 흡연율-성-연령별.csv | # Prepare dataset
Region_df = pd.read_csv('../dataset/Region_sido_addPop_addHospital.csv')[['province', 'safe_hospitals_count', 'infection_hospitals_count', 'infection_hospitals_bed_num']]
Smoke_df = pd.read_csv('../dataset/흡연율_성_연령별.csv')
Smoke_df = Smoke_df.rename(columns={'성별':'sex','연령별':'age','분율':'smoking_rate'}... | _____no_output_____ | MIT | dacon_covid-19/ML/COVID_ML_05_XGBoost-GridSearchCV-final-model.ipynb | sam351/competitions |
2. Preprocess data- selected features : **'sex', 'birth_year', 'age', 'province', 'disease (98.9% NaN)', 'infection_case (34.1% NaN)', 'symptom_onset_date (86.2% NaN)', 'confirmed_date', 'contact_number (75.4% NaN)''**- dropped features after validation : 'country', 'city', 'infection_order (98.3% NaN)- handling nan ... | # Select features
X_features = PatientInfo_df[['sex', 'birth_year', 'age', 'province', 'disease', 'infection_case',
'symptom_onset_date', 'confirmed_date', 'contact_number']].copy()
y_target = PatientInfo_df[['state']].copy()
print(f'X_features.shape : {X_features.shape}')
print(f'y_target... | _____no_output_____ | MIT | dacon_covid-19/ML/COVID_ML_05_XGBoost-GridSearchCV-final-model.ipynb | sam351/competitions |
3. Split data into train, val, test- It's important that **labels are highly unbalanced** (only about 3% is deceased)- Since the dataset is quite small(1704 records), I will split the date into **6:2:2** for now (test data could be added from the next file update)- Since the labels are highly imbalanced, it's better t... | # Get train dataset
X_train_val, X_test, y_train_val, y_test = train_test_split(X_features_processed, y_target_processed, test_size=0.2,
random_state=0, stratify=y_target_processed)
# Get val & test dataset
X_train, X_val, y_train, y_val = train_test_split(X... | < Percentage of each label (whole dataset) >
0 96.044864
1 3.955136
Name: state_deceased, dtype: float64
< Percentage of each label (Train dataset) > - size of dataset : 907
0 96.030871
1 3.969129
Name: state_deceased, dtype: float64
< Percentage of each label (Validation dataset) > - size of dataset : ... | MIT | dacon_covid-19/ML/COVID_ML_05_XGBoost-GridSearchCV-final-model.ipynb | sam351/competitions |
4. Train model - XGBoost with GridSearchCV | # Look for best hyper-parameters
start = time.time()
# Train model
xgb = XGBClassifier(random_state=0, n_jobs=-1)
xgb_param = {
'n_estimators': [100, 200, 300, 400],
'min_child_weight': [1, 2, 3],
'gamma': [1.5, 2, 2.5, 3],
'colsample_bytree': [0.7, 0.8, 0.9],
'max_depth': [5, 6, 7, 8, 9, 10]
}
gr... | _____no_output_____ | MIT | dacon_covid-19/ML/COVID_ML_05_XGBoost-GridSearchCV-final-model.ipynb | sam351/competitions |
Style TransferWe are optimising the input image to reduce loss between output of convolutional layers(compared with output from layers when we pass the style/content image) of VGG16 model(we don't optimise weights since they are pretrained). Also we use the optimized input image as final prediction instead of output f... | import tensorflow as tf
if tf.__version__.startswith('2'):
tf.compat.v1.disable_eager_execution()
from tensorflow.keras.layers import Input, Lambda, Dense, Flatten
from tensorflow.keras.layers import AveragePooling2D, MaxPooling2D
from tensorflow.keras.layers import Conv2D
from tensorflow.keras.models import Model... | _____no_output_____ | MIT | NeuralStyleTransfer/StyleTransfer.ipynb | Frostday/Small-Tensorflow-Projects |
Transfer Learning Part | def VGG16_AvgPool(shape):
# we want to account for features across the entire image so get rid of the maxpool which throws away information and use average # pooling instead.
vgg = VGG16(input_shape=shape, weights='imagenet', include_top=False)
i = vgg.input
x = i
for layer in vgg.layers:
... | _____no_output_____ | MIT | NeuralStyleTransfer/StyleTransfer.ipynb | Frostday/Small-Tensorflow-Projects |
Processing | # load the content image
def load_img_and_preprocess(path, shape=None):
img = image.load_img(path, target_size=shape)
# convert image to array and preprocess for vgg
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)
return x
# since VGG accepts BGR this function allows us t... | _____no_output_____ | MIT | NeuralStyleTransfer/StyleTransfer.ipynb | Frostday/Small-Tensorflow-Projects |
Style lossConverting output to gram matrix and calculating style loss | def gram_matrix(img):
# input is (H, W, C) (C = # feature maps)
# we first need to convert it to (C, H*W)
X = K.batch_flatten(K.permute_dimensions(img, (2, 0, 1)))
# now, calculate the gram matrix
# gram = XX^T / N
# the constant is not important since we'll be weighting these
G = K.dot(X, K.transpose(... | _____no_output_____ | MIT | NeuralStyleTransfer/StyleTransfer.ipynb | Frostday/Small-Tensorflow-Projects |
Minimizing loss and optimising image(training) | # function to minimise loss by optimising input image
def minimize(fn, epochs, batch_shape, content_image):
t0 = datetime.now()
losses = []
# x = np.random.randn(np.prod(batch_shape))
x = content_image
for i in range(epochs):
x, l, _ = fmin_l_bfgs_b(
func=fn,
x0=x,
maxfun=20
)
x ... | _____no_output_____ | MIT | NeuralStyleTransfer/StyleTransfer.ipynb | Frostday/Small-Tensorflow-Projects |
Modelling | content_path = 'images/content/elephant.jpg'
style_path = 'images/style/lesdemoisellesdavignon.jpg'
x = load_img_and_preprocess(content_path)
h, w = x.shape[1:3]
# reduce image size while keeping ratio of dimensions same
i = 2
h_new = h
w_new = w
while h_new > 400 or w_new > 400:
h_new = h/i
w_new = w/i
i... | _____no_output_____ | MIT | NeuralStyleTransfer/StyleTransfer.ipynb | Frostday/Small-Tensorflow-Projects |
ST0256 - Análisis NuméricoCapítulo 5: Diferenciación e integración numérica2021/01MEDELLÍN - COLOMBIA Text provided under a Creative Commons Attribution license, CC-BY. All code is made available under the FSF-approved MIT license.(c) Carlos Alberto Alvarez Henao *** ***Docente:*** Carlos Alberto Álvarez Henao, I.... | import numpy as np
import matplotlib.pyplot as plt
import sympy as sym
sym.init_printing()
#Esquemas de diferencias finitas para la primera derivada
def df1df(x0, h):
# Esquema de diferencias finitas para la primera derivada hacia adelante (forward)
return (f(x0 + h) - f(x0)) / h
def df1db(x0, h):
# Esqu... | _____no_output_____ | MIT | Cap05_IntegracionNumerica.ipynb | Youngermaster/Numerical-Analysis |
[Volver a la Tabla de Contenido](TOC) Integración Numérica Introducción La [integración numérica](https://en.wikipedia.org/wiki/Numerical_integration) aborda una amplia gama de algoritmos para determinar el valor numérico (aproximado) de una integral definida. En este curso nos centraremos principalmente en los métod... | import numpy as np
import matplotlib.pyplot as plt
def trapezoidal(x):
n = len(x)
h = (x[-1] - x[0]) / n
suma = 0
for i in range(1, n-1):
suma += funcion(x[i])
return h * (funcion(x[0]) + 2 * suma + funcion(x[-1])) / 2
def funcion(x):
return 4 / (1 + x**2)
a = 0
b = 1
n = 1000
... | _____no_output_____ | MIT | Cap05_IntegracionNumerica.ipynb | Youngermaster/Numerical-Analysis |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.