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
同时赋值var1, var2,var3... = exp1,exp2,exp3...
Joekr, Mistt,hahah,lalal = 'lalal',120,120.33333,True print(Joekr,Mistt,hahah,lalal)
lalal 120 120.33333 True
Apache-2.0
7.16.ipynb
hzh029/hzh1
定义常量- 常量:表示一种定值标识符,适合于多次使用的场景。比如PI- 注意:在其他低级语言中如果定义了常量,那么,该常量是不可以被改变的,但是在Python中一切皆对象,常量也是可以被改变的
chart = 100.1 chart = 'hahahah' chart = True print(chart) import math print(math.pi)
3.141592653589793
Apache-2.0
7.16.ipynb
hzh029/hzh1
数值数据类型和运算符- 在Python中有两种数值类型(int 和 float)适用于加减乘除、模、幂次 运算符 /、//、**
number1 = 100 number2 = 500 print(number1 + number2) number3 = 100.0 number4 = 500.0 print(number3 + number4) number3 = 100.0 number4 = 500.0 print(number3 - number4) number3 = 100.0 number4 = 500.0 print(number3 * number4) number3 = 100.0 number4 = 500.0 print(number3 / number4) number3 = 100.0 number4 = 500.0 print(n...
10000.0
Apache-2.0
7.16.ipynb
hzh029/hzh1
运算符 %
number3 = 100.0 number4 = 500.0 print(number3 % number4)
100.0
Apache-2.0
7.16.ipynb
hzh029/hzh1
EP:- 25/4 多少,如果要将其转变为整数该怎么改写- 输入一个数字判断是奇数还是偶数- 进阶: 输入一个秒数,写一个程序将其转换成分和秒:例如500秒等于8分20秒- 进阶: 如果今天是星期六,那么10天以后是星期几? 提示:每个星期的第0天是星期天
res = 25//4 print(res) input_number = input('input number') input_number_int = eval(input_number) if input_number_int == int: if input_number_int % 2 == 0: print('偶数') else: print('奇数') else: if input_number_int % 2.0 == 0.0: print('偶数') else: print('奇数') time = eval(inpu...
输入10 2
Apache-2.0
7.16.ipynb
hzh029/hzh1
科学计数法- 1.234e+2- 1.234e-2
num1=1.234e+2 num2 = 1.234e-2 print(num1,num2)
123.4 0.01234
Apache-2.0
7.16.ipynb
hzh029/hzh1
计算表达式和运算优先级
x = eval(input('x')) y = eval(input('y')) a = eval(input('a')) b = eval(input('b')) c = eval(input('c')) part_1 = (3 + 4 * x) / 5 part_2 = (10 * (y-5)* (a+b+c))/ x part_3 = 9*(4/x + (9+x)/y) print(part_1 - part_2 + part_3)
_____no_output_____
Apache-2.0
7.16.ipynb
hzh029/hzh1
增强型赋值运算
a = 1 a += 100 # a = a + 100 print(a)
101
Apache-2.0
7.16.ipynb
hzh029/hzh1
类型转换- float -> int- 四舍五入 round
int(25 / 4) # 转换成整型 str(25 / 4) # 转换成字符串 float(25//5) # 转换成浮点 round(25/4,1) # 四舍五入
_____no_output_____
Apache-2.0
7.16.ipynb
hzh029/hzh1
EP:- 如果一个年营业税为0.06%,那么对于197.55e+2的年收入,需要交税为多少?(结果保留2为小数)- 必须使用科学计数法
water_floawer = 153 bai = 153 //100 shi = 153 //10 % 10 ge = 153 % 10 if water_floawer == bai ** 3 + shi **3 + ge **3: print('是水仙花') else: print('NO') round(197.55e+2 * 0.06e-2,2)
_____no_output_____
Apache-2.0
7.16.ipynb
hzh029/hzh1
Project- 用Python写一个贷款计算器程序:输入的是月供(monthlyPayment) 输出的是总还款数(totalpayment)![](../Photo/05.png)
贷款数 = eval(input('请输入贷款数')) 月利率 = eval(input('月利率')) 年限 = eval(input('年限')) 月供= ( (贷款数 * 月利率) / (1-(1/(1+月利率)**(年限*12)))) 总还款数 = 月供 * 年限 * 12 print(总还款数) import time print(time.time())
1531727407.061894
Apache-2.0
7.16.ipynb
hzh029/hzh1
Homework- 1
celsius=eval(input("请输入摄氏温度")) fahrenheit=(9/5)*celsius+32 print(fahrenheit)
请输入摄氏温度43 109.4
Apache-2.0
7.16.ipynb
hzh029/hzh1
- 2
pi=3.14 radius=eval(input("请输入半径")) length=eval(input("请输入高")) area=radius*radius*pi volume=area*length print(area) print(volume)
请输入半径5.5 请输入高12 94.985 1139.82
Apache-2.0
7.16.ipynb
hzh029/hzh1
- 3
yingchi=eval(input("请输入英尺数")) michi=yingchi*0.305 print(michi)
请输入英尺数16.5 5.0325
Apache-2.0
7.16.ipynb
hzh029/hzh1
- 4
water_amount=eval(input("请输入水量")) temperature_ini=eval(input("请输入初始温度")) temperature_fin=eval(input("请输入最终温度")) Q=water_amount*(temperature_fin-temperature_ini)*4184 print(Q)
请输入水量55.5 请输入初始温度3.5 请输入最终温度10.5 1625484.0
Apache-2.0
7.16.ipynb
hzh029/hzh1
- 5
差额=eval(input("请输入差额")) 年利率=eval(input("请输入年利率")) 利息=差额*(年利率/1200) print(利息)
请输入差额1000 请输入年利率3.5 2.916666666666667
Apache-2.0
7.16.ipynb
hzh029/hzh1
- 6
v0=eval(input("v0")) v1=eval(input("v1")) t=eval(input("t")) a=(v1-v0)/t print(a)
v05.5 v150.9 t4.5 10.088888888888889
Apache-2.0
7.16.ipynb
hzh029/hzh1
- 7 进阶
月存额=eval(input("月存额")) 第一个月=月存额*(1+0.05/12) print("第一个月后,账户里的数目变为:",第一个月) 第二个月=(月存额+第一个月)*(1+0.05/12) print("第二个月后,账户里的数目变为:",第二个月)
月存额100 第一个月后,账户里的数目变为: 100.41666666666667 第二个月后,账户里的数目变为: 201.25173611111111
Apache-2.0
7.16.ipynb
hzh029/hzh1
From padding to subdivision As evoked in the 1st notebook, in previous experiments, every bar of the tensor was zero-padded if it was shorter than the longest bar of the song.This fix is not satisfactory, as it creates null artifacts at the end of most of the slices of the tensor. Description of the subdivision metho...
# On définit le type d'annotations annotations_type = "MIREX10" ranks_rhythm = [16,24,32,40] ranks_pattern = [16,24,32,40]
_____no_output_____
BSD-3-Clause
Notebooks/Notebooks ISMIR 2020/3 - Subdivisions of bars.ipynb
ax-le/MusicNTD
Subdivision 96 Fixed ranksBelow are segmentation results with the subdivision fixed to 96, for the different ranks values, on the RWC Pop dataset.Results are computed with tolerance of respectively 0.5 seconds and 3 seconds.
zero_five_nine, three_nine = hide.compute_ranks_RWC(ranks_rhythm,ranks_pattern, W = "chromas", annotations_type = annotations_type, subdivision=96, penalty_weight = 1)
c:\users\amarmore\desktop\projects\phd main projects\on git\code\tensor factorization\musicntd\autosimilarity_segmentation.py:43: RuntimeWarning: invalid value encountered in true_divide this_array = np.array([list(i/np.linalg.norm(i)) for i in this_array.T]).T
BSD-3-Clause
Notebooks/Notebooks ISMIR 2020/3 - Subdivisions of bars.ipynb
ax-le/MusicNTD
Oracle ranksIn this condition, we only keep the ranks leading to the highest F measure.In that sense, it's an optimistic upper bound on metrics.
hide.printmd("**A 0.5 secondes:**") best_chr_zero_five = hide.best_f_one_score_rank(zero_five_nine) hide.printmd("**A 3 secondes:**") best_chr_three = hide.best_f_one_score_rank(three_nine)
_____no_output_____
BSD-3-Clause
Notebooks/Notebooks ISMIR 2020/3 - Subdivisions of bars.ipynb
ax-le/MusicNTD
Below is presented the distribution of the optimal ranks in the "oracle ranks" condition, _i.e._ the distribution of the ranks for $H$ and $Q$ which result in the highest F measure for the different songs.
hide.plot_3d_ranks_study(zero_five_nine, ranks_rhythm, ranks_pattern)
_____no_output_____
BSD-3-Clause
Notebooks/Notebooks ISMIR 2020/3 - Subdivisions of bars.ipynb
ax-le/MusicNTD
Below is shown the distribution histogram of the F measure obtained with the oracle ranks.
hide.plot_f_mes_histogram(zero_five_nine)
_____no_output_____
BSD-3-Clause
Notebooks/Notebooks ISMIR 2020/3 - Subdivisions of bars.ipynb
ax-le/MusicNTD
Finally, here are displayed the 5 worst songs in term of F measure in this condition.
hide.return_worst_songs(zero_five_nine, 5)
_____no_output_____
BSD-3-Clause
Notebooks/Notebooks ISMIR 2020/3 - Subdivisions of bars.ipynb
ax-le/MusicNTD
Subdivision 128 Fixed ranksBelow are segmentation results with the subdivision fixed to 128, for the different ranks values, on the RWC Pop dataset.Results are computed with tolerance of respectively 0.5 seconds and 3 seconds.
zero_five_cent, three_cent = hide.compute_ranks_RWC(ranks_rhythm,ranks_pattern, W = "chromas", annotations_type = annotations_type, subdivision=128, penalty_weight = 1)
c:\users\amarmore\desktop\projects\phd main projects\on git\code\tensor factorization\musicntd\autosimilarity_segmentation.py:43: RuntimeWarning: invalid value encountered in true_divide this_array = np.array([list(i/np.linalg.norm(i)) for i in this_array.T]).T
BSD-3-Clause
Notebooks/Notebooks ISMIR 2020/3 - Subdivisions of bars.ipynb
ax-le/MusicNTD
Oracle ranksIn this condition, we only keep the ranks leading to the highest F measure.In that sense, it's an optimistic upper bound.
hide.printmd("**A 0.5 secondes:**") best_chr_zero_five = hide.best_f_one_score_rank(zero_five_cent) hide.printmd("**A 3 secondes:**") best_chr_three = hide.best_f_one_score_rank(three_cent)
_____no_output_____
BSD-3-Clause
Notebooks/Notebooks ISMIR 2020/3 - Subdivisions of bars.ipynb
ax-le/MusicNTD
Below is presented the distribution of the optimal ranks in the "oracle ranks" condition, _i.e._ the distribution of the ranks for $H$ and $Q$ which result in the highest F measure for the different songs.
hide.plot_3d_ranks_study(zero_five_cent, ranks_rhythm, ranks_pattern)
_____no_output_____
BSD-3-Clause
Notebooks/Notebooks ISMIR 2020/3 - Subdivisions of bars.ipynb
ax-le/MusicNTD
Below is shown the distribution histogram of the F measure obtained with the oracle ranks.
hide.plot_f_mes_histogram(zero_five_cent)
_____no_output_____
BSD-3-Clause
Notebooks/Notebooks ISMIR 2020/3 - Subdivisions of bars.ipynb
ax-le/MusicNTD
Finally, here are displayed the 5 worst songs in term of F measure in this condition.
hide.return_worst_songs(zero_five_cent, 5)
_____no_output_____
BSD-3-Clause
Notebooks/Notebooks ISMIR 2020/3 - Subdivisions of bars.ipynb
ax-le/MusicNTD
Subdivision 192 Fixed ranksBelow are segmentation results with the subdivision fixed to 192, for the different ranks values, on the RWC Pop dataset.Results are computed with tolerance of respectively 0.5 seconds and 3 seconds.
zero_five_hunnine, three_hunnine = hide.compute_ranks_RWC(ranks_rhythm,ranks_pattern, W = "chromas", annotations_type = annotations_type, subdivision=192, penalty_weight = 1)
c:\users\amarmore\desktop\projects\phd main projects\on git\code\tensor factorization\musicntd\autosimilarity_segmentation.py:43: RuntimeWarning: invalid value encountered in true_divide this_array = np.array([list(i/np.linalg.norm(i)) for i in this_array.T]).T
BSD-3-Clause
Notebooks/Notebooks ISMIR 2020/3 - Subdivisions of bars.ipynb
ax-le/MusicNTD
Oracle ranksIn this condition, we only keep the ranks leading to the highest F measure.In that sense, it's an optimistic upper bound.
hide.printmd("**A 0.5 secondes:**") best_chr_zero_five = hide.best_f_one_score_rank(zero_five_hunnine) hide.printmd("**A 3 secondes:**") best_chr_three = hide.best_f_one_score_rank(three_hunnine)
_____no_output_____
BSD-3-Clause
Notebooks/Notebooks ISMIR 2020/3 - Subdivisions of bars.ipynb
ax-le/MusicNTD
Below is presented the distribution of the optimal ranks in the "oracle ranks" condition, _i.e._ the distribution of the ranks for $H$ and $Q$ which result in the highest F measure for the different songs.
hide.plot_3d_ranks_study(zero_five_hunnine, ranks_rhythm, ranks_pattern)
_____no_output_____
BSD-3-Clause
Notebooks/Notebooks ISMIR 2020/3 - Subdivisions of bars.ipynb
ax-le/MusicNTD
Below is shown the distribution histogram of the F measure obtained with the oracle ranks.
hide.plot_f_mes_histogram(zero_five_hunnine)
_____no_output_____
BSD-3-Clause
Notebooks/Notebooks ISMIR 2020/3 - Subdivisions of bars.ipynb
ax-le/MusicNTD
Finally, here are displayed the 5 worst songs in term of F measure in this condition.
hide.return_worst_songs(zero_five_hunnine, 5)
_____no_output_____
BSD-3-Clause
Notebooks/Notebooks ISMIR 2020/3 - Subdivisions of bars.ipynb
ax-le/MusicNTD
Numba implementation of Random Walk (2D) in 8 directions [Adapted from: geeksforgeeks](https://www.geeksforgeeks.org/random-walk-implementation-python/)
@jit(nopython=True) def random_walk_2d_n8(nwalks): # Arrays to store x, y coordinates x = np.zeros(nwalks) y = np.zeros(nwalks) # 8 directions n8 = [(-1,-1), (-1,0), (-1,1), (0,-1), (0,1), (1,-1), (1,0), (1,1)] for n in range(nwalks): idx = np.random.choice(len(n8), 1)[0] x[...
_____no_output_____
CC-BY-4.0
Numba/02_random_walk.ipynb
enricocid/python_gis
inference in simple model using synthetic datapopulation size 10^6, inference window 2x4 = 8 days, to be compared with ``-win5`` analogous notebook
%env OMP_NUM_THREADS=1 %matplotlib inline import numpy as np import os import pickle import pprint import time import pyross import matplotlib.pyplot as plt import matplotlib.image as mpimg #from matplotlib import rc; rc('text', usetex=True) import synth_fns
_____no_output_____
MIT
SimpleTestModel/synthInfTest-pop1e6-win2.ipynb
rljack2002/infExampleCovidEW
(cell 3 was removed to hide local file info) main settings
## for dataFiles : needs a fresh value in every notebook fileRoot = 'dataSynthInfTest-pop1e6-win2' ## total population popN = 1e6 ## tau-leaping param, take this negative to force gillespie ## or set a small value for high-accuracy tau-leap (eg 1e-4 or 1e-5) leapEps = -1 ## do we use small tolerances for the likelih...
_____no_output_____
MIT
SimpleTestModel/synthInfTest-pop1e6-win2.ipynb
rljack2002/infExampleCovidEW
model
model_dict = synth_fns.get_model(popN) model_spec = model_dict['mod'] contactMatrix = model_dict['CM'] parameters_true = model_dict['params'] cohortsM = model_dict['cohortsM'] Ni = model_dict['cohortsPop']
_____no_output_____
MIT
SimpleTestModel/synthInfTest-pop1e6-win2.ipynb
rljack2002/infExampleCovidEW
more settings
## total trajectory time (bare units) Tf_bare = 20 ## total inf time Tf_inf_bare = 2 ## inference period starts when the total deaths reach this amount (as a fraction) fracDeaths = 2e-3 # int(N*200/1e5) ## hack to get higher-frequency data ## how many data points per "timestep" (in original units) fineData = 4 ## th...
_____no_output_____
MIT
SimpleTestModel/synthInfTest-pop1e6-win2.ipynb
rljack2002/infExampleCovidEW
plotting helper functions
def plotTraj(M,data_array,Nf_start,Tf_inference,fineData): fig = plt.figure(num=None, figsize=(6, 4), dpi=80, facecolor='w', edgecolor='k') #plt.rc('text', usetex=True) plt.rc('font', family='serif', size=12) t = np.linspace(0, Tf/fineData, Nf) # plt.plot(t, np.sum(data_array[:, :M], axis=1), '-o',...
_____no_output_____
MIT
SimpleTestModel/synthInfTest-pop1e6-win2.ipynb
rljack2002/infExampleCovidEW
synthetic data
if loadTraj : ipFile = fileRoot+'-stochTraj.npy' syntheticData = np.load(ipFile) print('loading trajectory from',ipFile) else : ticTime = time.time() syntheticData = synth_fns.make_stochastic_traj(Tf,Nf,trajSeed,model_dict,leapEps) tocTime = time.time() - ticTime print('traj generation time'...
_____no_output_____
MIT
SimpleTestModel/synthInfTest-pop1e6-win2.ipynb
rljack2002/infExampleCovidEW
basic inference (estimator) setup(including computation of likelihood for the true parameters)
[estimator,fltrDeath,obsData,trueInit] = synth_fns.get_estimator(isHighAccuracy,model_dict,syntheticData, popN, Nf_start, Nf_inference,) ## compute log-likelihood of true params logpTrue = -estimator.minus_logp_red(parameters_true, trueInit, obsData, fltrDeath, Tf_inference, conta...
setting high-accuracy for likelihood **logLikTrue -40.72311526408154 death data [[2365.] [2767.] [3313.] [3839.] [4438.] [5060.] [5722.] [6501.] [7253.]] length 9 9
MIT
SimpleTestModel/synthInfTest-pop1e6-win2.ipynb
rljack2002/infExampleCovidEW
priors
[param_priors,init_priors] = synth_fns.get_priors(model_dict,betaPriorOffset,betaPriorLogNorm,fracDeaths,estimator) print('Prior Params:',param_priors) print('Prior Inits:') pprint.pprint(init_priors) print('trueBeta',parameters_true['beta']) print('trueInit',trueInit)
Prior Params: {'beta': {'mean': 0.028000000000000004, 'std': 0.014000000000000002, 'bounds': [0.0001, 0.14], 'prior_fun': 'truncnorm'}} Prior Inits: {'independent': {'bounds': [[72000.0, 1000000.0], [10100.251257867601, 1010025.12578676], [7899.748742132397, 78997...
MIT
SimpleTestModel/synthInfTest-pop1e6-win2.ipynb
rljack2002/infExampleCovidEW
inference (MAP)
infResult = synth_fns.do_inf(estimator, obsData, fltrDeath, syntheticData, popN, Tf_inference, infSeed, param_priors,init_priors, model_dict, inf_atol) #pprint.pprint(infResult) print('MAP likelihood',infResult['log_likelihood'],'true',logpTrue) print('MAP beta',infResult['params_dict']['b...
MAP likelihood -40.347160920804455 true -40.72311526408154 MAP beta 0.03188011492363837 true 0.035
MIT
SimpleTestModel/synthInfTest-pop1e6-win2.ipynb
rljack2002/infExampleCovidEW
plot MAP trajectory
plotMAP(infResult,syntheticData,cohortsM,popN,estimator,Nf_start,Tf_inference,fineData)
**beta(bare units) 0.12752045969455347 **logLik -40.347160920804455 true was -40.72311526408154 {'params_dict': {'beta': 0.03188011492363837, 'gE': 0.35000000000000003, 'gR': 0.245, 'gD': 0.005, 'seed': 18}, 'x0': array([725209.60575166, 101859.7992907 , 76606.06026326, 2365. ]), 'flat_params': array([3.188...
MIT
SimpleTestModel/synthInfTest-pop1e6-win2.ipynb
rljack2002/infExampleCovidEW
slice of likelihood (note this is not the posterior, hence MAP is not exactly at the peak)
## range for beta (relative to MAP) rangeParam = 0.1 [bVals,likVals] = synth_fns.sliceLikelihood(rangeParam,infResult, estimator,obsData,fltrDeath,contactMatrix,Tf_inference) #print('logLiks',likVals,logp) plt.plot(bVals , likVals, 'o-') plt.plot(infResult['params_dict']['be...
_____no_output_____
MIT
SimpleTestModel/synthInfTest-pop1e6-win2.ipynb
rljack2002/infExampleCovidEW
MCMC
sampler = synth_fns.do_mcmc(mcSamples, nProcMCMC, estimator, Tf_inference, infResult, obsData, fltrDeath, param_priors, init_priors, model_dict,infSeed) plotMCtrace([0,2,3], sampler) result_mcmc = synth_fns.load_mcmc_result(estimator, obsData, fltrDeath, sampler...
_____no_output_____
MIT
SimpleTestModel/synthInfTest-pop1e6-win2.ipynb
rljack2002/infExampleCovidEW
save the result
if saveMC : opFile = fileRoot + "-mcmc.pik" print('opf',opFile) with open(opFile, 'wb') as f: pickle.dump([infResult,result_mcmc],f)
opf dataSynthInfTest-pop1e6-win2-mcmc.pik
MIT
SimpleTestModel/synthInfTest-pop1e6-win2.ipynb
rljack2002/infExampleCovidEW
estimate MCMC autocorrelation
# these are the estimated autocorrelation times for the sampler # (it likes runs ~50 times longer than this...) pp = sampler.get_log_prob() nSampleTot = np.shape(pp)[0] #print('correl',sampler.get_autocorr_time(discard=int(nSampleTot/3))) print('nSampleTot',nSampleTot)
nSampleTot 5000
MIT
SimpleTestModel/synthInfTest-pop1e6-win2.ipynb
rljack2002/infExampleCovidEW
plot posterior distributions
plotPosteriors(estimator,obsData, fltrDeath, Tf_inference,param_priors, init_priors,contactMatrix, infResult,parameters_true,trueInit)
_____no_output_____
MIT
SimpleTestModel/synthInfTest-pop1e6-win2.ipynb
rljack2002/infExampleCovidEW
analyse posterior for beta
betas = [ rr['params_dict']['beta'] for rr in result_mcmc ] postMeanBeta = np.mean(betas) postStdBeta = np.std(betas) postCIBeta = [ np.percentile(betas,2.5) , np.percentile(betas,97.5)] print("beta: true {b:.5f} MAP {m:.5f}".format(b=parameters_true['beta'],m=infResult['params_dict']['beta'])) print("post: mean {m:.5...
beta: true 0.03500 MAP 0.03188 post: mean 0.03242 std 0.00305 CI95: 0.02698 0.03879
MIT
SimpleTestModel/synthInfTest-pop1e6-win2.ipynb
rljack2002/infExampleCovidEW
posterior correlations for initial conditions
sis = np.array( [ rr['x0'][0] for rr in result_mcmc ] )/popN eis = np.array( [ rr['x0'][1] for rr in result_mcmc ] )/popN iis = np.array( [ rr['x0'][2] for rr in result_mcmc ] )/popN betas = [ rr['params_dict']['beta'] for rr in result_mcmc ] fig,axs = plt.subplots(1,3,figsize=(15,4)) plt.subplots_adjust(wspace=0.35) ...
528
MIT
SimpleTestModel/synthInfTest-pop1e6-win2.ipynb
rljack2002/infExampleCovidEW
Table of Contents* [Challenge Problems](Challenge-Problems) * [1. Spinodal Decomposition - Cahn-Hilliard](1.-Spinodal-Decomposition---Cahn-Hilliard) * [Parameter Values](Parameter-Values) * [Initial Conditions](Initial-Conditions) * [Domains](Domains) * [a. Square Periodic](a.-Square-Periodic) * [b. No Flux](b....
from IPython.display import SVG SVG(filename='../images/block1.svg')
_____no_output_____
MIT
hackathon1/problems.ipynb
dschwen/chimad-phase-field
b. No Flux 2D square domain with $L_x = L_y = 200$ and zero flux boundary conditions. c. T-Shape No Flux T-shaped reiong with zero flux boundary conditions with $a=b=100$ and $c=d=20.$
from IPython.display import SVG SVG(filename='../images/t-shape.svg')
_____no_output_____
MIT
hackathon1/problems.ipynb
dschwen/chimad-phase-field
d. Sphere Domain is the surface of a sphere with radius 100, but with initial conditions of$$ c\left(\theta, \phi, 0\right) = \bar{c}_0 + \epsilon \cos \left( \sqrt{233} \theta \right) \sin \left( \sqrt{239} \phi \right) $$where $\theta$ and $\phi$ are the polar a...
from IPython.display import SVG SVG(filename='../images/block1.svg')
_____no_output_____
MIT
hackathon1/problems.ipynb
dschwen/chimad-phase-field
b. No Flux 2D square domain with $L_x = L_y = 200$ and zero flux boundary conditions. c. T-Shape No Flux T-shaped reiong with zero flux boundary conditions with $a=b=100$ and $c=d=20.$
from IPython.display import SVG SVG(filename='../images/t-shape.svg')
_____no_output_____
MIT
hackathon1/problems.ipynb
dschwen/chimad-phase-field
First Last - Homework 4 * Use the `Astropy` units and constants packages to solve the following problems.* Do not hardcode any constants!* Unless asked, your units should be in the simplest SI units possible
import numpy as np from astropy import units as u from astropy import constants as const from astropy.units import imperial imperial.enable()
_____no_output_____
MIT
FirstLast_HW4.ipynb
UWashington-Astro300/Astro300-W17
Swish-based classifier with data augmentation and stochastic weght-averaging- Swish activation, 4 layers, 100 neurons per layer- Data is augmentaed via phi rotations, and transvers and longitudinal flips- Model uses a running average of previous weights- Validation score use ensemble of 10 models weighted by loss Imp...
%matplotlib inline from __future__ import division import sys import os sys.path.append('../') from Modules.Basics import * from Modules.Class_Basics import *
/home/giles/anaconda3/lib/python3.6/site-packages/h5py/__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`. from ._conv import register_converters as _register_converters /home...
MIT
Notebooks/6_Model_SWA_Augmentation.ipynb
GilesStrong/QCHS-2018
Options
with open(dirLoc + 'features.pkl', 'rb') as fin: classTrainFeatures = pickle.load(fin) nSplits = 10 patience = 50 maxEpochs = 200 ensembleSize = 10 ensembleMode = 'loss' compileArgs = {'loss':'binary_crossentropy', 'optimizer':'adam'} trainParams = {'epochs' : 1, 'batch_size' : 256, 'verbose' : 0} modelParams = {...
Training on 31 features: ['DER_mass_MMC', 'DER_mass_transverse_met_lep', 'DER_mass_vis', 'DER_pt_h', 'DER_deltaeta_jet_jet', 'DER_mass_jet_jet', 'DER_prodeta_jet_jet', 'DER_deltar_tau_lep', 'DER_pt_tot', 'DER_sum_pt', 'DER_pt_ratio_lep_tau', 'DER_met_phi_centrality', 'DER_lep_eta_centrality', 'PRI_met_pt', 'PRI_met_su...
MIT
Notebooks/6_Model_SWA_Augmentation.ipynb
GilesStrong/QCHS-2018
Import data
with open(dirLoc + 'inputPipe.pkl', 'rb') as fin: inputPipe = pickle.load(fin) trainData = RotationReflectionBatch(classTrainFeatures, h5py.File(dirLoc + 'train.hdf5', "r+"), inputPipe=inputPipe, augRotMult=16)
_____no_output_____
MIT
Notebooks/6_Model_SWA_Augmentation.ipynb
GilesStrong/QCHS-2018
Determine LR
lrFinder = batchLRFind(trainData, getModel, modelParams, trainParams, lrBounds=[1e-5,1e-1], trainOnWeights=True, verbose=0)
2 classes found, running in binary mode
MIT
Notebooks/6_Model_SWA_Augmentation.ipynb
GilesStrong/QCHS-2018
Train classifier
results, histories = batchTrainClassifier(trainData, nSplits, getModel, {**modelParams, 'compileArgs':{**compileArgs, 'lr':2e-3}}, trainParams, trainOnWeights=True, maxEpochs=maxEpochs, swaStar...
Training using weights Running fold 1 / 10 2 classes found, running in binary mode 1 New best found: 3.8324186580732575e-05 2 New best found: 3.7469157104559623e-05 3 New best found: 3.6876136355998674e-05 4 New best found: 3.543037565955778e-05 6 New best found: 3.5032572314542355e-05 7 New best found: 3.487276302154...
MIT
Notebooks/6_Model_SWA_Augmentation.ipynb
GilesStrong/QCHS-2018
Once SWA is activated at epoch 125, we find that the validation loss goes through a rapid decrease followed by a plateau with large suppression of the statistical fluctuations.Comparing to 5_Model_Data_Augmentation the metrics are mostly the same, except for the AMS which moves from3.98 to 4.04. Construct ensemble
with open('train_weights/resultsFile.pkl', 'rb') as fin: results = pickle.load(fin) ensemble, weights = assembleEnsemble(results, ensembleSize, ensembleMode, compileArgs)
Choosing ensemble by loss Model 0 is 6 with loss = 3.056904335753643e-05 Model 1 is 9 with loss = 3.071672455570552e-05 Model 2 is 3 with loss = 3.120919069624506e-05 Model 3 is 4 with loss = 3.186284687035368e-05 Model 4 is 1 with loss = 3.198194178443449e-05 Model 5 is 0 with loss = 3.1988215248678005e-05 Model 6 is ...
MIT
Notebooks/6_Model_SWA_Augmentation.ipynb
GilesStrong/QCHS-2018
Response on validation data with TTA
valData = RotationReflectionBatch(classTrainFeatures, h5py.File(dirLoc + 'val.hdf5', "r+"), inputPipe=inputPipe, rotate = True, reflect = True, augRotMult=8) batchEnsemblePredict(ensemble, weights, valData, ensembleSize=ensembleSize, verbose=1) print('Testing ROC AUC: unweighted {}, we...
50000 candidates loaded Mean AMS=4.0+-0.2, at mean cut of 0.961+-0.008 Exact mean cut 0.9606163307325915, corresponds to AMS of 3.9670679002860356 CPU times: user 2.58 s, sys: 15.1 s, total: 17.6 s Wall time: 2min 9s
MIT
Notebooks/6_Model_SWA_Augmentation.ipynb
GilesStrong/QCHS-2018
In the validation metrics we also find improvement over 5_Model_Data_Augmentation: overallAMS moves from 3.97 to 3.99, and AMS corresponding to mean cut increases to 3.97 from 3.91. Test scoring
testData = RotationReflectionBatch(classTrainFeatures, h5py.File(dirLoc + 'testing.hdf5', "r+"), inputPipe=inputPipe, rotate = True, reflect = True, augRotMult=8) %%time batchEnsemblePredict(ensemble, weights, testData, ensembleSize=ensembleSize, verbose=1) scoreTestOD(testData.source...
Public:Private AMS: 3.6798281799107344 : 3.7847099714589465
MIT
Notebooks/6_Model_SWA_Augmentation.ipynb
GilesStrong/QCHS-2018
Unfortunately, applying the cut to the test data shows an improvement in the public score (3.65->3.68) but a large decrease in private score (3.82->3.79) Save/Load
name = "weights/Swish_SWA-125" saveEnsemble(name, ensemble, weights, compileArgs, overwrite=1) ensemble, weights, compileArgs, _, _ = loadEnsemble(name)
_____no_output_____
MIT
Notebooks/6_Model_SWA_Augmentation.ipynb
GilesStrong/QCHS-2018
탐구실험용 toy 코드 (Facebook 바비 Question-Answer)   +++++++++++++++++++++++++++++++++++++++++++++ toy 코드의 한계 및 약점은 ? 약점을 보강할 수 있는 방법 ? 영어와 한글 데이터의 부족을 한영 번역기로 try 하며 탐구   +++++++++++++++++++++++++++++++++++++++++++++++++++   toy 코드를 통해 약점을 알아내고, 데이터를 조작하며 (좋은 뜻으로 조절), 데이터가 어떻게 변형되고, 행렬의 weig...
# babi 데이터 Sandra travelled to the kitchen. Sandra travelled to the hallway. Mary went to the bathroom. Sandra moved to the garden. Where is Sandra ? Ground Truth: Garden (based on single supporting fact 4) ### Each sentence is provided with an ID. The IDs for a given “story” start at 1 ...
_____no_output_____
MIT
TF-Keras_CHATBOT/0.Keras-Babi_MathQA.ipynb
ds3mbc-snu/ds3mbc-snu.github.io
바비 데이터 github : https://github.com/andri27-ts/bAbI 수학교육 탐구과제로 도전가능한 문제 QA6 - Yes/No Questions QA7 - Counting 바비 데이터 : https://github.com/harvardnlp/MemN2N/tree/master/babi_data/en   settings ==> .keras ==> dataset 안에 데이터 저장됨 https://appliedmachinelearning.blog/2019/05/01/developing-factoid-que...
#Library Imports import pickle import numpy as np import pandas as pd
_____no_output_____
MIT
TF-Keras_CHATBOT/0.Keras-Babi_MathQA.ipynb
ds3mbc-snu/ds3mbc-snu.github.io
pickle 데이터 파일과 csv 데이터 파일 교재 80페이지의 pandas, numpy 를 익힌다.
#retrieve training data # IOPub data rate exceeded. # jupyter notebook --NotebookApp.iopub_data_rate_limit=10000000000 unpickled_df = pd.read_pickle('./data_in/babi_train_qa.txt') # print( unpickled_df)== list 이다 df = pd.DataFrame( unpickled_df ) # df = pd.DataFrame(some_list, columns=["colummn"]) df.to_csv...
['Mary', 'got', 'the', 'milk', 'there', '.', 'John', 'moved', 'to', 'the', 'bedroom', '.'] ['Is', 'John', 'in', 'the', 'kitchen', '?'] no ['Mary', 'got', 'the', 'milk', 'there', '.', 'John', 'moved', 'to', 'the', 'bedroom', '.', 'Mary', 'discarded', 'the', 'milk', '.', 'John', 'went', 'to', 'the', 'garden', '.', 'Danie...
MIT
TF-Keras_CHATBOT/0.Keras-Babi_MathQA.ipynb
ds3mbc-snu/ds3mbc-snu.github.io
[문제] 아래 QA6 text 파일과 비교하여보라 ./data_in/babi_qa6_train.txt ./data_in/babi_qa6_test.txt
with open('./data_in/babi_train_qa.txt', 'rb') as f: train_data = pickle.load(f) print( train_data[10] ) train_data[0][0:3] #retrieve test data with open('./data_in/babi_test_qa.txt', 'rb') as f: test_data = pickle.load(f) #Number of training instances len(train_data) #Number of test instances len(test_data)...
_____no_output_____
MIT
TF-Keras_CHATBOT/0.Keras-Babi_MathQA.ipynb
ds3mbc-snu/ds3mbc-snu.github.io
++++++++++++++++++++++++++++++++++++   [과제] 한글 챗복 데이터 다루기   ++++++++++++++++++++++++++++++++++++ [과제 1] data_nmt/conversaiton2.txt 데이터 다루기
import pandas as pd file = open( "./data_nmt/conversation2.txt", "r" , encoding="utf-8") data = file.readlines() df1 = [] for ii in data: df1.append(ii[:-1]) df2 = pd.DataFrame( df1 ) df2.to_csv( './data_nmt/conversation2.csv' , index=False, encoding='utf-8') datacsv = pd.read_csv( './data_nmt/conversation2...
['칠까', '스트레스', '전부터', '의', '지갑', '바쿠', '언제', '레스', '야', '모르는']
MIT
TF-Keras_CHATBOT/0.Keras-Babi_MathQA.ipynb
ds3mbc-snu/ds3mbc-snu.github.io
++++++++++++++++++++++++++++++++++++ [과제 2] data_in/ChatBotData.csv 데이터 다루기
import pandas as pd data = pd.read_csv( './data_in/ChatBotData.csv' , encoding='utf-8') print( data.head() ) questions, answers = list( data['Q'] ) , list( data['A'] ) from konlpy.tag import Okt # Twitter from tqdm import tqdm morph_analyzer = Okt() # Twitter() # 형태소 토크나이즈 결과 문장을 받을 # 리스트를 생성합니다. resul...
111808 15680 단어장이 새로 만들어짐 !!
MIT
TF-Keras_CHATBOT/0.Keras-Babi_MathQA.ipynb
ds3mbc-snu/ds3mbc-snu.github.io
++++++++++++++++++++++++++++++++++++ [문제] 한글 단어장을 만드는 과정을 이해하자 !! ++++++++++++++++++++++++++++++++++++   챗봇 데이터의 단어장으로 문장을 벡터로 표현 !!   ++++++++++++++++++++++++++++++++++++ 교재 30페이지의 내용과 비교한다
set1=[1,2,3,4,5, 1,2,3,9] set2=[2,3,5,6,7, 2,3,4,8] set1 = set(set1) moim = set() moim = moim.union( set1) moim = moim.intersection( set(set2)) print( moim )
{2, 3, 4, 5}
MIT
TF-Keras_CHATBOT/0.Keras-Babi_MathQA.ipynb
ds3mbc-snu/ds3mbc-snu.github.io
./data_in/babi_train_qa.txt 데이터
import pickle with open('./data_in/babi_train_qa.txt', 'rb') as f: train_data = pickle.load(f) print( train_data[10] ) train_data[0][0:3] #First we will build a set of all the words in the dataset: vocab = set() for story, question, answer in train_data: vocab = vocab.union(set(story)) #Set returns unique ...
_____no_output_____
MIT
TF-Keras_CHATBOT/0.Keras-Babi_MathQA.ipynb
ds3mbc-snu/ds3mbc-snu.github.io
이제 Babi 데이터의 문장을 벡터로 만들자 First, we will go through a manual process of how to vectorize the data, and then we will create a function that does this automatically for us.
import keras print( keras.__version__ ) from keras.preprocessing.sequence import pad_sequences from keras.preprocessing.text import Tokenizer #Create an instance of the tokenizer object: tokenizer = Tokenizer(filters = []) tokenizer.fit_on_texts(vocab) #Dictionary that maps every word in our vocab to an index # ...
_____no_output_____
MIT
TF-Keras_CHATBOT/0.Keras-Babi_MathQA.ipynb
ds3mbc-snu/ds3mbc-snu.github.io
교재 36페이지의 input-output mapping 참고 벡터 대응시키는 모델 (뉴럴네트워크)
#Imports from keras.models import Sequential, Model from keras.layers.embeddings import Embedding from keras.layers import Input, Activation, Dense, Permute, Dropout, add, dot, concatenate, LSTM # We need to create the placeholders #The Input function is used to create a keras tensor #PLACEHOLDER shape = (max_story...
Tensor("input_1:0", shape=(None, 156), dtype=float32) Tensor("input_2:0", shape=(None, 6), dtype=float32)
MIT
TF-Keras_CHATBOT/0.Keras-Babi_MathQA.ipynb
ds3mbc-snu/ds3mbc-snu.github.io
encocder + decoder 교재 129 페이지 참고![title](images/babiMNN.png) On the left part of the previous image we can see a representation of a single layer of this model. Two different embeddings are calculated for each sentence, A and C. Also, the query or question q is embedded, using the B embedding.The A embeddings mi, are...
#Create input encoder A: input_encoder_m = Sequential() input_encoder_m.add(Embedding(input_dim=vocab_len,output_dim = 64)) #From paper input_encoder_m.add(Dropout(0.3)) #Outputs: (Samples, story_maxlen,embedding_dim) -- Gives a list of the lenght of the samples where each item has the #lenght of the max story lenght...
_____no_output_____
MIT
TF-Keras_CHATBOT/0.Keras-Babi_MathQA.ipynb
ds3mbc-snu/ds3mbc-snu.github.io
++++++++++++++++++++++++Once we have created the two embeddings for the input sentences, and the embeddings for the questions, we can start defining the operations that take place in our model. As mentioned previously, we compute the attention by doing the dot product between the embedding of the questions and one of ...
#Use dot product to compute similarity between input encoded m and question #Like in the paper: match = dot([input_encoded_m,question_encoded], axes = (2,2)) match = Activation('softmax')(match)
_____no_output_____
MIT
TF-Keras_CHATBOT/0.Keras-Babi_MathQA.ipynb
ds3mbc-snu/ds3mbc-snu.github.io
After this, we need to calculate the output o adding the match matrix with the second input vector sequence, and then calculate the response using this output and the encoded question.
#For the response we want to add this match with the ouput of input_encoded_c response = add([match,input_encoded_c]) response = Permute((2,1))(response) #Permute Layer: permutes dimensions of input #Once we have the response we can concatenate it with the question encoded: answer = concatenate([response, question_en...
_____no_output_____
MIT
TF-Keras_CHATBOT/0.Keras-Babi_MathQA.ipynb
ds3mbc-snu/ds3mbc-snu.github.io
Lastly, once this is done we add the rest of the layers of the model, adding an LSTM layer (instead of an RNN like in the paper), a dropout layer and a final softmax to compute the output.
# Reduce the answer tensor with a RNN (LSTM) answer = LSTM(32)(answer) #Regularization with dropout: answer = Dropout(0.5)(answer) #Output layer: answer = Dense(vocab_len)(answer) #Output shape: (Samples, Vocab_size) #Yes or no and all 0s #Now we need to output a probability distribution for the vocab, using softma...
_____no_output_____
MIT
TF-Keras_CHATBOT/0.Keras-Babi_MathQA.ipynb
ds3mbc-snu/ds3mbc-snu.github.io
모델 Model !!Notice here that the output is a vector of the size of the vocabulary (that is, the length of the number of words known by the model), where all the positions should be zero except the ones at the indexes of ‘yes’ and ‘no’.
#Now we build the final model: model = Model([input_sequence,question], answer) model.compile(optimizer='rmsprop', loss = 'categorical_crossentropy', metrics = ['accuracy']) #Categorical instead of binary cross entropy as because of the way we are training #we could actually see any of the words from the vocab as ou...
Model: "model_1" __________________________________________________________________________________________________ Layer (type) Output Shape Param # Connected to ================================================================================================== input_...
MIT
TF-Keras_CHATBOT/0.Keras-Babi_MathQA.ipynb
ds3mbc-snu/ds3mbc-snu.github.io
With these two lines we build the final model, and compile it, that is, define all the maths that will be going on in the background by specifying an optimiser, a loss function and a metric to optimise.Now its time to train the model, here we need to define the inputs to the training, (the input stories, questions and ...
print( answers_train.shape ) answers_train[0] val=model.evaluate( [inputs_train, questions_train], answers_train, batch_size = 32) print(val) # 길이가 38인 곳으로 랜덤하게 가기에, 확률적으로 1/38 ##################################################### my_story = 'Sandra picked up the milk . Mary travelled left . ' my_...
0.026316524
MIT
TF-Keras_CHATBOT/0.Keras-Babi_MathQA.ipynb
ds3mbc-snu/ds3mbc-snu.github.io
+++++++++++++++++++++++++++++++++   여기의 숫자 ? 확률적으로 ! 깡통인 모델에 이미 학습한 것을 주입하자모델 학습과정 설정하기 학습하기 전에 학습에 대한 설정을 수행합니다. 손실 함수 및 최적화 방법을 정의합니다. 케라스에서는 compile() 함수를 사용합니다. 모델 학습시키기 훈련셋을 이용하여 구성한 모델로 학습시킵니다. 케라스에서는 fit() 함수를 사용합니다. 학습과정 살펴보기 모델 학습 시 훈련셋, 검증셋의 손실 및 정확도를 측정합...
del model ################################################## #To load a model that we have already trained and saved: # batch_size=32 , epochs=350 이상 훈련시킨 모델 부름 from keras.models import load_model # returns a compiled model # identical to the previous one ################################################## ######...
C:\WinPython37F\python-3.7.2.amd64\lib\site-packages\tensorflow_core\python\framework\indexed_slices.py:424: UserWarning: Converting sparse IndexedSlices to a dense Tensor of unknown shape. This may consume a large amount of memory. "Converting sparse IndexedSlices to a dense Tensor of unknown shape. "
MIT
TF-Keras_CHATBOT/0.Keras-Babi_MathQA.ipynb
ds3mbc-snu/ds3mbc-snu.github.io
=============================== 더 공부를 시키자 !! 공부한 것을 저장시키자 !!   Training and testing the model Saving the model +++++++++++ 학습 평가를 Matplotlib 그래프로 표현
""" import keras.callbacks import EarlyStopping early_stopping_callback = EarlyStopping( monitor='val_loss', patience=100) history = model.fit([inputs_train,questions_train],answers_train, batch_size = 32, epochs = 150, validation_data = ([inputs_test,questions_test],answers_...
Train on 10000 samples, validate on 1000 samples Epoch 1/5 10000/10000 [==============================] - 5s 481us/step - loss: 2.4825 - accuracy: 0.4756 - val_loss: 0.6502 - val_accuracy: 0.6070 Epoch 2/5 10000/10000 [==============================] - 4s 392us/step - loss: 0.6337 - accuracy: 0.6368 - val_loss: 0.5686 ...
MIT
TF-Keras_CHATBOT/0.Keras-Babi_MathQA.ipynb
ds3mbc-snu/ds3mbc-snu.github.io
batch_size = 32 와 epochs=50 의 시작Train on 10000 samples, validate on 1000 samplesEpoch 1/50 10000/10000 [==============================] - 7s 686us/step - loss: 0.8794 - accuracy: 0.5036 - val_loss: 0.6941 - val_accuracy: 0.5030Epoch 2/50 10000/10000 [==============================] - 6s 570us/step - loss: 0.7019...
# model.compile(optimizer='rmsprop', loss = 'categorical_crossentropy', metrics = ['accuracy']) # print( answers_train.shape ) ==> ( 10000, 38 ) one hot vector ### train 에 대해서 evaluate 한다 //////// test 데이터로 하는 것과 차이 ?? /////// val=model.evaluate( [inputs_train,questions_train], answers_train, batch_size = 32) #####...
10000/10000 [==============================] - 1s 94us/step
MIT
TF-Keras_CHATBOT/0.Keras-Babi_MathQA.ipynb
ds3mbc-snu/ds3mbc-snu.github.io
========================================== 학습된 AI 두뇌 테스트를 위해 문제를 출제 !!!! ====================================
#Lets check out the predictions on the test set: #These are just probabilities for every single word on the vocab # 테스트 데이터 기반의 prediction ############################## pred_results = model.predict(([inputs_test,questions_test])) print( pred_results )
[[5.3464513e-09 4.7893756e-09 5.9277316e-09 ... 5.8098868e-09 6.7517063e-09 5.7777618e-09] [1.1304347e-08 9.6045669e-09 1.1915859e-08 ... 1.1772948e-08 1.3240343e-08 1.3179218e-08] [4.7399933e-08 3.1272307e-08 4.0516948e-08 ... 4.2989544e-08 4.5466496e-08 4.3368548e-08] ... [2.2156049e-08 1.7657909e-08 2.2862...
MIT
TF-Keras_CHATBOT/0.Keras-Babi_MathQA.ipynb
ds3mbc-snu/ds3mbc-snu.github.io
These results are an array, as mentioned earlier that contain in every position the probabilities of each of the words in the vocabulary being the answer to the question. If we look at the first element of this array, we will see a vector of the size of the vocabulary, where all the times are close to 0 except the ones...
my_story = 'Sandra picked up the milk . Mary travelled left . ' my_question = 'Sandra got the milk ?' my_data = [(my_story.split(), my_question.split(),'yes')] my_story, my_ques, my_ans = vectorize_stories(my_data) pred_results = model.predict(([my_story,my_ques])) val_max = np.argmax(pred_results[0]) print(pred_res...
_____no_output_____
MIT
TF-Keras_CHATBOT/0.Keras-Babi_MathQA.ipynb
ds3mbc-snu/ds3mbc-snu.github.io
================================
#Now, we can make our own questions using the vocabulary we have print( len(vocab) ) vocab # 'office': 1 # '?': 37 == 마지막 index my_story = 'Sandra picked up the milk . Mary travelled left . ' my_story.split()
_____no_output_____
MIT
TF-Keras_CHATBOT/0.Keras-Babi_MathQA.ipynb
ds3mbc-snu/ds3mbc-snu.github.io
my_story = 'Sandra picked up the milk . Mary travelled left . ' my_question = 'Sandra got the milk ?' my_data = [(my_story.split(), my_question.split(),'yes')] my_story, my_ques, my_ans = vectorize_stories(my_data) pred_results = model.predict(([my_story,my_ques])) val_max = np.argmax(pred_results[0]...
my_question = 'Sandra got the milk ?' my_question.split() #Put the data in the same format as before my_data = [(my_story.split(), my_question.split(),'yes')] #Vectorize this data my_story, my_ques, my_ans = vectorize_stories(my_data) #Make the prediction pred_results = model.predict(([my_story,my_ques])) print( pred...
(1, 38) yes : 1.633283e-09 no : 2.412464e-09 0.6770186
MIT
TF-Keras_CHATBOT/0.Keras-Babi_MathQA.ipynb
ds3mbc-snu/ds3mbc-snu.github.io
'yes': 24, 'left': 25, 'to': 26, 'milk': 27, 'in': 28, 'moved': 29, 'discarded': 30, 'no': 31,
val_max = np.argmax(pred_results[0]) print( val_max ) #Correct prediction! for key,val in tokenizer.word_index.items(): if val == val_max: k = key print(val) print(k) #Confidence pred_results[0][val_max]
_____no_output_____
MIT
TF-Keras_CHATBOT/0.Keras-Babi_MathQA.ipynb
ds3mbc-snu/ds3mbc-snu.github.io
====================================
my_story = 'Sandra picked up the milk . Sandra moved to the bathroom . ' my_question = 'Is the milk in the bathroom ?' my_data = [(my_story.split(), my_question.split(),'yes')] my_story, my_ques, my_ans = vectorize_stories(my_data) pred_results = model.predict(([my_story,my_ques])) val_max = np.argmax(pred_results[0]) ...
29 37 yes
MIT
TF-Keras_CHATBOT/0.Keras-Babi_MathQA.ipynb
ds3mbc-snu/ds3mbc-snu.github.io
====================================   한 장에 모아쓴 코드
import keras from keras.models import Sequential, Model from keras.layers.embeddings import Embedding from keras.layers import Permute, dot, add, concatenate from keras.layers import LSTM, Dense, Dropout, Input, Activation from keras.utils.data_utils import get_file from keras.preprocessing.sequence import pad_sequence...
_____no_output_____
MIT
TF-Keras_CHATBOT/0.Keras-Babi_MathQA.ipynb
ds3mbc-snu/ds3mbc-snu.github.io
====================================   [생각] 영어 데이터를 한글 번역기로 번역을 시킨다.   [생각] 한글용 Babi 데이터로 한글 QA 만들어본다.   [생각] 수학학습 질문과 답변 데이터로 만들어본다.   web 버젼, attention 버젼 https://github.com/vinhkhuc/MemN2N-babi-python ++++++++++++++++++++++++++++++++++   sequence 2 sequence 실험   ![title](im...
import tensorflow.compat.v1 as tf tf.disable_eager_execution() import numpy as np char_arr = [c for c in "SEPabcdefghijklmnopqrstuvwxyz단어나무놀이소녀키스사랑봉구우루"] num_dic = {n: i for i, n in enumerate(char_arr)} dic_len = len(num_dic) seq_data = [['word', "단어"], ["wood", "나무"], ["game", "놀이"], ["girl", "소녀"], [...
==== translate test ==== word -> 단어 wodr -> 단무 love -> 사랑 loev -> 사랑 bogn -> 봉구 uruu -> 우루 abcd -> 놀봉구
MIT
TF-Keras_CHATBOT/0.Keras-Babi_MathQA.ipynb
ds3mbc-snu/ds3mbc-snu.github.io
자동 단어 완성 !! (3글자 ==> 4글자) ![title](images/word_auto.png)
import tensorflow.compat.v1 as tf import numpy as np char_arr = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"] num_dic = {n: i for i, n in enumerate(char_arr)} dic_len = len(num_dic) seq_data = [...
==== prediction ==== input_value: ['wor', 'woo', 'dee', 'div', 'col', 'coo', 'loa', 'lov', 'kis', 'kin'] prediction_value: ['word', 'wood', 'deep', 'dive', 'cold', 'cool', 'load', 'love', 'kiss', 'kind'] accuracy: 1.000
MIT
TF-Keras_CHATBOT/0.Keras-Babi_MathQA.ipynb
ds3mbc-snu/ds3mbc-snu.github.io
4.ipynb 에서 attention 개념 위해 사용하는 toy 코드   +++++++++++++++++++++++++++++++++++++++++++++++++++   [과제] 실행시간이 오래 걸림 . 저장된 모델 불러오는 기능을 추가. [과제] 구글 번역기로 한글 charbot 데이터를 영어로 번역하고 탐구.
from __future__ import print_function from keras.models import Model from keras.layers import Input, LSTM, Dense import numpy as np batch_size = 64 # Batch size for training. epochs = 3 # 100 # Number of epochs to train for. latent_dim = 256 # Latent dimensionality of the encoding space. num_samples = 10000 # Num...
Number of samples: 3318 Number of unique input tokens: 75 Number of unique output tokens: 891 Max sequence length for inputs: 537 Max sequence length for outputs: 298 Train on 2654 samples, validate on 664 samples Epoch 1/100 2654/2654 [==============================] - 473s 178ms/step - loss: 0.6580 - accuracy: 0.9389...
MIT
TF-Keras_CHATBOT/0.Keras-Babi_MathQA.ipynb
ds3mbc-snu/ds3mbc-snu.github.io
Skip-gram Word2VecIn this notebook, I'll lead you through using PyTorch to implement the [Word2Vec algorithm](https://en.wikipedia.org/wiki/Word2vec) using the skip-gram architecture. By implementing this, you'll learn about embedding words for use in natural language processing. This will come in handy when dealing w...
# read in the extracted text file with open('data/text8') as f: text = f.read() # print out the first 100 characters print(text[:100])
anarchism originated as a term of abuse first used against early working class radicals including t
MIT
word2vec-embeddings/Negative_Sampling_Exercise.ipynb
sonalagrawal7/DeepLearning-nanodegree-exercises
Pre-processingHere I'm fixing up the text to make training easier. This comes from the `utils.py` file. The `preprocess` function does a few things:>* It converts any punctuation into tokens, so a period is changed to ` `. In this data set, there aren't any periods, but it will help in other NLP problems. * It remove...
import utils # get list of words words = utils.preprocess(text) print(words[:30]) # print some stats about this word data print("Total words in text: {}".format(len(words))) print("Unique words: {}".format(len(set(words)))) # `set` removes any duplicate words
Total words in text: 16680599 Unique words: 63641
MIT
word2vec-embeddings/Negative_Sampling_Exercise.ipynb
sonalagrawal7/DeepLearning-nanodegree-exercises
DictionariesNext, I'm creating two dictionaries to convert words to integers and back again (integers to words). This is again done with a function in the `utils.py` file. `create_lookup_tables` takes in a list of words in a text and returns two dictionaries.>* The integers are assigned in descending frequency order, ...
vocab_to_int, int_to_vocab = utils.create_lookup_tables(words) int_words = [vocab_to_int[word] for word in words] print(int_words[:30])
[5233, 3080, 11, 5, 194, 1, 3133, 45, 58, 155, 127, 741, 476, 10571, 133, 0, 27349, 1, 0, 102, 854, 2, 0, 15067, 58112, 1, 0, 150, 854, 3580]
MIT
word2vec-embeddings/Negative_Sampling_Exercise.ipynb
sonalagrawal7/DeepLearning-nanodegree-exercises
SubsamplingWords that show up often such as "the", "of", and "for" don't provide much context to the nearby words. If we discard some of them, we can remove some of the noise from our data and in return get faster training and better representations. This process is called subsampling by Mikolov. For each word $w_i$ i...
from collections import Counter import random import numpy as np threshold = 1e-5 word_counts = Counter(int_words) #print(list(word_counts.items())[0]) # dictionary of int_words, how many times they appear total_count = len(int_words) freqs = {word: count/total_count for word, count in word_counts.items()} p_drop = ...
[5233, 3133, 476, 10571, 27349, 102, 15067, 58112, 3580, 10712, 371, 26, 1423, 2757, 5233, 44611, 792, 186, 5233, 8983, 4147, 6437, 4186, 5233, 344, 6753, 7573, 1774, 11064, 7088]
MIT
word2vec-embeddings/Negative_Sampling_Exercise.ipynb
sonalagrawal7/DeepLearning-nanodegree-exercises
Making batches Now that our data is in good shape, we need to get it into the proper form to pass it into our network. With the skip-gram architecture, for each word in the text, we want to define a surrounding _context_ and grab all the words in a window around that word, with size $C$. From [Mikolov et al.](https://...
def get_target(words, idx, window_size=5): ''' Get a list of words in a window around an index. ''' R = np.random.randint(1, window_size+1) start = idx - R if (idx - R) > 0 else 0 stop = idx + R target_words = words[start:idx] + words[idx+1:stop+1] return list(target_words) # test your...
Input: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Target: [4, 6]
MIT
word2vec-embeddings/Negative_Sampling_Exercise.ipynb
sonalagrawal7/DeepLearning-nanodegree-exercises