markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
Flag photos for deletion by clicking 'Delete'. Then click 'Next Batch' to delete flagged photos and keep the rest in that row. ImageCleaner will show you a new row of images until there are no more to show. In this case, the widget will show you images until there are none left from top_losses.ImageCleaner(ds, idxs).<b...
ds, idxs = DatasetFormatter().from_similars(learn_cln) ImageCleaner(ds, idxs, path, duplicates=True)
zh-nbs/Lesson2_download.ipynb
fastai/course-v3
apache-2.0
Remember to recreate your ImageDataBunch from your cleaned.csv to include the changes you made in your data!<br> 记住从你的cleaned.csv中重新创建ImageDatabunch,以便包含你对数据的所有变更! Putting your model in production 部署模型 First thing first, let's export the content of our Learner object for production:<br> 首先,导出我们训练好的Learner对象内容,为部署做好准备:
learn.export()
zh-nbs/Lesson2_download.ipynb
fastai/course-v3
apache-2.0
This will create a file named 'export.pkl' in the directory where we were working that contains everything we need to deploy our model (the model, the weights but also some metadata like the classes or the transforms/normalization used).<br> 这个命令会在我们处理模型的目录里创建名为export.pk1的文件,该文件中包含了用于部署模型的所有信息(模型、权重,以及一些元数据,如一些类或用到的变换/...
defaults.device = torch.device('cpu') img = open_image(path/'black'/'00000021.jpg') img
zh-nbs/Lesson2_download.ipynb
fastai/course-v3
apache-2.0
We create our Learner in production enviromnent like this, jsut make sure that path contains the file 'export.pkl' from before.<br> 我们在这样的生产环境下创建学习器,只需确保path参数包含了前面生成好的“export.pk1”文件。
learn = load_learner(path) pred_class,pred_idx,outputs = learn.predict(img) pred_class
zh-nbs/Lesson2_download.ipynb
fastai/course-v3
apache-2.0
So you might create a route something like this (thanks to Simon Willison for the structure of this code):<br> 你可能需要像下面的代码这样,创建一个路径, (谢谢Simon Willison提供了这些代码的架构): python @app.route("/classify-url", methods=["GET"]) async def classify_url(request): bytes = await get_bytes(request.query_params["url"]) img = open_...
learn = cnn_learner(data, models.resnet34, metrics=error_rate) learn.fit_one_cycle(1, max_lr=0.5)
zh-nbs/Lesson2_download.ipynb
fastai/course-v3
apache-2.0
Learning rate (LR) too low 学习率(LR)太低
learn = cnn_learner(data, models.resnet34, metrics=error_rate)
zh-nbs/Lesson2_download.ipynb
fastai/course-v3
apache-2.0
Previously we had this result:<br> 前面的代码运行后,我们得到如下结果: Total time: 00:57 epoch train_loss valid_loss error_rate 1 1.030236 0.179226 0.028369 (00:14) 2 0.561508 0.055464 0.014184 (00:13) 3 0.396103 0.053801 0.014184 (00:13) 4 0.316883 0.050197 0.021277 (00:15)
learn.fit_one_cycle(5, max_lr=1e-5) learn.recorder.plot_losses()
zh-nbs/Lesson2_download.ipynb
fastai/course-v3
apache-2.0
As well as taking a really long time, it's getting too many looks at each image, so may overfit.<br> 不仅运行耗时过长,而且模型对每一个图片都太过注重细节,因此可能过拟合。 Too few epochs epochs过少
learn = cnn_learner(data, models.resnet34, metrics=error_rate, pretrained=False) learn.fit_one_cycle(1)
zh-nbs/Lesson2_download.ipynb
fastai/course-v3
apache-2.0
Too many epochs epochs过多
np.random.seed(42) data = ImageDataBunch.from_folder(path, train=".", valid_pct=0.9, bs=32, ds_tfms=get_transforms(do_flip=False, max_rotate=0, max_zoom=1, max_lighting=0, max_warp=0 ),size=224, num_workers=4).normalize(imagenet_stats) learn = cnn_learner(data, models.resnet50, m...
zh-nbs/Lesson2_download.ipynb
fastai/course-v3
apache-2.0
Estimation
O.par['n_cond']=3; # For estimation, the numbner of conditionals need never be highed than the number of actual conditional hard and/or soft data. O.par['n_real']=1; O.par['do_estimation']=1 O.par['do_entropy']=1 # when using mps_genesim, we need to compute a conditional O.par['n_max_cpdf_count']=1000000; # We need to ...
scikit-mps/examples/ex_mpslib_estimation.ipynb
ergosimulation/mpslib
lgpl-3.0
Simulation
O.par['n_real']=30; O.par['n_cond']=25; # For estimation, one typically needs n_cond higher to obtain realizations with resonable pattern reproduction. O.par['do_estimation']=0 O.par['max_cpdf_count']=1; # Direct sampling mode O.par['n_max_ite']=1000 # This is typically not set to a very high number to avoid scanning ...
scikit-mps/examples/ex_mpslib_estimation.ipynb
ergosimulation/mpslib
lgpl-3.0
1. What is the output of the commands above? Now each time we call a function that’s in a library, we use the syntax: python LibraryName.FunctionName Adding the library name with a . before the function name tells Python where to find the function. In the example above, we have imported Pandas as pd. This means we don’...
# url where data is stored url = "https://raw.githubusercontent.com/Reproducible-Science-Curriculum/data-exploration-RR-Jupyter/master/gapminderDataFiveYear_superDirty.txt" # assigns the identifier 'gapminder' to the entire dataset gapminder = pd.read_table(url, sep = "\t")
lesson14/Lesson14_team_improved.ipynb
nerdcommander/scientific_computing_2017
mit
2. In the command above, why did we use pd.read_table, not just read_table or pandas.read_table? Now we have a DataFrame called gapminder with all of our data in it! One of the first things we do after importing data is to just have a look and make sure it looks like what we think it should. In this case, this is yo...
## DataFrame name here
lesson14/Lesson14_team_improved.ipynb
nerdcommander/scientific_computing_2017
mit
There are usually too many rows to print to the screen and you don't really want to find out by printing them all to the screen and regretting it. By default, when you type the name of the DataFrame and run a cell, pandas knows not to print the whole thing if there are a lot of rows. Instead, you will see the first a...
## head and tail methods
lesson14/Lesson14_team_improved.ipynb
nerdcommander/scientific_computing_2017
mit
3. Make a few observations about what you see in the data so far (you don't have to go too deep since we are going to use pandas to look next) Assess structure and cleanliness How many rows and columns are in the data? We often want to know how many rows and columns are in the data -- we want to know what is called t...
## shape
lesson14/Lesson14_team_improved.ipynb
nerdcommander/scientific_computing_2017
mit
4. How many rows and columns are there? The info() method gives a few useful pieces of information quickly, including the shape of the DataFrame, the variable type of each column, and the amount of memory stored. run the code in the cell below
# get info gapminder.info()
lesson14/Lesson14_team_improved.ipynb
nerdcommander/scientific_computing_2017
mit
There are several problems with this data set as it is. BTW, this is super common and data nerd slang for fundamentally useful data with issues is "dirty data" and the process for un-dirtying it is called "data cleaning". (believe it or not, tidy data is yet again a different thing, we'll get to that later) The first s...
## describe
lesson14/Lesson14_team_improved.ipynb
nerdcommander/scientific_computing_2017
mit
Uh-oh what happened to the percentiles? Also notice that you get an error, but it gives you some output. The DataFrame method describe() just blindly looks at all numeric variables. First, we wouldn't actually want to take the mean year. Additionally, we obtain 'NaN' (not a number) values for our quartiles. This sugges...
# use describe but only on columns with continuous values gapminder[['pop', 'life Exp', 'gdpPercap']].describe()
lesson14/Lesson14_team_improved.ipynb
nerdcommander/scientific_computing_2017
mit
8. We haven't really nailed this problem down yet. Reflect (or look) back on your answer to Question#7 and think about what might be happening (don't worry too much about the mathematical specifics). Let's get after it. The command value_counts() gives you a quick idea of what kinds of names are in your categorical dat...
## use value_counts to find out how many times each unique region occus
lesson14/Lesson14_team_improved.ipynb
nerdcommander/scientific_computing_2017
mit
Uh-oh! The table reveals several problems. 9. Describe and Explain the (several) problems that you see. Data cleaning Handling Missing Data Missing data is an important issue to handle. As we've seen, ignoring it doesn't make it go away, in our example, it has been giving us problems in our describe() results -- remem...
# isnull results in T/F for each cell, # sum adds them up by column since F=0 and T=1 so #=#NAs gapminder.isnull().sum()
lesson14/Lesson14_team_improved.ipynb
nerdcommander/scientific_computing_2017
mit
Yikes! There are NA values in each column except region. Removing NAs from a DataFrame is incredibly easy to do because pandas allows you to either remove all instances will NA/null data or replace them with a particular value. (sometimes too easy, so make sure you are careful!) The method df = df.dropna() (here df is ...
## before you rip into removing, it's a good idea to know how many rows you have ## you know a few ways to get this info, write some code here to get # of rows ## now use dropna() ## now get the number of rows again ## use isnull() again to confirm
lesson14/Lesson14_team_improved.ipynb
nerdcommander/scientific_computing_2017
mit
11. How many rows were removed? Make sure the code immediately above justifies this. 12. Which regions lost rows? Run code to see if there are still NAs and also to identify regions with too many observations. (hint: it won't be perfect yet)
## your code
lesson14/Lesson14_team_improved.ipynb
nerdcommander/scientific_computing_2017
mit
Are we done yet? Oh, no, we certainly are not... One more nice trick. If you want to examine a subset (more later) of the rows, for example to exmaine the region with too many observations, you can use code like this: python gapminder[gapminder.column == 'value_in_column'] where column is the name of a column and 'valu...
## code to examine rows from regions with too many obs
lesson14/Lesson14_team_improved.ipynb
nerdcommander/scientific_computing_2017
mit
Handling strange variable types Remember above where we had some strange/annoying variable types? Now we can fix them. The methods below would have failed if there were NAs in the data since they look for the type of the data and try to change it. Inconsistencies in data types and NAs cause problems for a lot of method...
##type casts the year column data from float to int gapminder['year'] = gapminder['year'].astype(int)
lesson14/Lesson14_team_improved.ipynb
nerdcommander/scientific_computing_2017
mit
Now you use astype() to type cast the other problematic column and use info() to make sure these two operations worked.
## fix other column and make sure all is ok
lesson14/Lesson14_team_improved.ipynb
nerdcommander/scientific_computing_2017
mit
Progress! Your data types should make more sense now and since we removed the NA values above, the total number of rows or entries is the same as the non-null rows. Nice! Handling (Unwanted) Repetitive Data Sometimes observations can end up in the data set more than once creating a duplicate row. Luckily, pandas has me...
## get T/F output for each row if it is a duplicate (only look at top 5) gapminder.duplicated().head()
lesson14/Lesson14_team_improved.ipynb
nerdcommander/scientific_computing_2017
mit
Wow, there is a repeat in the first 5 rows! Write code below that allows you to confirm this by examining the DataFrame.
## confirm duplicate in top 5 rows of df ## you can use the .sum() to count the number of duplicated rows in the DataFrame
lesson14/Lesson14_team_improved.ipynb
nerdcommander/scientific_computing_2017
mit
In cases where you don’t want exactly repeated rows (we don’t -- we only want each country to be represented once for every relevant year), you can easily drop such duplicate rows with the method df.drop_duplicates(). Note: drop_duplicates() is another method that does not work in place, and if you want the DataFrame ...
## remove duplicates and confirm
lesson14/Lesson14_team_improved.ipynb
nerdcommander/scientific_computing_2017
mit
More Progress! Reindexing with reset_index() Now we have 1704 rows, but our index is off. Look at the index values in gapminder just above. One is missing! We can reset our indices easily with the method reset_index(drop=True). Remember, Python is 0-indexed so our indices will be valued 0-1703. The drop=True parameter...
## reset index and check top 5
lesson14/Lesson14_team_improved.ipynb
nerdcommander/scientific_computing_2017
mit
Handling Inconsistent Data The region column still has issues that will affect our analysis. We used the value_counts() method above to examine some of these issues... write code to look at the number of observations for each unique region
## get value counts for the region column
lesson14/Lesson14_team_improved.ipynb
nerdcommander/scientific_computing_2017
mit
14. Describe and Explain... 14a. what is better now that we have done some data cleaning. 14b. what is still in need of being fixed. String manipulations Very common problems with string variables are: + lingering white space + upper case vs. lower case These issues are problematic since upper and lower case characters...
## write code to strip white space on both left and right of region names ## convert region names to lowercase, and print out df to confirm
lesson14/Lesson14_team_improved.ipynb
nerdcommander/scientific_computing_2017
mit
As a side note, one of the coolest thing about pandas is an idea called chaining. If you prefer, the three commands can be written in one single line! python df['column_name'] = df['column_name'].str.lstrip().str.rstrip().str.lower() You may be wondering about the order of operations and it starts closest to the data ...
# gives a problem -- 24 values of the congo! temp = gapminder['region'].replace(".*congo.*", "africa_dem rep congo", regex=True) temp.value_counts()
lesson14/Lesson14_team_improved.ipynb
nerdcommander/scientific_computing_2017
mit
16. What happened?
## this should help # shows all the rows that have 'congo' in the name gapminder[gapminder['region'].str.contains('congo')]
lesson14/Lesson14_team_improved.ipynb
nerdcommander/scientific_computing_2017
mit
We can revert back to working on the the non-temporary DataFrame and correctly modify our regex to isolate only the Democratic Republic of Congo instances (as opposed to including the Republic of Congo as well). Using regex to fix the Dem. Rep. Congo... As noted above, regular expressions (regex) provide a powerful to...
# fix the two different versions of the incorrect name to the same correct version gapminder['region'].replace(".*congo, dem.*", "africa_dem rep congo", regex=True, inplace=True) gapminder['region'].replace(".*_democratic republic of the congo", "africa_dem rep congo", regex=True, inplace=True) ## you write code to ch...
lesson14/Lesson14_team_improved.ipynb
nerdcommander/scientific_computing_2017
mit
Exercise (regex): Now that we've taken a close look at how to properly design and use regex to clean string entries in our data, let's try to normalize the naming of a few other countries. Using the pandas code we constructed above as a template, write similar code to what we used above (using df.replace()) to fix th...
## code to fix other incorrect names
lesson14/Lesson14_team_improved.ipynb
nerdcommander/scientific_computing_2017
mit
Are we there yet??!??! 17. Looks like we successfully cleaned our data! Justify that we are done. Tidy data Having what is called a Tidy data set can make cleaning and analyzing your data much easier. Two of the important aspects of Tidy data are: * every variable has its own column * every observation has its own row ...
# split region into country and continent to tidy data gapminder['country']=gapminder['region'].str.split('_', 1).str[1] gapminder['continent']=gapminder['region'].str.split('_', 1).str[0] gapminder.head()
lesson14/Lesson14_team_improved.ipynb
nerdcommander/scientific_computing_2017
mit
19. Describe what happens for each of the lines of code that contains split(). Be sure to explain why the 2 columns end up with different values.
## mess around with it if you need to, but make a 'temp' version of gapminder to play with!
lesson14/Lesson14_team_improved.ipynb
nerdcommander/scientific_computing_2017
mit
Removing and renaming columns We have now added the columns country and continent, but we still have the old region column as well. In order to remove that column we use the drop() command. The first argument of the drop() command is the name of the element to be dropped. The second argument is the axis number: 0 for r...
## check new columns # drop old region column gapminder = gapminder.drop('region', 1) gapminder.head()
lesson14/Lesson14_team_improved.ipynb
nerdcommander/scientific_computing_2017
mit
Finally, it is a good idea to look critically at your column names themselves. It is a good idea to be as consistent as possible when naming columns. We often use all lowercase for all column names to avoid accidentally making names that can be confusing -- gdppercap and gdpPercap and GDPpercap are all the same nut gdp...
# turns all column names to lowercase # yes you need the .columns on the left side too gapminder.columns = gapminder.columns.str.lower() gapminder.head()
lesson14/Lesson14_team_improved.ipynb
nerdcommander/scientific_computing_2017
mit
We also want to remove the space from the life exp column name. We can do that with Pandas rename method. It takes a dictionary as its argument, with the old column names as keys and new column names as values. If you're unfamiliar with dictionaries, they are a very useful data structure in Python. You can read more a...
# rename column gapminder = gapminder.rename(columns={'life exp' : 'lifeexp'}) gapminder.head()
lesson14/Lesson14_team_improved.ipynb
nerdcommander/scientific_computing_2017
mit
Tidy data wrap-up 21. explain why the data set at this point is Tidy or at least much tidier than it was before. Export clean and tidy data file Now that we have a clean and tidy data set in a DataFrame, we want to export it and give it a new name so that we can refer to it and use it python df.to_csv('file name for ex...
# exports gapminder_CandT.csv gapminder.to_csv('gapminder_CandT.csv', index=False)
lesson14/Lesson14_team_improved.ipynb
nerdcommander/scientific_computing_2017
mit
Subsetting and sorting There are many ways in which you can manipulate a Pandas DataFrame - here we will discuss only two: subsetting and sorting. Sometimes you only want part of a larger data set, then you would subset your DataFrame. Othertimes you want to sort the data into a particular order (year more recent to...
# first 15 rows gapminder[0:15] # could also be gapminder[:15]
lesson14/Lesson14_team_improved.ipynb
nerdcommander/scientific_computing_2017
mit
write code to take a different slice
## your slice
lesson14/Lesson14_team_improved.ipynb
nerdcommander/scientific_computing_2017
mit
21. Predict what the slice below will do. python gapminder[-10:]
## run the code here to test prediction.
lesson14/Lesson14_team_improved.ipynb
nerdcommander/scientific_computing_2017
mit
22a. What does the negative number (in the cell above) mean? 22b. What happens when you leave the space before or after the colon empty? write code to take another different slice
## your 'nother slice
lesson14/Lesson14_team_improved.ipynb
nerdcommander/scientific_computing_2017
mit
More Subsetting Subsetting can also be done by selecting for a particular value in a column. For instance to select all of the rows that have 'africa' in the column 'continent'. python gapminder_africa = gapminder[gapminder['continent']=='africa'] Note the double equal sign: Remember that single equal signs are used ...
# makes a new DataFrame with just data from Africa gapminder_africa = gapminder[gapminder['continent']=='africa'] ## write code to quickly check that this worked
lesson14/Lesson14_team_improved.ipynb
nerdcommander/scientific_computing_2017
mit
Even more... There are several other fancy ways to subset rows and columns from DataFrames, the .loc and .iloc methods are particularly useful. If you're interested, look them up on the cheatsheet or in the docs. Sorting Sorting may help to further organize and inspect your data. The method sort_values() takes a numbe...
# sort by year, from most recent to oldest gapminder.sort_values(by='year', ascending = False)
lesson14/Lesson14_team_improved.ipynb
nerdcommander/scientific_computing_2017
mit
Note: the sort() method does not sort in place. write code to prove it.
## your code, sort() not in place
lesson14/Lesson14_team_improved.ipynb
nerdcommander/scientific_computing_2017
mit
23. Make a new variable with a sorted version of the DataFrame organized by country, from ‘Afganistan’ to ‘Zimbabwe’. Also include code to show that it is sorted correctly.
## alphabetical by country
lesson14/Lesson14_team_improved.ipynb
nerdcommander/scientific_computing_2017
mit
Summarize and plot Summaries and Statistics are very useful for intial examination of data as well as in depth analysis. Here we will only scratch the surface. Plots/graphs/charts are also great visual ways to examine data and illustrate patterns. Exploring your data is often iterative - summarize, plot, summarize, pl...
# review info() gapminder.info()
lesson14/Lesson14_team_improved.ipynb
nerdcommander/scientific_computing_2017
mit
We also saw above that the describe() method will take the numeric columns and give a summary of their values. We have to remember that we changed the changed column names, and this time it shouldn't have NAs.
# review describe gapminder[['pop', 'lifeexp', 'gdppercap']].describe()
lesson14/Lesson14_team_improved.ipynb
nerdcommander/scientific_computing_2017
mit
More summaries What if we just want a single value, like the mean of the population column? We can call mean on a single column this way:
# population mean gapminder['pop'].mean()
lesson14/Lesson14_team_improved.ipynb
nerdcommander/scientific_computing_2017
mit
What if we want to know the mean population by continent? Then we need to use the Pandas groupby() method and tell it which column we want to group by.
# population mean by continent gapminder[['continent', 'pop']].groupby(by='continent').mean()
lesson14/Lesson14_team_improved.ipynb
nerdcommander/scientific_computing_2017
mit
What if we want to know the median population by continent? The method that gives you the median is called median(). write code below to get the median population by continent
## population median by continent
lesson14/Lesson14_team_improved.ipynb
nerdcommander/scientific_computing_2017
mit
Or the number of entries (rows) per continent?
# count number of rows gapminder[['continent', 'country']].groupby(by='continent').count()
lesson14/Lesson14_team_improved.ipynb
nerdcommander/scientific_computing_2017
mit
Sometimes we don't want a whole DataFrame. Here is another way to do this that produces a series as opposed to a DataFrame that tells us number of entries (rows).
# get size by continent gapminder[['continent', 'country']].groupby(by='continent').size()
lesson14/Lesson14_team_improved.ipynb
nerdcommander/scientific_computing_2017
mit
We can also look at the mean GDP per capita of each country: write code below to get the mean GDP per capita of each country
## mean GDP per capita by country
lesson14/Lesson14_team_improved.ipynb
nerdcommander/scientific_computing_2017
mit
What if we wanted a new DataFrame that just contained these summaries? This could be a table in a report, for example.
# pretty slick, right?! continent_mean_pop = gapminder[['continent', 'pop']].groupby(by='continent').mean() continent_mean_pop = continent_mean_pop.rename(columns = {'pop':'meanpop'}) continent_row_ct = gapminder[['continent', 'country']].groupby(by='continent').count() continent_row_ct = continent_row_ct.rename(column...
lesson14/Lesson14_team_improved.ipynb
nerdcommander/scientific_computing_2017
mit
Visualization with matplotlib Recall that matplotlib is Python's main visualization library. It provides a range of tools for constructing plots, and numerous high-level and add on plotting libraries are built with matplotlib in mind. When we were in the early stages of setting up our analysis, we loaded these libr...
# import again just in case import matplotlib.pyplot as plt ## generate some toy data and plot it # required to generate toy data import numpy as np # magic to plot straight into notebook, probably no longer needed. # %matplotlib inline # evenly sampled time at 200ms intervals t = np.arange(0., 5., 0.2) # red das...
lesson14/Lesson14_team_improved.ipynb
nerdcommander/scientific_computing_2017
mit
Single variable plots Histograms - provide a quick way of visualizing the distribution of numerical data, or the frequencies of observations for categorical variables. Run the code below to generate a smaple histogram.
# example histogram # generate some random numbers from a normal distribution data = 100 + np.random.randn(500) # make a histogram with 20 bins plt.hist(data, 20) plt.xlabel('x axis') plt.ylabel('y axis') plt.show()
lesson14/Lesson14_team_improved.ipynb
nerdcommander/scientific_computing_2017
mit
write code below to make a histogram of the distribution of life expectancies of the countries in the gapminder DataFrame.
## histogram of lifeexp
lesson14/Lesson14_team_improved.ipynb
nerdcommander/scientific_computing_2017
mit
Target configuration The target configuration is used to describe and configure your test environment. You can find more details in examples/utils/testenv_example.ipynb.
# Root path of the gem5 workspace base = "/home/vagrant/gem5" conf = { # Only 'linux' is supported by gem5 for now, 'android' is a WIP "platform" : 'linux', # Preload settings for a specific target "board" : 'gem5', # Devlib modules to load - "gem5stats" is required to use the po...
ipynb/deprecated/examples/energy_meter/EnergyMeter_Gem5.ipynb
ARM-software/lisa
apache-2.0
Workload execution For this example, we will investigate the energy consumption of the target while running a random workload. Our observations will be made using the RT-App decreasing ramp workload defined below. With such a workload, the system load goes from high to low over time. We expect to see a similar pattern ...
# Create and RTApp RAMP tasks rtapp = RTA(target, 'ramp', calibration=te.calibration()) rtapp.conf(kind='profile', params={ 'ramp1' : Ramp( start_pct = 95, end_pct = 5, delta_pct = 10, time_s = 0.1).get...
ipynb/deprecated/examples/energy_meter/EnergyMeter_Gem5.ipynb
ARM-software/lisa
apache-2.0
Energy estimation The gem5 energy meters feature two methods: reset and report. * The reset method will start sampling the channels defined in the target configuration. * The report method will stop the sampling and produce a CSV file containing power samples together with a JSON file summarizing the total energy consu...
# Start emeters & run workload te.emeter.reset() rtapp.run(out_dir=te.res_dir) nrg_rep = te.emeter.report(te.res_dir)
ipynb/deprecated/examples/energy_meter/EnergyMeter_Gem5.ipynb
ARM-software/lisa
apache-2.0
Data analysis
logging.info("Measured channels energy:") print json.dumps(nrg_rep.channels, indent=4) logging.info("DataFrame of collected samples (only first 5)") nrg_rep.data_frame.head() # Obtain system level energy by ... df = nrg_rep.data_frame # ... summing the dynamic power of all cores to obtain total dynamic power, ... df[...
ipynb/deprecated/examples/energy_meter/EnergyMeter_Gem5.ipynb
ARM-software/lisa
apache-2.0
We can see on the above plot that the system level power consumption decreases over time (in average). This is coherent with the expected behaviour given the decreasing ramp workload under consideration.
logging.info("Power distribution") axes = df[('total')].plot(kind='hist', bins=32, figsize=(16,8)); axes.set_title('Power Histogram'); axes.set_xlabel('Output power [W] buckets'); axes.set_ylabel('Samples per bucket'); logging.info("Plot of collected power samples") nrg_rep.data_frame.describ...
ipynb/deprecated/examples/energy_meter/EnergyMeter_Gem5.ipynb
ARM-software/lisa
apache-2.0
Here we upload the data obtained from Brownian Dynamics simulations of isotropic diffusion on a 2D potential.
h5file = "data/cossio_kl1.3_Dx1_Dq1.h5" f = h5py.File(h5file, 'r') data = np.array(f['data']) f.close()
examples/brownian_dynamics_2D/2D_smFS_MSM.ipynb
daviddesancho/MasterMSM
gpl-2.0
Trajectory analysis
fig, ax = plt.subplots(2,1,figsize=(12,3), sharex=True,sharey=False) ax[0].plot(data[:,0],data[:,1],'.', markersize=1) ax[1].plot(data[:,0],data[:,2],'g.', markersize=1) ax[0].set_ylim(-10,10) ax[1].set_xlim(0,25000) ax[0].set_ylabel('x') ax[1].set_ylabel('q') ax[1].set_xlabel('Time') plt.tight_layout(h_pad=0) fig, ax...
examples/brownian_dynamics_2D/2D_smFS_MSM.ipynb
daviddesancho/MasterMSM
gpl-2.0
Representation of the bistable 2D free energy surface as a function of the measured q and molecular x extensions:
H, x_edges, y_edges = np.histogram2d(data[:,1],data[:,2], \ bins=[np.linspace(-7,7,20), np.linspace(-7,7,20)]) fig, ax = plt.subplots(figsize=(6,5)) pmf = -np.log(H.transpose()) pmf -= np.min(pmf) cs = ax.contourf(pmf, extent=[x_edges.min(), x_edges.max(), \ y_edges.min(), y_edges.max(...
examples/brownian_dynamics_2D/2D_smFS_MSM.ipynb
daviddesancho/MasterMSM
gpl-2.0
Assignment Now we discretize the trajectory using the states obtained from partitioning the 2D free energy surface of the diffusion of the molecule. We first need to import the function that makes the grid.
from scipy.stats import binned_statistic_2d statistic, x_edge, y_edge, binnumber = \ binned_statistic_2d(data[:,1],data[:,2],None,'count', \ bins=[np.linspace(-7,7,20), np.linspace(-7,7,20)]) fig, ax = plt.subplots(figsize=(6,5)) grid = ax.imshow(-np.log(statistic.transpose()),origin="low...
examples/brownian_dynamics_2D/2D_smFS_MSM.ipynb
daviddesancho/MasterMSM
gpl-2.0
Master Equation Model
from mastermsm.trajectory import traj from mastermsm.msm import msm distraj = traj.TimeSeries(distraj=list(binnumber), dt=1) distraj.find_keys() distraj.keys.sort() msm_2D = msm.SuperMSM([distraj])
examples/brownian_dynamics_2D/2D_smFS_MSM.ipynb
daviddesancho/MasterMSM
gpl-2.0
Convergence Test
for i in [1, 2, 5, 10, 20, 50, 100]: msm_2D.do_msm(i) msm_2D.msms[i].do_trans(evecs=True) msm_2D.msms[i].boots() fig, ax = plt.subplots() for i in range(5): tau_vs_lagt = np.array([[x,msm_2D.msms[x].tauT[i],msm_2D.msms[x].tau_std[i]] \ for x in sorted(msm_2D.msms.keys())]) ax.errorba...
examples/brownian_dynamics_2D/2D_smFS_MSM.ipynb
daviddesancho/MasterMSM
gpl-2.0
There is no dependency of the relaxation times $\tau$ on the lag time $\Delta$t. Estimation
lt=2 plt.figure() plt.imshow(msm_2D.msms[lt].trans, interpolation='none', \ cmap='viridis_r',origin="lower") plt.ylabel('$\it{i}$') plt.xlabel('$\it{j}$') plt.colorbar() plt.figure() plt.imshow(np.log(msm_2D.msms[lt].trans), interpolation='none', \ cmap='viridis_r',origin="lower") plt.ylabel('$\it{i}$') plt.xla...
examples/brownian_dynamics_2D/2D_smFS_MSM.ipynb
daviddesancho/MasterMSM
gpl-2.0
The first mode captured by $\lambda_1$ is significantly slower than the others. That mode, which is described by the right eigenvector $\psi^R_1$ as the transition of the protein between the folded and unfolded states.
fig, ax = plt.subplots(figsize=(10,4)) ax.plot(msm_2D.msms[2].rvecsT[:,1]) ax.fill_between(range(len(msm_2D.msms[lt].rvecsT[:,1])), 0, \ msm_2D.msms[lt].rvecsT[:,1], \ where=msm_2D.msms[lt].rvecsT[:,1]>0,\ facecolor='c', interpolate=True,alpha=.4) ax.fill_between(range(le...
examples/brownian_dynamics_2D/2D_smFS_MSM.ipynb
daviddesancho/MasterMSM
gpl-2.0
The projection of $\psi^R_1$ on the 2D grid shows the transitions between the two conformational states (red and blue).
fig,ax = plt.subplots(1,2,figsize=(10,5),sharey=True,sharex=True) rv_mat = np.zeros((20,20), float) for i in [x for x in zip(msm_2D.msms[lt].keep_keys, \ msm_2D.msms[lt].rvecsT[:,1])]: unr_ind=np.unravel_index(i[0],(21,21)) rv_mat[unr_ind[0]-1,unr_ind[1]-1] = -i[1] ax[0].imshow(rv_m...
examples/brownian_dynamics_2D/2D_smFS_MSM.ipynb
daviddesancho/MasterMSM
gpl-2.0
where DEEPNUC_PATH specifies the path to the DeepNuc directory. All examples in this manual assume usage of this directory structure. Although this manual was written using Jupyter notebook, I would not recommend running training within a notebook environment. Example 1: Training and testing a model from a fasta file F...
import tensorflow as tf import sys import os.path sys.path.append('../../') import numpy as np from deepnuc.nucdata import * from deepnuc.nucbinaryclassifier import NucBinaryClassifier from deepnuc.databatcher import DataBatcher from deepnuc.modelparams import * from deepnuc.logger import Logger import deepnuc.nuccon...
docs/manual/DeepNuc Instructions.ipynb
LarsDu/DeepNuc
gpl-3.0
Then specify model parameters. * seq_len: Sequence length. * num_epochs: Number of epochs. An epoch is a single pass through every item in a training set. * learning_rate: Learning rate for gradient descent * batch_size: Mini-batch size. * keep_prob: The keep probability for Dropout. A keep prob of .6 will randomly dr...
params = ModelParams( seq_len=600, num_epochs=35, learning_rate=1e-4, batch_size=24, keep_prob=0.5, beta1=0.9, concat_revcom_input=False, ...
docs/manual/DeepNuc Instructions.ipynb
LarsDu/DeepNuc
gpl-3.0
Now create a NucData type object from your fasta file. NucData type objects are described in the nucdata.py module. There are many different types of NucData objects for different filetypes. We will use NucDataBedMem which reads all nucleotide sequences into the computer's memory. Note that since most bed files will ha...
bed_file = "kruesi_bed_0_4.bed" genome_file="WS230_genome.fa" chr_sizes_file="WS230_genome.chr.sizes" seq_len=600 skip_first=False nuc_data = NucDataBedMem( bed_file, genome_file, chr_sizes_file, seq_len=600, skip_f...
docs/manual/DeepNuc Instructions.ipynb
LarsDu/DeepNuc
gpl-3.0
NucData objects encapsulate data from different file formats, but aren't used for training and testing directly. DataBatcher objects are useful for slicing NucData objects into training and testing sets by index. DataBatcher objects also shuffle records by index every epoch and pull randomized mini-batches for training...
#First scramble the indices you want to use seed = 12415 perm_indices = np.random.RandomState(seed).\ permutation(range(nuc_data.num_records)) #Slice out 20% of indices for testing and 80% for training test_frac = .2 test_size = int(nuc_data.num_records*test_frac) train_size = nuc_data.num...
docs/manual/DeepNuc Instructions.ipynb
LarsDu/DeepNuc
gpl-3.0
With the training and testing batchers, we can now run training from within a Tensorflow session. Note: Training parameters can be passed directly to NucBinaryClassifier, but in many situtations, using the ModelParams object can be useful for writing methods which train off different dataset using the same training par...
save_dir="test_train1" os.makedirs(save_dir) with tf.Session() as sess: nc_test = NucBinaryClassifier(sess, train_batcher, test_batcher, params.num_epochs, params.learning_rate, ...
docs/manual/DeepNuc Instructions.ipynb
LarsDu/DeepNuc
gpl-3.0
nc_test.build_model() will also load trained models. For example. After running training, the following line can be used to evaluate metrics from a differerent test or evaluation batcher.
nc_test.build_model() nc_test.eval_model_metrics(different_batcher)
docs/manual/DeepNuc Instructions.ipynb
LarsDu/DeepNuc
gpl-3.0
Generating a dinucleotide shuffled file manually Making dinucleotide shuffled files can also be done manually using the BedReader class Example 2: Training and testing a model from a fasta file Training and testing a from a fasta file is identical to training and testing from a bed file. The only difference is changing...
fasta_neg = "kruesi_tss_-300_300_dinuc_shuffle.fa" fasta_pos = "kruesi_tss_-300_300.fa" nuc_data = NucDataFastaMem([fasta_neg,fasta_pos],seq_len=600)
docs/manual/DeepNuc Instructions.ipynb
LarsDu/DeepNuc
gpl-3.0
Example 3: Performing k-folds cross-validation using a bed file Getting a model trained and evaluating a test set is nice, but in a real world situation, we want to have a way to know how well our model performed. This is where k-folds cross-validation is useful. Cross validation can be done in the following manner.
cv_save_dir = "cv_test1" cv_test = CrossValidator(params, nuc_data, cv_save_dir, seed=124155, k_folds=3, test_frac=0.15) cv.run() #Calculate average of k-fold metrics and display in terminal cv.cal...
docs/manual/DeepNuc Instructions.ipynb
LarsDu/DeepNuc
gpl-3.0
Note that cv.run() does not need to be called from within a tf.Session() Example 4: Performing a grid search with cross-validation using a bed file On top of k-folds cross-validation, we want to have cross-validation metrics for different hyperparameter combinations. This is where a grid search is useful. Performing a ...
gsave_dir="gridtest1" gparams = GridParams( seq_len= seq_len, num_epochs=[55], learning_rate=[1e-4], batch_size=[24], keep_prob=[0.5], beta1=[0.9], concat_revcom_inpu...
docs/manual/DeepNuc Instructions.ipynb
LarsDu/DeepNuc
gpl-3.0
After a grid search is performed, the model can be loaded and final training performed on the best classifier:
with tf.Session() as sess: best_classifier,best_model_params = gsearch.best_binary_classifier(sess,"auroc") print "\n\n\nBest model params for {}".format(tss_bed) best_model_params.print_params()
docs/manual/DeepNuc Instructions.ipynb
LarsDu/DeepNuc
gpl-3.0
The best_classifier can be treated as any other NucBinaryClassifier object.
best_classifier.eval_model_metrics(different_batcher)
docs/manual/DeepNuc Instructions.ipynb
LarsDu/DeepNuc
gpl-3.0
Note that if running back to back grid search or training runs from the same script, you should reset the default graph with the following command.
tf.reset_default_graph()
docs/manual/DeepNuc Instructions.ipynb
LarsDu/DeepNuc
gpl-3.0
Example 5: Using a fasta or bed file as a negative class To specify a specific bed or fasta file to use as a negative class, pass a BedReader or FastaReader to the neg_data_reader parameter of NucDataBedMem when making a NucData object.
seq_len=600 specific_neg_file="my_specific_file.fa" my_neg_reader = FastaReader(specific_neg_file,seq_len) bed_file = "kruesi_bed_0_4.bed" genome_file="WS230_genome.fa" chr_sizes_file="WS230_genome.chr.sizes" skip_first=False nuc_data = NucDataBedMem( bed_file, genome_file, ...
docs/manual/DeepNuc Instructions.ipynb
LarsDu/DeepNuc
gpl-3.0
Since training should be performed with balanced data, you may want to set a limit on the number of negative items you pull from a specified file. This is available as an argument to the FastaReader object.
seq_len=600 specific_neg_file="my_specific_file.fa" my_neg_reader = FastaReader(specific_neg_file, seq_len, pull_limit=4121)
docs/manual/DeepNuc Instructions.ipynb
LarsDu/DeepNuc
gpl-3.0
Tarea 1 (a). Irradiancia máxima Como estamos considerando el haz láser de un puntero que emite en el visible, como tiempo de exposición emplearemos el tiempo que se tarda en cerrar el párpado. Así con este tiempo de exposición estimar de la gráfica la irradiancia máxima que puede alcanzar el ojo. Escribir el tiempo de...
#### # Parámetros a modificar. INICIO #### web_laser = 'http://www.punterolaser.com' # Incluir la dirección de la página web web_anchura = '1100' # Valor en pixeles de la anchura de la página web incrustada en el notebook. Solo modificar si no se ve bien la página web web_altura = '800' # Valor en pixeles de la altu...
Trabajo Filtro Interferencial/.ipynb_checkpoints/TrabajoFiltrosweb-checkpoint.ipynb
ecabreragranado/OpticaFisicaII
gpl-3.0
Tarea 3. Elección del filtro interferencial Vamos a buscar en internet un filtro interferencial comercial que permita evitar el riesgo de daño ocular para el puntero láser seleccionado. Se tratará de un filtro que bloquee la longitud de onda del puntero láser. Tarea 3 (a). Busqueda e información del filtro interferenc...
#### # Parámetros a modificar. INICIO #### web_filtro = 'http://www.semrock.com/FilterDetails.aspx?id=LP02-224R-25' # Incluir la dirección de la página web web_anchura = '1100' # Valor en pixeles de la anchura de la página web incrustada en el notebook. Solo modificar si no se ve bien la página web web_altura = '800...
Trabajo Filtro Interferencial/.ipynb_checkpoints/TrabajoFiltrosweb-checkpoint.ipynb
ecabreragranado/OpticaFisicaII
gpl-3.0
Tarea 3 (b). Verificación del filtro Empleando el dato de la transmitancia (T) a la longitud de onda del puntero láser comprobar que dicho filtro evitará el riesgo de lesión. Para ello vamos a usar los datos de la transmitancia del filtro seleccionado que aparecen en la página web de Semrock. Para cargar dichos datos e...
%pylab inline #### # Parámetros a modificar. INICIO #### longitud_de_onda_laser = 530 # Incluir el valor de la longitud de onda del puntero láser seleccionado (en nm) # Pintamos la gráfica original y un zoom empleando el rango de valores siguientes (para ver mejor la zona deseada) longitud_de_onda_minina = 500 # Incl...
Trabajo Filtro Interferencial/.ipynb_checkpoints/TrabajoFiltrosweb-checkpoint.ipynb
ecabreragranado/OpticaFisicaII
gpl-3.0
Load the file, and from the file pull our the engine (which tells us what the timestep was) and the move scheme (which gives us a starting point for much of the analysis).
# note that this log will overwrite the log from the previous notebook #import logging.config #logging.config.fileConfig("logging.conf", disable_existing_loggers=False) %%time flexible = paths.AnalysisStorage("ad_tps.nc") # opening as AnalysisStorage is a little slower, but speeds up the move_summary engine = flexibl...
examples/alanine_dipeptide_tps/AD_tps_3a_analysis_flex.ipynb
dwhswenson/openpathsampling
mit
Replica history tree and decorrelated trajectories The ReplicaHistoryTree object gives us both the history tree (often called the "move tree") and the number of decorrelated trajectories. A ReplicaHistoryTree is made for a certain set of Monte Carlo steps. First, we make a tree of only the first 25 steps in order to vi...
replica_history = ops_vis.ReplicaEvolution(replica=0) tree = ops_vis.PathTree( flexible.steps[0:25], replica_history ) tree.options.css['scale_x'] = 3 SVG(tree.svg()) # can write to svg file and open with programs that can read SVG with open("flex_tps_tree.svg", 'w') as f: f.write(tree.svg()) print("Deco...
examples/alanine_dipeptide_tps/AD_tps_3a_analysis_flex.ipynb
dwhswenson/openpathsampling
mit
Path length distribution Flexible length TPS gives a distribution of path lengths. Here we calculate the length of every accepted trajectory, then histogram those lengths, and calculate the maximum and average path lengths. We also use engine.snapshot_timestep to convert the count of frames to time, including correct u...
path_lengths = [len(step.active[0].trajectory) for step in flexible.steps] plt.hist(path_lengths, bins=40, alpha=0.5); print("Maximum:", max(path_lengths), "("+(max(path_lengths)*engine.snapshot_timestep).format("%.3f")+")") print ("Average:", "{0:.2f}".format(np.mean(path_lengths)), "("+(np.mean(path_len...
examples/alanine_dipeptide_tps/AD_tps_3a_analysis_flex.ipynb
dwhswenson/openpathsampling
mit
Path density histogram Next we will create a path density histogram. Calculating the histogram itself is quite easy: first we reload the collective variables we want to plot it in (we choose the phi and psi angles). Then we create the empty path density histogram, by telling it which CVs to use and how to make the hist...
from openpathsampling.numerics import HistogramPlotter2D psi = flexible.cvs['psi'] phi = flexible.cvs['phi'] deg = 180.0 / np.pi path_density = paths.PathDensityHistogram(cvs=[phi, psi], left_bin_edges=(-180/deg,-180/deg), bin_widths=...
examples/alanine_dipeptide_tps/AD_tps_3a_analysis_flex.ipynb
dwhswenson/openpathsampling
mit
Convert to MDTraj for analysis by external tools The trajectory can be converted to an MDTraj trajectory, and then used anywhere that MDTraj can be used. This includes writing it to a file (in any number of file formats) or visualizing the trajectory using, e.g., NGLView.
ops_traj = flexible.steps[1000].active[0].trajectory traj = ops_traj.to_mdtraj() traj # Here's how you would then use NGLView: #import nglview as nv #view = nv.show_mdtraj(traj) #view flexible.close()
examples/alanine_dipeptide_tps/AD_tps_3a_analysis_flex.ipynb
dwhswenson/openpathsampling
mit
Make plot
# Create the general blog and the "subplots" i.e. the bars f, ax1 = plt.subplots(1, figsize=(10,5)) # Set the bar width bar_width = 0.75 # positions of the left bar-boundaries bar_l = [i+1 for i in range(len(df['pre_score']))] # positions of the x-axis ticks (center of the bars as bar labels) tick_pos = [i+(bar_wid...
python/matplotlib_stacked_bar_plot.ipynb
tpin3694/tpin3694.github.io
mit
1. What is the voxelwise threshold?
# From smoothness + mask to ReselCount FWHM = 3 ReselSize = FWHM**3 MNI_mask = nib.load("MNI152_T1_2mm_brain_mask.nii.gz").get_data() Volume = np.sum(MNI_mask) ReselCount = Volume/ReselSize print("ReselSize: "+str(ReselSize)) print("Volume: "+str(Volume)) print("ReselCount: "+str(ReselCount)) print("------------") #...
Figure1_Power/.ipynb_checkpoints/RequiredEffectSizeForSufficientPower-checkpoint.ipynb
jokedurnez/RequiredEffectSize
mit
Detect 3 regions What if there are three regions and we want to detect all three. What should the power be in each region to have omnibus 80% power (find all 3)
regions = 3 PowerPerRegion = Power**(1/3) print("The power in each region should be: "+str(PowerPerRegion))
Figure1_Power/.ipynb_checkpoints/RequiredEffectSizeForSufficientPower-checkpoint.ipynb
jokedurnez/RequiredEffectSize
mit