markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
that's the same relationship as a plot
p = linspace(0,0.25,50) sd = list(map(f, p)) sd2 = list(map(f2, p)) plot (p,p, 'k') plot (p,p-sd, 'g--') plot (p,p+sd, 'g--') plot (p,p-sd2, 'r--') plot (p,p+sd2, 'r--') grid(b=True, which='major', color='k', linestyle='--')
iPython/Error-Estimation-for-Survey-Data.ipynb
oditorium/blog
agpl-3.0
For reference, the 2-sided tail probabilites as a function of $z$ (the way to read it is as follows: the probability of a Normal distribution being 2 standard deviations away from its mean to either side is about 0.05, or 5%). Saying it the other way round, a two-standard-deviation difference corresponds to about 95% c...
z=linspace(1.,3,100) plot(z,1. - (norm.cdf(z)-norm.cdf(-z))) grid(b=True, which='major', color='k', linestyle='--') plt.title("Probability of being beyond Z (2-sided) vs Z")
iPython/Error-Estimation-for-Survey-Data.ipynb
oditorium/blog
agpl-3.0
Using Monte Carlo we also need some additional parameters for our Monte Carlo
number_of_tries = 1000
iPython/Error-Estimation-for-Survey-Data.ipynb
oditorium/blog
agpl-3.0
We do some intermediate calculations...
N_female = int (N_people * ratio_female) N_male = N_people - N_female
iPython/Error-Estimation-for-Survey-Data.ipynb
oditorium/blog
agpl-3.0
...and then generate our random numbers...
data_male = np.random.binomial(n=1, p=proba, size=(number_of_tries, N_male)) data_female = np.random.binomial(n=1, p=proba, size=(number_of_tries, N_female))
iPython/Error-Estimation-for-Survey-Data.ipynb
oditorium/blog
agpl-3.0
...that we then reduce in one dimension (ie, over that people in the sample) to obtain our estimator for the probas for males and females as well as the difference. On the differences finally we look at the mean (should be zero-ish) and the standard deviation (should be consistent with the numbers above)
proba_male = map(numpy.mean, data_male) proba_female = map(numpy.mean, data_female) proba_diff = list((pm-pf) for pm,pf in zip(proba_male, proba_female)) np.mean(proba_diff), np.std(proba_diff)
iPython/Error-Estimation-for-Survey-Data.ipynb
oditorium/blog
agpl-3.0
Setup We have stored the data and simulation mesh so that they can just be downloaded and used here
url = "https://storage.googleapis.com/simpeg/kevitsa_synthetic/" files = ['dcipdata_12150N.txt', 'dc_mesh.txt', 'dc_sigma.txt', 'dc_topo.txt'] keys = ['data', 'mesh', 'sigma', 'topo'] downloads = Utils.download([url + f for f in files], folder='./KevitsaDC', overwrite=True) downloads = dict(zip(keys, downloads)) mesh ...
docs/case-studies/DCIP/Kevitsa_DC.ipynb
geoscixyz/computation
mit
Model This model is a synthetic based on geologic surfaces interpreted from seismic data over the Kevitsa deposit in Finland. Synthetic 3D conductivity model is generated, and below figure shows conductivity section acrosses the mineralzined zone of interest. Nearsurface conductor on the lefthand side corresponds to se...
figsize(8, 4) indy = 6 temp = 1./sigma.copy() temp[~actind] = np.nan out = mesh.plotSlice(temp, normal="Y", ind=indy, pcolorOpts={"norm": LogNorm(), "cmap":"jet_r"}, clim=(1e0, 1e3)) plt.ylim(-800, 250) plt.xlim(5000, 11000) plt.gca().set_aspect(2.) plt.title(("y= %d m")%(mesh.vectorCCy[indy])) cb = plt.colorbar(out[0]...
docs/case-studies/DCIP/Kevitsa_DC.ipynb
geoscixyz/computation
mit
Survey Direct current (DC) resisistivity and IP survey have been perforemd by using Titan24 system; pole-dpole array was used. We use a same survey set up at 12150N line, having 61 current sources (poles). Largest offset between current pole and potential eletrodes are around 2 km. We read in field data using below scr...
def getGeometricFactor(locA, locB, locsM, locsN, eps = 0.01): """ Geometric factor for a pole-dipole survey """ MA = np.abs(locA[0] - locsM[:, 0]) MB = np.abs(locB[0] - locsM[:, 0]) NA = np.abs(locA[0] - locsN[:, 0]) NB = np.abs(locB[0] - locsN[:, 0]) geometric = 1./(2*np.pi)...
docs/case-studies/DCIP/Kevitsa_DC.ipynb
geoscixyz/computation
mit
Problem This is a physics behind DC resistivity survey. Here we solve Poisson's equation and compute potential in our discretized domain. Survey information is required to run simulation.
m0 = np.ones(actind.sum())*np.log(1e-3) actMap = Maps.InjectActiveCells(mesh, actind, np.log(1e-8)) mapping = Maps.ExpMap(mesh) * actMap problem = EM.Static.DC.Problem3D_N(mesh, sigmaMap=mapping) problem.Solver = PardisoSolver if DCsurvey.ispaired: DCsurvey.unpair() problem.pair(DCsurvey)
docs/case-studies/DCIP/Kevitsa_DC.ipynb
geoscixyz/computation
mit
Forward Simulation Things are set. Now we can run simulaton by passing conductivity model to the DC problem.
f = problem.fields(np.log(sigma)[actind]) dpred = DCsurvey.dpred(np.log(sigma)[actind], f=f) appres = dpred / geometric dcdata = Data(DCsurvey, v=dpred) appresdata = Data(DCsurvey, v=appres)
docs/case-studies/DCIP/Kevitsa_DC.ipynb
geoscixyz/computation
mit
Plot the Data We are going to plot simulated data for each current pole. By moving slider bar below, you can explore the data at different current pole location. We provide both voltage and apparent resistivity.
def vizdata(isrc): fig = plt.figure(figsize = (7, 2)) src = srcLists[isrc] rx = src.rxList[0] data_temp = dcdata[src, rx] appres_temp = appresdata[src, rx] midx = (rx.locs[0][:,0] + rx.locs[1][:,0]) * 0.5 midz = (rx.locs[0][:,2] + rx.locs[1][:,2]) * 0.5 ax = plt.subplot(111) ax_1...
docs/case-studies/DCIP/Kevitsa_DC.ipynb
geoscixyz/computation
mit
Plot the currents Did you understand simluated data? why they are changing? Here we show how currents flow in the earth medium. Similarly, you can move slider bar to see how current changes depending upon current source location.
fig = plt.figure(figsize = (7, 1.5)) def vizJ(isrc): indy = 6 src = srcLists[isrc] rx = src.rxList[0] out = mesh.plotSlice(f[src, 'j'], vType="E", normal="Y", view="vec", ind=indy, streamOpts={"color":"k"}, pcolorOpts={"norm": LogNorm(), "cmap":"viridis"}, clim=(1e-10, 1e-4)) plt.plot(src.loc[0], sr...
docs/case-studies/DCIP/Kevitsa_DC.ipynb
geoscixyz/computation
mit
Plot Pseudo section We are going to plot simulated data for each current pole. By moving slider bar below, you can explore the data at different current pole location.
vmin, vmax = 1, 1e4 appres = dpred/geometric temp = appres.copy() Utils.plot2Ddata(np.c_[mid_x[inds_data], mid_z[inds_data]], temp, ncontour=100, dataloc=True, scale="log", contourOpts={"vmin":np.log10(vmin), "vmax":np.log10(vmax)}) cb = plt.colorbar(out[0], orientation="horizontal", format="1e%.0f", ticks=np.linspace(...
docs/case-studies/DCIP/Kevitsa_DC.ipynb
geoscixyz/computation
mit
Plot Field data (pseudo-section) Let's see how the field data looks like on this line (12150N). Are they similar with our simulated data?
vmin, vmax = 1, 1e4 temp = dcipdata[:,8].copy() temp[dcipdata[:,8]<vmin] = vmin temp[dcipdata[:,8]>vmax] = vmax out = Utils.plot2Ddata(np.c_[mid_x[inds_data], mid_z[inds_data]], temp[inds_data], ncontour=100, dataloc=True, scale="log") cb = plt.colorbar(out[0], orientation="horizontal", format="1e%.0f", ticks=np.linspa...
docs/case-studies/DCIP/Kevitsa_DC.ipynb
geoscixyz/computation
mit
Loading Data using Pandas
data=pd.read_csv('../data/Testdata.dat', delimiter=' ') # Print the first 8 rows of the dataset data.head(8) #Print the last 8 rows of the dataset data.tail(8) # Commands used to check the title names in each column as some of the titles were omitted data.dtypes.head()
bin/Compiled_Codes_for_Final_Project.ipynb
Jhanelle/Jhanelle_New_Version_of_final_project
mit
Hypothesis and Questions .......... Things I need to do: Format the date properly. I need help do use regular expression to fix the format of my date
# Here we extract only two columns from the data as these are the main variables for the statistcal analysis strain_df=data[['strain','speed']] strain_df.head() # Eliminate NaN from the dataset strain_df=strain_df.dropna() strain_df.head() #Resample the data to group by strain strain_resampled=strain_df.groupby('...
bin/Compiled_Codes_for_Final_Project.ipynb
Jhanelle/Jhanelle_New_Version_of_final_project
mit
Interpretation of Histograms Based on the histograms of the respective strain it is clear that the data does not follow a normal distribution. Therefore t-tests and linear regression cannot be applied to this data set as planned.
# I know I should applu Apply Kruskal. wallis statistics to data, however I am not sure how to deal with the array scipy.stats.mstats.kruskalwallis( , ) def test_mean1(): '''This function created to give the mean values for the different strains in the dataset. The input of the function is the raw speed of t...
bin/Compiled_Codes_for_Final_Project.ipynb
Jhanelle/Jhanelle_New_Version_of_final_project
mit
torchvision for loading input images This is done through the torchvision.io.read_image function which returns a torch.Tensor of the image.
img = torchvision.io.read_image("data/birdie2.jpg") img = torchvision.transforms.ToPILImage()(img) display(img)
versions/2022/tools/python/input_demo.ipynb
roatienza/Deep-Learning-Experiments
mit
Visualize the transforms done before model prediction In an earlier example, we used the torchvision.transforms module to apply a series of transformations to the input image before passing it to the model. Let us visualize the resulting image.
img = torchvision.io.read_image("data/birdie2.jpg") normalize = torchvision.transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) img = torchvision.transforms.Resize(256)(img) img = torchvision.transforms.CenterCrop(224)(img).float()/255. img = normali...
versions/2022/tools/python/input_demo.ipynb
roatienza/Deep-Learning-Experiments
mit
plot_waveform function from torchaudio This function accepts raw waveform and sampling rate to plot the waveform for visualization.
def plot_waveform(waveform, sample_rate, title="Waveform", xlim=None, ylim=None): waveform = waveform.numpy() num_channels, num_frames = waveform.shape time_axis = torch.arange(0, num_frames) / sample_rate figure, axes = plt.subplots(num_channels, 1) if num_channels == 1: axes = [axes] ...
versions/2022/tools/python/input_demo.ipynb
roatienza/Deep-Learning-Experiments
mit
Using torchaudio to load audio and display waveform using plot_waveform This is an alternative method to librosa for loading audio.
wav_path = "data/ljspeech.wav" metadata = torchaudio.info(wav_path) print(metadata) wav, sample_rate = torchaudio.load(wav_path) display(Audio(wav, rate=sample_rate)) plot_waveform(wav, sample_rate)
versions/2022/tools/python/input_demo.ipynb
roatienza/Deep-Learning-Experiments
mit
<p><font size="6"><em>-</em> CLEANDATA <em>-</em></font></p>
modelRatings = df.pivot_table(index=['EQP_LOCAL_EQP'],columns=['EQP_MODEL_EQP'],values='EQP_FAIL_CNT_EQP').iloc[:, 1:10] modelRatings.head()
CRUCK v1.ipynb
ChrisRucker/Samples
mit
<p><font size="6"><em>-</em> SUBRATINGS <em>-</em></font></p>
MCARD9060Ratings = modelRatings['MCARD9060'] MCARD9060Ratings.head()
CRUCK v1.ipynb
ChrisRucker/Samples
mit
<p><font size="6"><em>-</em> PAIRWISE <em>-</em></font></p>
similarModels = modelRatings.corrwith(MCARD9060Ratings) similarModels = similarModels.dropna() df = pd.DataFrame(similarModels) df.head(20)
CRUCK v1.ipynb
ChrisRucker/Samples
mit
<p><font size="6"><em>-</em> SCORE <em>-</em></font></p>
similarModels.sort_values(ascending=False).head(20)
CRUCK v1.ipynb
ChrisRucker/Samples
mit
Preparing data set sweep First, we're going to define the data sets that we'll sweep over. The following cell does not need to be modified unless if you wish to change the datasets or reference databases used in the sweep.
dataset_reference_combinations = [ ('mock-1', 'gg_13_8_otus'), # formerly S16S-1 ('mock-2', 'gg_13_8_otus'), # formerly S16S-2 ('mock-3', 'gg_13_8_otus'), # formerly Broad-1 ('mock-4', 'gg_13_8_otus'), # formerly Broad-2 ('mock-5', 'gg_13_8_otus'), # formerly Broad-3 ('mock-6', 'gg_13_8_otus'), # formerly Turnbau...
ipynb/mock-community/taxonomy-assignment-blast+.ipynb
gregcaporaso/short-read-tax-assignment
bsd-3-clause
Preparing the method/parameter combinations and generating commands Now we set the methods and method-specific parameters that we want to sweep. Modify to sweep other methods. Note how method_parameters_combinations feeds method/parameter combinations to parameter_sweep() in the cell below.
method_parameters_combinations = { 'blast+' : {'p-evalue': [0.001], 'p-maxaccepts': [1, 10, 100], 'p-perc-identity': [0.80, 0.97, 0.99], 'p-min-consensus': [0.51, 0.75, 0.99]} }
ipynb/mock-community/taxonomy-assignment-blast+.ipynb
gregcaporaso/short-read-tax-assignment
bsd-3-clause
Now enter the template of the command to sweep, and generate a list of commands with parameter_sweep(). Fields must adhere to following format: {0} = output directory {1} = input data {2} = reference sequences {3} = reference taxonomy ...
command_template = "mkdir -p {0}; qiime feature-classifier blast --i-query {1} --o-classification {0}/rep_seqs_tax_assignments.qza --i-reference-reads {2} --i-reference-taxonomy {3} {5}; qiime tools export {0}/rep_seqs_tax_assignments.qza --output-dir {0}" commands = parameter_sweep(data_dir, results_dir, refe...
ipynb/mock-community/taxonomy-assignment-blast+.ipynb
gregcaporaso/short-read-tax-assignment
bsd-3-clause
Generate per-method biom tables Modify the taxonomy_glob below to point to the taxonomy assignments that were generated above. This may be necessary if filepaths were altered in the preceding cells.
taxonomy_glob = join(results_dir, '*', '*', '*', '*', 'taxonomy.tsv') generate_per_method_biom_tables(taxonomy_glob, data_dir)
ipynb/mock-community/taxonomy-assignment-blast+.ipynb
gregcaporaso/short-read-tax-assignment
bsd-3-clause
Python 何时执行装饰器 装饰器一个关键特性是,它们被装饰的函数定义之后立即运行。这通常是在导入模块(Python 加载模块时),如下面的 register.py 模块
#!/usr/bin/env python # encoding: utf-8 registry = [] def register(func): print('running register(%s)' % func) registry.append(func) return func @register def f1(): print('running f1()') @register def f2(): print('running f2()') def f3(): print('running f3()') def main(): print('runnin...
content/fluent_python/7_decorate.ipynb
ghvn7777/ghvn7777.github.io
apache-2.0
看到 register 在模块中其它函数之前运行(两次)。调用 register 时,传给它的参数是被装饰的函数,例如 <function f1 at 0x7fbac67ca6a8> 加载模块后,registry 有两个被装饰函数的引用:f1 和 f2。这两个函数,以及 f3,只在 main 明确调用它们时候才执行 如果单纯导入 register.py
import register
content/fluent_python/7_decorate.ipynb
ghvn7777/ghvn7777.github.io
apache-2.0
此时查看 registry 的值:
register.registry
content/fluent_python/7_decorate.ipynb
ghvn7777/ghvn7777.github.io
apache-2.0
这主要为了强调,函数装饰器在导入模块时立即执行,而被装饰的函数只在明确调用时执行。这突出了 Python 程序员说的 导入时 和 运行时 的区别 考虑到装饰器在真实代码中的常用方式,上面的例子有两个不同寻常的地方: 装饰器函数与被装饰的函数在同一个模块定义,实际上装饰器通常在一个模块中定义,然后应用到其它模块中的函数上 register 装饰器返回的函数与通过参数传入的相同,实际上大多数装饰器会在内部定义一个函数,然后返回 使用装饰器改进 “策略” 模式 在上一章的商品折扣例子中有一个问题,每次通过 best_promo 函数判断最大折扣,这个函数也需要一个折扣函数列表,如果忘了添加,会导致一些不容易被发现的问题。下面使用注册装...
promos = [] def promotion(promo_func): promos.append(promo_func) return promo_func @promotion def fidelity_promo(order): '''为积分为 1000 或以上的顾客提供 5% 折扣''' return order.total() * .05 if order.customer.fidelity >= 1000 else 0 @promotion def bulk_item_promo(order): '''单个商品为 20 个或以上时提供 %10 折扣''' ...
content/fluent_python/7_decorate.ipynb
ghvn7777/ghvn7777.github.io
apache-2.0
这个方案有几个优点 促销策略函数无需使用特殊名(即不用以 _promo 结尾) @promotion 装饰器突出了被装饰函数的作用,还可以临时禁止某个折扣策略,只需要把装饰器注释 促销折扣策略可以在其它模块中定义,在系统任意地方都行,只要使用 @promotion 装饰器即可 不过,多数的装饰器会修改被装饰函数。通常,它们会定义一个内部函数,然后将其返回,替换被装饰的函数。使用内部函数的代码几乎都要靠闭包才能正确工作。为了理解闭包,我们先退后一步,了解 Python 中变量的作用域 变量作用域规则
def f1(a): print(a) print(b) f1(3)
content/fluent_python/7_decorate.ipynb
ghvn7777/ghvn7777.github.io
apache-2.0
这里出现错误不奇怪,如果先给全局变量 b 赋值,然后调用 f1,就不会出错
b = 6 f1(3)
content/fluent_python/7_decorate.ipynb
ghvn7777/ghvn7777.github.io
apache-2.0
这也很正常,下面是一个会让你大吃一惊的例子:),前面代码和上面的例子一样,可是,在赋值之前,第二个 print 失败了。
b = 6 def f2(a): print(a) print(b) b = 9 f2(3)
content/fluent_python/7_decorate.ipynb
ghvn7777/ghvn7777.github.io
apache-2.0
首先输出了 3,表明 print(a) 执行了。但是 print(b) 无法执行,这是因为,Python 编译函数的定义时,判断 b 是局部变量,因为在函数中给它赋值了。生成的字节码证实了这种判断,Python 会尝试从本地环境获取 b。后面调用 f2(3) 时,f2 的定义体会获取并打印局部变量 a 的值,但是尝试获取局部变量 b 的时候,发现 b 没有绑定值。 这不是缺陷,而是设计选择,Python 不要求声明变量,但是假定在函数定义体中赋值的变量是局部变量。 如果在函数中赋值时想让解释器把 b 当成全局变量,要求使用 global 声明:
b = 6 def f3(a): global b print(a) print(b) b = 9 f3(3) f3(3) b = 30 b
content/fluent_python/7_decorate.ipynb
ghvn7777/ghvn7777.github.io
apache-2.0
了解了 Python 的变量作用域之后,我们就可以讨论闭包了 闭包 人们有时会把闭包和匿名函数弄混,这是有历史原因的,在函数内部定义函数不常见,直到开始使用匿名函数才这么做。而且,只有涉及嵌套函数时才有闭包的问题。因此,很多人是同时知道这两个概念的 其实,闭包指延伸了作用域的函数,其中包含函数定义体中引用、但是不在定义体中定义的非全局变量。函数是不是匿名的没有关系,关键是它能访问定义体之外定义的非全局变量。 我们通过例子来理解,加入 avg 函数是计算不断增加的系列值的均值,例如整个历史中的某个商品的平均收盘价,每天都会增加新价格,因此平均值要考虑至目前为止的所有价格。 一开始,avg 是这样的:
class Averager(): def __init__(self): self.series = [] def __call__(self, new_value): self.series.append(new_value) total = sum(self.series) return total / len(self.series) avg = Averager() avg(10) avg(11) avg(12)
content/fluent_python/7_decorate.ipynb
ghvn7777/ghvn7777.github.io
apache-2.0
下面是函数式实现,使用高阶函数 make_averager,调用 make_averager,返回一个 averager 函数对象。每次调用 averager 时,都会把参数添加到系列值中,然后计算当前平均值
def make_averager(): series = [] def averager(new_value): series.append(new_value) total = sum(series) return total / len(series) return averager avg = make_averager() avg(10) avg(11) avg(12)
content/fluent_python/7_decorate.ipynb
ghvn7777/ghvn7777.github.io
apache-2.0
注意,这两个例子有共通之处,调用 Averager() 或 make_averager() 得到一个可调用对象 avg,它会更新历史值,然后计算当前均值。 Averager 将历史值存在哪里很明显,self.series 属性中,avg 函数将 series 存在哪里呢? 注意 series 是 make_averager 的局部变量,因为那个函数的定义体中初始化了 series,series = [],可是调用 avg(10) 时候,make_averager 已经返回了,而它本身地作用域也没有了 在 averager 函数中,series 是自由变量。这是一个技术术语,指未在本地作用域绑定的变量,averager 的闭包延伸到这...
avg.__code__.co_varnames avg.__code__.co_freevars
content/fluent_python/7_decorate.ipynb
ghvn7777/ghvn7777.github.io
apache-2.0
series 的绑定在返回的 avg 函数的 __closure__ 属性中,avg.__closure__ 中的各个元素对应于 avg.__code__.co_freevars 中的一个名称。这些元素是 cell 对象,有个 cell_contents 属性,保存着真正的值。这些属性如下所示:
avg.__code__.co_freevars avg.__closure__ avg.__closure__[0].cell_contents
content/fluent_python/7_decorate.ipynb
ghvn7777/ghvn7777.github.io
apache-2.0
综上,闭包是一种函数,它会保留定义函数时存在的自有变量的绑定,这样调用函数时,虽然定义域不可用了,但是仍然能使用这些绑定 注意,只有嵌套在其它函数中的函数才可能需要处理不在全局作用域中的外部变量 nonlocal 声明 前面实现的计算平均值方法效率不高,因为每次把值存到历史数列中,遍历历史数列求平均数,更好的方法是只存储目前的平均数和个数,然后用这两个数计算平均值 下面是一个有缺陷的的程序,只是为了阐明某个观点,我们来看一下:
def make_averager(): count = 0 total = 0 def averager(new_value): count += 1 total += new_value return total / count return averager avg = make_averager() avg(10)
content/fluent_python/7_decorate.ipynb
ghvn7777/ghvn7777.github.io
apache-2.0
问题是,当 count 是数字和不可变类型时, count += 1 和 count = count + 1 是等价的。我们在 averager 函数中为 count 赋值了,这会把 Count变成局部变量,total 变量也会受这个问题影响。 在前面的例子没有这个问题,因为我们没有给 series 赋值,我们只是调用 series.append(), 并把 series 传给 sum 和 len。也就是说,我们利用了列表是可变对象的这一事实 但是对于数字,字符串,元组等不可变类型来说,只能读取,不能更新。如果尝试像上面重新绑定,就会隐式的创建局部变量 count。这样 count 就不是自由变量了,因此不会保存到闭包中 为了解决这...
def make_averager(): count = 0 total = 0 def averager(new_value): nonlocal count, total count += 1 total += new_value return total / count return averager avg = make_averager() avg(10) avg(11)
content/fluent_python/7_decorate.ipynb
ghvn7777/ghvn7777.github.io
apache-2.0
Python 2 中的处理方法可以把 count 和 total 存储为可变对象,例如列表和字典就可以了。 实现一个简单的装饰器 下面定义一个装饰器,会在每次调用被装饰的函数时计时,然后把经过的时间、传入的参数和调用结果打印
import time def clock(func): def clocked(*args): #返回计时器的精准时间(系统的运行时间),包含整个系统的睡眠时间。系统起始运行时间不确定,所以一般只有两个时间差才有效 t0 = time.perf_counter() result = func(*args) elapsed = time.perf_counter() - t0 name = func.__name__ # repr 方法用得好,用的对象例如列表不能用 str(),但是可以用 repr() 获取对象的标准字符串...
content/fluent_python/7_decorate.ipynb
ghvn7777/ghvn7777.github.io
apache-2.0
clock 中还定义 clocked 函数的原因是 clock 函数中的内容在模块引入后会被执行,所以再嵌套一个函数,保证不会在模块引入后直接执行装饰器内容,然后在 clocked 中对原函数计时 工作原理 @clock def factorial(n): return 1 if n &lt; 2 else n * factorial(n - 1) 等价于 def factorial(n): return 1 if n &lt; 2 else n * factorial(n - 1) factorial = clock(factorial) 因此,在这两个示例中,factorial 会作为 func 参数传给 c...
factorial.__name__
content/fluent_python/7_decorate.ipynb
ghvn7777/ghvn7777.github.io
apache-2.0
所以,现在 factorial 保存的是 clocked 函数的引用。此后,调用 factorial(n),执行的都是 clocked(n)。clocked 大致做了以下几件事 记录初试时间 t0 调用原来的 factorial 函数,保存结果 计算经过的时间 格式化收集的数据,打印 返回第二步保存的结果 上面的 clock 装饰器有几个缺点,不支持关键字参数,而且遮盖了被装饰函数的 __name__ 和 __doc__ 属性。下面使用 functools.wraps 装饰器可以把相关属性从 func 复制到 clocked 中。此外还能正确处理关键字参数
import time import functools def clock(func): @functools.wraps(func) def clocked(*args, **kwargs): t0 = time.time() result = func(*args, **kwargs) elapsed = time.time() - t0 name = func.__name__ arg_lst = [] if args: arg_lst.append(', '.join...
content/fluent_python/7_decorate.ipynb
ghvn7777/ghvn7777.github.io
apache-2.0
看到 factorial 的属性已经被复制到了 clocked 中。functools.wraps 只是标准库中拿来即用的装饰器之一,下面介绍 functools 模块中最令人印象深刻的两个装饰器: lru_cache 和 singledispatch 标准库中的装饰器 Python 内置了 3 个用于装饰器方法的函数:property, classmethod, staticmethod。property 在第 19 章讨论, 另外两个在第 9 章讨论 另一个常见的装饰器是 functools.wraps,它的作用是协助构建行为良好的装饰器。我们在前面用过,现在来介绍标准库中最值得关注的两个装饰器 lru_cache 和全新的 s...
@clock def fibonacci(n): if n < 2: return n return fibonacci(n - 2) + fibonacci(n - 1) print(fibonacci(6))
content/fluent_python/7_decorate.ipynb
ghvn7777/ghvn7777.github.io
apache-2.0
看到很浪费时间, fibonacci(1) 调用了 8 次, fibonacci(2) 调用了 5 次。但是如果增加两行代码,性能会显著改善,如下:
@functools.lru_cache() # note @clock def fibonacci(n): if n < 2: return n return fibonacci(n - 2) + fibonacci(n - 1) print(fibonacci(6))
content/fluent_python/7_decorate.ipynb
ghvn7777/ghvn7777.github.io
apache-2.0
注意,必须像常规函数那样调用 lru_cache。这一行中有一对括号: @functools.lru_cache()。这么做的原因是,lru_cache() 可以接受配置参数,稍后说明 这里还叠放了装饰器,lru_cache() 应用到了 @clock 返回的函数上 这样一来,看到执行时间减半,而且 n 的每个值只调用一次函数。 除了优化递归算法之外,lru_cache 在从 Web 中获取信息的应用也能发挥巨大作用。特别要注意,lru_cache 可以使用两个可选的参数来配置。它的签名是:functools.lru_cache(maxsize = 128, typed = False) maxsize 指定最多存储多少个调用结果,...
import html def htmlize(obj): content = html.escape(repr(obj)) # 对字符串进行转义,详情见注释说明 return '<pre>{}</pre>'.format(content) ''' html.escape(s, quote=True) Convert the characters &, < and > in string s to HTML-safe sequences. Use this if you need to display text that might contain such characters in HTML. If the ...
content/fluent_python/7_decorate.ipynb
ghvn7777/ghvn7777.github.io
apache-2.0
这个函数适用于任何 Python 类型,但是我们想做个扩展,让它使用特别的方式显示某些类型。 str: 把内部的换行符换成 &lt;br&gt;\n;不使用 &lt;pre&gt;,而是使用 &lt;p&gt; int: 以十进制和十六进制显示数字 list:输出一个 HTML 列表,根据各个元素的类型进行格式化 我们想要的行为如下所示:
htmlize({1, 2, 3}) # 默认情况下, 在 <pre> 标签内显示 HTML 转义后的字符串表示形式 htmlize(abs) htmlize('Heimlich & Co.\n- a game')# str 对象也是显示 HTML 转义后的形式,\n 换成 <br>\n 并且放到 <p> 标签内 htmlize(42) # 数字显示 10进制和 16进制形式 print(htmlize(['alpha', 66, {3, 2, 1}])) #列表根据各自的类型格式化显示
content/fluent_python/7_decorate.ipynb
ghvn7777/ghvn7777.github.io
apache-2.0
Python 不支持重载方法或函数,所以我们不能使用不同签名定义 htmlize 的变体。也无法使用不同方式处理不同的数据类型。在 Python 中,一种常见的做法是把 htmlize 变成一个分派函数,使用一串 if else 来调用专门的函数,但是这样太笨,而且不好维护 Python 3.4 新增了 functools.singledispatch 装饰器可以把整体方案拆成多个模块,甚至可以为你无法修改的类提供专门的函数。使用 @singledispathc 会把普通的函数变成泛函数。根据第一参数的类型,以不同方式执行相同操作的一组函数
from functools import singledispatch from collections import abc import numbers import html @singledispatch def htmlize(obj): content = html.escape(repr(obj)) return '<pre>{}</pre>'.format(content) @htmlize.register(str) #各个函数用 @base_function.register(type) 装饰 def _(text): #专门函数的名称不重要, _ 是个不错的选择 content =...
content/fluent_python/7_decorate.ipynb
ghvn7777/ghvn7777.github.io
apache-2.0
只要有可能,注册的专门函数应该处理抽象基类(例如 numbers.Integral 和 abc.MutableSequence),不要处理具体实现(如 int 和 list)。这样,代码支持的兼容类型更广泛 叠放装饰器 上面已经用过了叠放装饰器的方式,@lru_cache 应用到 @clock 装饰 fibonacci 得到的结果上。上面的例子最后也用到了两个 @htmlize.register 装饰器 把 @d1 和 @d2 两个装饰器按顺序应用到 f 函数上,作用相当于 f = d1(d2(f)),也就是说 @d1 @d2 def f(): print('f') 等同于 ``` def f(): print('...
registry = [] def register(func): print('funning register(%s)' % func) registry.append(func) return func @register def f1(): print('running f1()') print('running main()') print('registry ->', registry) f1()
content/fluent_python/7_decorate.ipynb
ghvn7777/ghvn7777.github.io
apache-2.0
为了便于启动和禁用 register 执行的函数注册功能,我们为他提供一个可选的 activate 参数,设为 False 时,不注册被装饰的函数。实现如下,从概念上来看,这个新的 register 函数不是装饰器,而是装饰器工厂函数。调用它会返回真正的装饰器,这才是应用到目标上的装饰器 为了接受参数,新的 register 装饰器必须作为函数调用
registry = set() #添加删除元素更快(相比列表) def register(active = True): def decorate(func): #这是真正的装饰器,它的参数是一个函数 print('running register(active=%s)->decorate(%s)' % (active, func)) if active: registry.add(func) else: registry.discard(func) return func #decorate...
content/fluent_python/7_decorate.ipynb
ghvn7777/ghvn7777.github.io
apache-2.0
这里的关键是,register() 要返回 decorate,并把它应用到被装饰器函数上,注意只有 f2 在 registry 中,因为 f1 传给装饰器工厂函数的参数是 False。如果不能使用 @ 语法,那就要像常规函数那样使用 register,若想把 f 添加到 registry 中,则装饰 f 函数的语法是 register()(f)。下面演示了如何把函数添加到 registry 中,以及如何从中删除函数
register()(f3) registry register(active=False)(f2) registry
content/fluent_python/7_decorate.ipynb
ghvn7777/ghvn7777.github.io
apache-2.0
参数化装饰器原理相当复杂,我们讨论的是很简单的内容,参数化装饰器通常会把被装饰的函数替换掉,而且结构上需要多一层嵌套,接下来会讨论这种函数金字塔 参数化 clock 装饰器 我们这次为 clock 装饰器添加一个功能,让用户传入一个格式字符串,控制被装饰函数的输出,见下面例子,为了方便起见,我们下面用的是最初实现的 clock,而不是示例中使用 @functools.wraps 的改进后的版本,因为那一版增加了一层函数
import time DEFAULT_FMT = '[{elapsed:0.8f}s] {name}({args}) -> {result}' def clock(fmt = DEFAULT_FMT): # 参数化装饰器工厂函数 def decorate(func): # 真正的装饰器 def clocked(*_args): # 包装被装饰器的函数 t0 = time.time() _result = func(*_args) elapsed = time.time() - t0 name...
content/fluent_python/7_decorate.ipynb
ghvn7777/ghvn7777.github.io
apache-2.0
下面是用户传入自定义的格式字符串的调用:
@clock('{name}: {elapsed}s') def snooze(seconds): time.sleep(seconds) for i in range(3): snooze(.123) @clock('{name}({args}) dt={elapsed:0.3f}s') def snooze(seconds): time.sleep(seconds) for i in range(3): snooze(.123)
content/fluent_python/7_decorate.ipynb
ghvn7777/ghvn7777.github.io
apache-2.0
Relevant Parameters The 'l3' parameter describes how much third light exists in a given passband. Since this is passband dependent and only used for flux measurments - it does not yet exist for a new empty Bundle.
b.filter(qualifier='l3')
2.0/tutorials/l3.ipynb
phoebe-project/phoebe2-docs
gpl-3.0
We now see that the LC dataset created an 'l3' parameters for the new dataset.
b.filter(qualifier='l3') print b['l3@lc01']
2.0/tutorials/l3.ipynb
phoebe-project/phoebe2-docs
gpl-3.0
Influence on Light Curves (Fluxes) "Third" light is simply additional flux added to the light curve from some external source - whether it be crowding from a background object, light from the sky, or an extra component in the system that is unaccounted for in the system hierarchy. To see this we'll compare a light curv...
b.run_compute(irrad_method='none', model='no_third_light') b['l3@lc01'] = 5 b.run_compute(irrad_method='none', model='with_third_light')
2.0/tutorials/l3.ipynb
phoebe-project/phoebe2-docs
gpl-3.0
As expected, adding 5 W/m^3 of third light simply shifts the light curve up by that exact same amount.
fig = plt.figure() ax1, ax2 = fig.add_subplot(121), fig.add_subplot(122) axs, artists = b['lc01'].plot(model='no_third_light', ax=ax1) axs, artists = b['lc01'].plot(model='with_third_light', ax=ax2)
2.0/tutorials/l3.ipynb
phoebe-project/phoebe2-docs
gpl-3.0
Influence on Meshes (Intensities) "Third" light does not affect the intensities stored in the mesh (including those in relative units). In other words, like distance, "third" light only scales the fluxes. NOTE: this is different than pblums which DO affect the relative intensities. Again, see the pblum tutorial for m...
b.add_dataset('mesh', times=[0], dataset='mesh01') b['l3@lc01'] = 0.0 b.run_compute(irrad_method='none', model='no_third_light') b['l3@lc01'] = 5 b.run_compute(irrad_method='none', model='with_third_light') print "no_third_light abs_intensities: ", b.get_value(qualifier='abs_intensities', component='primary', data...
2.0/tutorials/l3.ipynb
phoebe-project/phoebe2-docs
gpl-3.0
Sometimes in order to run some programming software we need to prepare an input description file which specifies the model setup (e.g., chemical mechanism, intergration method, desired type of results, etc). If we are planning to run the model several times with different, for example, initial conditions, constracting ...
header_text = '{!-*- F90 -*-}' with open('header.inp','w') as header_file: header_file.write(header_text)
content/notebooks/2016-01-22-string-formatting.ipynb
ueapy/ueapy.github.io
mit
The next four lines define the #INITVALUES section of the file, where the initial concentrations (actually, number densities) of chemical compounds of interest are set. If we want to change only numerical values in this section, it is logical to create a text template which would take into account the syntax of the tar...
def gen_concs_string(O3=7.50e+11, CH4=4.55e+13, CO=2.55e+12): concs_string = \ """ #INITVALUES O3\t={O3_nd:.2e}; CH4\t={CH4_nd:.2e}; CO\t={CO_nd:.2e};"""\ .format(O3_nd=O3, CH4_nd=CH4, CO_nd=CO) return concs_string
content/notebooks/2016-01-22-string-formatting.ipynb
ueapy/ueapy.github.io
mit
For convinience we can even set default values for each of the arguments (e.g., here default ozone initial concentration is $7.5\times 10^{11}$ molecules per $cm^{3}$). By the way, we have just used a new style of string formatting in Python! An old way of doing the same would include a '%' sign in front of the functio...
def gen_time_str(tstart, nhours, timestep, temp): time_string = \ """ #INLINE F90_INIT TSTART = {tstart}*{timestep} TEND = TSTART + {nhours}*3600 DT = {timestep} TEMP = {temp} #ENDINLINE"""\ .format(tstart=tstart, nhours=nhours, timestep=timestep, temp=temp) return time_string
content/notebooks/2016-01-22-string-formatting.ipynb
ueapy/ueapy.github.io
mit
And finally let's assemble our input description file:
# Read header with open('header.inp','r') as header_file: header_text = header_file.read() # Use default inital concentrations and set model integration time and temperature concstr = gen_concs_string() timestr = gen_time_str(0,7,3600,298) # Combine all strings together full_str = header_text + concstr + timestr #...
content/notebooks/2016-01-22-string-formatting.ipynb
ueapy/ueapy.github.io
mit
Creating a file mask There are plenty of other ways to use a new string formatting in Python to your advantage. For example, you could use it to create file names in a loop:
file_mask = '+{one}hours_{two}UTC.jpg' for i, j in zip((1,2,3), (4,5,6)): print(file_mask.format(one=i, two=j)) HTML(html)
content/notebooks/2016-01-22-string-formatting.ipynb
ueapy/ueapy.github.io
mit
TensorFlow 애드온 콜백: TQDM 진행률 표시줄 <table class="tfo-notebook-buttons" align="left"> <td><a target="_blank" href="https://www.tensorflow.org/addons/tutorials/tqdm_progress_bar"><img src="https://www.tensorflow.org/images/tf_logo_32px.png">TensorFlow.org에서 보기</a></td> <td><a target="_blank" href="https://colab.research...
!pip install -U tensorflow-addons !pip install -q "tqdm>=4.36.1" import tensorflow as tf import tensorflow_addons as tfa from tensorflow.keras.datasets import mnist from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Dropout, Flatten import tqdm # quietly deep-reload tqdm impo...
site/ko/addons/tutorials/tqdm_progress_bar.ipynb
tensorflow/docs-l10n
apache-2.0
데이터 가져오기 및 정규화
# the data, split between train and test sets (x_train, y_train), (x_test, y_test) = mnist.load_data() # normalize data x_train, x_test = x_train / 255.0, x_test / 255.0
site/ko/addons/tutorials/tqdm_progress_bar.ipynb
tensorflow/docs-l10n
apache-2.0
간단한 MNIST CNN 모델 빌드하기
# build the model using the Sequential API model = Sequential() model.add(Flatten(input_shape=(28, 28))) model.add(Dense(128, activation='relu')) model.add(Dropout(0.2)) model.add(Dense(10, activation='softmax')) model.compile(optimizer='adam', loss = 'sparse_categorical_crossentropy', metr...
site/ko/addons/tutorials/tqdm_progress_bar.ipynb
tensorflow/docs-l10n
apache-2.0
기본 TQDMCallback 사용법
# initialize tqdm callback with default parameters tqdm_callback = tfa.callbacks.TQDMProgressBar() # train the model with tqdm_callback # make sure to set verbose = 0 to disable # the default progress bar. model.fit(x_train, y_train, batch_size=64, epochs=10, verbose=0, callback...
site/ko/addons/tutorials/tqdm_progress_bar.ipynb
tensorflow/docs-l10n
apache-2.0
아래는 위의 셀을 실행할 때 예상되는 출력입니다.
# TQDMProgressBar() also works with evaluate() model.evaluate(x_test, y_test, batch_size=64, callbacks=[tqdm_callback], verbose=0)
site/ko/addons/tutorials/tqdm_progress_bar.ipynb
tensorflow/docs-l10n
apache-2.0
1.2. Tuple definition And some timing ... :-)
!python -m timeit "x = (1, 'a', 'b', 'a')" a = (1, 'a', 'b', 'a')
02-basics/containers/02-lists.ipynb
vicente-gonzalez-ruiz/YAPT
cc0-1.0
1.3. Counting ocurrences in tuples
a.count('a')
02-basics/containers/02-lists.ipynb
vicente-gonzalez-ruiz/YAPT
cc0-1.0
1.4. Searching for an item in a tuple
a.index('b')
02-basics/containers/02-lists.ipynb
vicente-gonzalez-ruiz/YAPT
cc0-1.0
1.5. Slicing in tuples
a a[2] # The 3-rd item a[2:1] # Extract the tuple from the 2-nd item to the 1-st one a[2:2] # Extract from the 2-nd item to the 2-nd item a[2:3] # Extract from the 2-nd item to the 3-rd one a[2:4] # Extract one item more a[1:] # Extract from the 1-st to the end a[:] # Extract all items (a==a[:])
02-basics/containers/02-lists.ipynb
vicente-gonzalez-ruiz/YAPT
cc0-1.0
1.6. Functions can return tuples
def return_tuple(): return (1, 'a', 2) print(return_tuple())
02-basics/containers/02-lists.ipynb
vicente-gonzalez-ruiz/YAPT
cc0-1.0
1.7. Swapping pairs with tuples is fun!
a = 1; b = 2 print(a, b) (a, b) = (b, a) print(a, b)
02-basics/containers/02-lists.ipynb
vicente-gonzalez-ruiz/YAPT
cc0-1.0
1.8. Tuples are inmutable They can not grow:
a = (1, 'a') print(id(a),a) a += (2,) # This creates a new instance of 'a' print(id(a),a)
02-basics/containers/02-lists.ipynb
vicente-gonzalez-ruiz/YAPT
cc0-1.0
... or be changed:
a[1] = 2
02-basics/containers/02-lists.ipynb
vicente-gonzalez-ruiz/YAPT
cc0-1.0
Tuples are inmutable!
a = 1; b = 2 print('"a" is in', id(a)) t = (a, b) print('"t" is in', id(t), 'and contains', t) a = 3 print('"a" is in', id(a)) print('"t" is in', id(t), 'and contains', t)
02-basics/containers/02-lists.ipynb
vicente-gonzalez-ruiz/YAPT
cc0-1.0
2. [0] Lists A list is a data (usually dynamic) structure that holds a collection of objects, which can have different types. Internally, a list is represented as an array, therefore, lists are fast for appending and for set/pop/getting an item, and slow for removing an internal item.
help([])
02-basics/containers/02-lists.ipynb
vicente-gonzalez-ruiz/YAPT
cc0-1.0
2.1 [1] (Of course) lists are objects
print(type([])); !python -m timeit "x = [1, 'a', 'b', 'a']" # List creation is more expensive than tuple creation
02-basics/containers/02-lists.ipynb
vicente-gonzalez-ruiz/YAPT
cc0-1.0
(Tuples are about three times faster)
a = [] # Empty list definition
02-basics/containers/02-lists.ipynb
vicente-gonzalez-ruiz/YAPT
cc0-1.0
2.2 [0] Appending items to a list (O(1))
a.append('Hello') a.append('world!') a
02-basics/containers/02-lists.ipynb
vicente-gonzalez-ruiz/YAPT
cc0-1.0
Python lists can be "promiscuous":
a.append(100) a
02-basics/containers/02-lists.ipynb
vicente-gonzalez-ruiz/YAPT
cc0-1.0
2.3 [0] Inserting items (O(n))
a.insert(1,'wave!') a
02-basics/containers/02-lists.ipynb
vicente-gonzalez-ruiz/YAPT
cc0-1.0
2.4 [0] Deleting items from a list by content (O(n)))
a.remove('Hello') a b = ['a', 'b', 'a']; b.remove('a'); print(b)
02-basics/containers/02-lists.ipynb
vicente-gonzalez-ruiz/YAPT
cc0-1.0
2.4 [0] Deleting items from the begin of the list (O(1)))
a.pop(0)
02-basics/containers/02-lists.ipynb
vicente-gonzalez-ruiz/YAPT
cc0-1.0
2.4 [0] Deleting items from the end of the list (O(1)))
print(a) a.pop(len(a)-1) # By index, equivalent to "del a[0]" print(a)
02-basics/containers/02-lists.ipynb
vicente-gonzalez-ruiz/YAPT
cc0-1.0
2.5 [0] Sorting the elements of a list (O(n log n))
a = [] a.append('c') a.append('b') a.append('a') a a.sort() a a.reverse() a # Indexing print(a[1]) # Second element print(a[-1]) # Last element print(a[100]) # Error a+a a*3 a[::-1] x = [1,2,3,2,1] # Palindrome? x[::-1] == x
02-basics/containers/02-lists.ipynb
vicente-gonzalez-ruiz/YAPT
cc0-1.0
2.6 [1] Erasing all list items (O(1))
a.clear() a
02-basics/containers/02-lists.ipynb
vicente-gonzalez-ruiz/YAPT
cc0-1.0
2.7 [0] List slicing (O(s))
a.append('Hello') print(a, a[0]) a.append(1) a.append(('a',2)) a.append('world!') a print(a[1:1], a[1:2], a[1:3], a[1:], a[:], a[1:3:2])
02-basics/containers/02-lists.ipynb
vicente-gonzalez-ruiz/YAPT
cc0-1.0
2.8 [1] Defining lists with list comprehensions:
[x**2 for x in range(10)] # http://stackoverflow.com/questions/31045518/finding-prime-numbers-using-list-comprehention [x for x in range(2, 2000) if all(x % y != 0 for y in range(2, int(x ** 0.5) + 1))] l = [[x+y for x in range(10)] for y in range(10)] l l[1][2] 10 in l 10 in l[1] # Lists of lists x = [[1,2],[2,3...
02-basics/containers/02-lists.ipynb
vicente-gonzalez-ruiz/YAPT
cc0-1.0
2.9 [1] Lists are mutable objects Lists can be modified "in-place".
l = [2,3] id(l) l[1] = 4 l id(l)
02-basics/containers/02-lists.ipynb
vicente-gonzalez-ruiz/YAPT
cc0-1.0
3. [0] Sets Sets are implemented as hash table of (unordered) objects, therefore sets are good for get/set/delete/searching items and bad for . Sets do not support indexing, slicing, or other sequence-like behavior.
a = {1, 2, 'a', (1, 2)} a print(type(a)) help(a)
02-basics/containers/02-lists.ipynb
vicente-gonzalez-ruiz/YAPT
cc0-1.0
3.2. [0] Sets can grow (O(1))
a.add('a') print(a)
02-basics/containers/02-lists.ipynb
vicente-gonzalez-ruiz/YAPT
cc0-1.0
3.3. [0] Sets can not contain dupplicate objects
a.add('a') print(a)
02-basics/containers/02-lists.ipynb
vicente-gonzalez-ruiz/YAPT
cc0-1.0
3.4. [1] Sets can not contain mutable objects Mutable objects can not be hashed :-(
a = set() a.add([1,2]) # Sets can not contain lists a = set() # Empty set a.add({1,2,3}) # Sets can not contain sets
02-basics/containers/02-lists.ipynb
vicente-gonzalez-ruiz/YAPT
cc0-1.0
3.5 [0] Intersection of sets (O(min(len(s), len(t)))
a = {1,2,3} b = {2,3,4} a.intersection(b)
02-basics/containers/02-lists.ipynb
vicente-gonzalez-ruiz/YAPT
cc0-1.0