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
For more about Numpy, see [http://wiki.scipy.org/Tentative_NumPy_Tutorial](http://wiki.scipy.org/Tentative_NumPy_Tutorial). Read and save filesThere are two kinds of computer files: text files and binary files:> Text file: computer file where the content is structured as a sequence of lines of electronic text. Text fi...
f = open("newfile.txt", "w") # open file for writing f.write("This is a test\n") # save to file f.write("And here is another line\n") # save to file f.close() f = open('newfile.txt', 'r') # open file for reading f = f.read() # read from file print(f) help(open)
Help on built-in function open in module io: open(...) open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None) -> file object Open file and return a stream. Raise IOError upon failure. file is either a text or byte string giving the name (...
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
**Using Numpy**
import numpy as np data = np.random.randn(3,3) np.savetxt('myfile.txt', data, fmt="%12.6G") # save to file data = np.genfromtxt('myfile.txt', unpack=True) # read from file data
_____no_output_____
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
Ploting with matplotlibMatplotlib is the most-widely used packge for plotting data in Python. Let's see some examples of it.
import matplotlib.pyplot as plt
_____no_output_____
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
Use the IPython magic `%matplotlib inline` to plot a figure inline in the notebook with the rest of the text:
%matplotlib notebook import numpy as np t = np.linspace(0, 0.99, 100) x = np.sin(2 * np.pi * 2 * t) n = np.random.randn(100) / 5 plt.Figure(figsize=(12,8)) plt.plot(t, x, label='sine', linewidth=2) plt.plot(t, x + n, label='noisy sine', linewidth=2) plt.annotate(s='$sin(4 \pi t)$', xy=(.2, 1), fontsize=20, color=[0, 0...
_____no_output_____
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
Use the IPython magic `%matplotlib qt` to plot a figure in a separate window (from where you will be able to change some of the figure proprerties):
%matplotlib qt mu, sigma = 10, 2 x = mu + sigma * np.random.randn(1000) fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 4)) ax1.plot(x, 'ro') ax1.set_title('Data') ax1.grid() n, bins, patches = ax2.hist(x, 25, normed=True, facecolor='r') # histogram ax2.set_xlabel('Bins') ax2.set_ylabel('Probability') ax2.set_title(...
_____no_output_____
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
And a window with the following figure should appear:
from IPython.display import Image Image(url="./../images/plot.png")
_____no_output_____
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
You can switch back and forth between inline and separate figure using the `%matplotlib` magic commands used above. There are plenty more examples with the source code in the [matplotlib gallery](http://matplotlib.org/gallery.html).
# get back the inline plot %matplotlib inline
_____no_output_____
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
Signal processing with ScipyThe Scipy package has a lot of functions for signal processing, among them: Integration (scipy.integrate), Optimization (scipy.optimize), Interpolation (scipy.interpolate), Fourier Transforms (scipy.fftpack), Signal Processing (scipy.signal), Linear Algebra (scipy.linalg), and Statistics (s...
from scipy.signal import butter, filtfilt import scipy.fftpack freq = 100. t = np.arange(0,1,.01); w = 2*np.pi*1 # 1 Hz y = np.sin(w*t)+0.1*np.sin(10*w*t) # Butterworth filter b, a = butter(4, (5/(freq/2)), btype = 'low') y2 = filtfilt(b, a, y) # 2nd derivative of the data ydd = np.diff(y,2)*freq*freq # raw data y2dd...
_____no_output_____
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
And the plots:
fig, ((ax1,ax2),(ax3,ax4)) = plt.subplots(2, 2, figsize=(10, 4)) ax1.set_title('Temporal domain', fontsize=14) ax1.plot(t, y, 'r', linewidth=2, label = 'raw data') ax1.plot(t, y2, 'b', linewidth=2, label = 'filtered @ 5 Hz') ax1.set_ylabel('f') ax1.legend(frameon=False, fontsize=12) ax2.set_title('Frequency domain', ...
_____no_output_____
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
For more about Scipy, see [http://docs.scipy.org/doc/scipy/reference/tutorial/](http://docs.scipy.org/doc/scipy/reference/tutorial/). Symbolic mathematics with SympySympy is a package to perform symbolic mathematics in Python. Let's see some of its features:
from IPython.display import display import sympy as sym from sympy.interactive import printing printing.init_printing()
_____no_output_____
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
Define some symbols and the create a second-order polynomial function (a.k.a., parabola):
x, y = sym.symbols('x y') y = x**2 - 2*x - 3 y
_____no_output_____
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
Plot the parabola at some given range:
from sympy.plotting import plot %matplotlib inline plot(y, (x, -3, 5));
_____no_output_____
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
And the roots of the parabola are given by:
sym.solve(y, x)
_____no_output_____
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
We can also do symbolic differentiation and integration:
dy = sym.diff(y, x) dy sym.integrate(dy, x)
_____no_output_____
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
For example, let's use Sympy to represent three-dimensional rotations. Consider the problem of a coordinate system xyz rotated in relation to other coordinate system XYZ. The single rotations around each axis are illustrated by:
from IPython.display import Image Image(url="./../images/rotations.png")
_____no_output_____
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
The single 3D rotation matrices around Z, Y, and X axes can be expressed in Sympy:
from IPython.core.display import Math from sympy import symbols, cos, sin, Matrix, latex a, b, g = symbols('alpha beta gamma') RX = Matrix([[1, 0, 0], [0, cos(a), -sin(a)], [0, sin(a), cos(a)]]) display(Math(latex('\\mathbf{R_{X}}=') + latex(RX, mat_str = 'matrix'))) RY = Matrix([[cos(b), 0, sin(b)], [0, 1, 0], [-sin...
_____no_output_____
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
And using Sympy, a sequence of elementary rotations around X, Y, Z axes is given by:
RXYZ = RZ*RY*RX display(Math(latex('\\mathbf{R_{XYZ}}=') + latex(RXYZ, mat_str = 'matrix')))
_____no_output_____
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
Suppose there is a rotation only around X ($\alpha$) by $\pi/2$; we can get the numerical value of the rotation matrix by substituing the angle values:
r = RXYZ.subs({a: np.pi/2, b: 0, g: 0}) r
_____no_output_____
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
And we can prettify this result:
display(Math(latex(r'\mathbf{R_{(\alpha=\pi/2)}}=') + latex(r.n(chop=True, prec=3), mat_str = 'matrix')))
_____no_output_____
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
For more about Sympy, see [http://docs.sympy.org/latest/tutorial/](http://docs.sympy.org/latest/tutorial/). Data analysis with pandas> "[pandas](http://pandas.pydata.org/) is a Python package providing fast, flexible, and expressive data structures designed to make working with โ€œrelationalโ€ or โ€œlabeledโ€ data both easy...
import pandas as pd x = 5*['A'] + 5*['B'] x df = pd.DataFrame(np.random.rand(10,2), columns=['Level 1', 'Level 2'] ) df['Group'] = pd.Series(['A']*5 + ['B']*5) plot = df.boxplot(by='Group') from pandas.tools.plotting import scatter_matrix df = pd.DataFrame(np.random.randn(100, 3), columns=['A', 'B', 'C']) plot = scatte...
_____no_output_____
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
pandas is aware the data is structured and give you basic statistics considerint that and nicely formatted:
df.describe()
_____no_output_____
MIT
notebooks/PythonTutorial.ipynb
jagar2/BMC
Task 4: Largest palindrome product As always, we'll try with the brute force algorithm, that has ~O(n^2) complexity, but still works pretty fast:
import time start = time.time() max_palindrome = 0 for i in range(100, 1000): for j in range(100, 1000): if str(i*j) == str(i*j)[::-1] and i*j > max_palindrome: max_palindrome = i*j finish = time.time() - start print(max_palindrome) print("Time in seconds: ", finish)
906609 Time in seconds: 0.7557618618011475
Unlicense
python/Problem4.ipynb
ditekunov/ProjectEuler-research
But we'll try to improve it.Firstly, we'll implement an obvious way to find MAX value, by running the cycle downwards.Let's record the speed to track, that the time improved.
import time start = time.time() max_palindrome = 0 for i in range(999, 800, -1): for j in range(999, 99, -1): if str(i*j) == str(i*j)[::-1] and i*j > max_palindrome: max_palindrome = i*j finish = time.time() - start print(max_palindrome) print(finish)
906609 0.17235779762268066
Unlicense
python/Problem4.ipynb
ditekunov/ProjectEuler-research
Note for the interpretation of the curves and definition of the statistical variablesThe quantum state classifier (QSC) error rates $\widehat{r}_i$ in function of the number of experimental shots $n$ were determined for each highly entangled quantum state $\omega_i$ in the $\Omega$ set, with $i=1...m$.The curves seen ...
# Calculate shot number 'm_shots' for mean error rate 'm_shot_rates' <= epsilon_t len_data = len(All_data) epsilon_t = 0.0005 window = 11 for i in range(len_data): curve = np.array(All_data[i]['error_curve']) # filter the curve only for real devices: if All_data[i]['device']!="ideal_device": ...
_____no_output_____
Apache-2.0
3_2_preliminary_statistics_project_2.ipynb
cnktysz/qiskit-quantum-state-classifier
Error rates in function of chosen $\epsilon_s$ and $\epsilon_t$
print("max mean error rate at n_s over all experiments =", round(max(df_All.mns_rate[:-2]),6)) print("min mean error rate at n_t over all experiments =", round(min(df_All.min_r[:-2]),6)) print("max mean error rate at n_t over all experiments =", round(max(df_All.min_r[:-2]),6)) df_All.mns_rate[:-2].plot.hist(alpha=0.5,...
_____no_output_____
Apache-2.0
3_2_preliminary_statistics_project_2.ipynb
cnktysz/qiskit-quantum-state-classifier
Statistical overviewFor this section, an ordinary linear least square estimation is performed.The dependent variables tested are $ln\;n_s$ (log_shots) and $ln\;n_t$ (log_min_r_shots)
stat_model = ols("log_shots ~ metric", df_All.query("device != 'ideal_device'")).fit() print(stat_model.summary()) stat_model = ols("log_min_r_shots ~ metric", df_All.query("device != 'ideal_device'")).fit() print(stat_model.summary()) stat_model = ols("log_shots ~ model+mitigation+...
OLS Regression Results ============================================================================== Dep. Variable: log_min_r_shots R-squared: 0.532 Model: OLS Adj. R-squared: 0.491 Meth...
Apache-2.0
3_2_preliminary_statistics_project_2.ipynb
cnktysz/qiskit-quantum-state-classifier
Comments:For the QSC, two different metrics were compared and at the end they gave the same output. For further analysis, the results obtained using the squared euclidean distance between distribution will be illustrated in this notebook, as it is more classical and strictly equivalent to the other classical Hellinger...
# this for Jensen-Shannon metric s_metric = 'jensenshannon' sm = np.array([96+16+16+16]) # added Quito and Lima and Belem SAD=0 # ! will be unselected by running the next cell # mainstream option for metric: squared euclidean distance # skip this cell if you don't want this option s_metric = 'sqeuclidean' sm = np.arra...
_____no_output_____
Apache-2.0
3_2_preliminary_statistics_project_2.ipynb
cnktysz/qiskit-quantum-state-classifier
1. Compare distribution models
# select data according to the options df_mod = df_All[df_All.mitigation == mit][df_All.metric == s_metric]
<ipython-input-20-af347b9ea33a>:2: UserWarning: Boolean Series key will be reindexed to match DataFrame index. df_mod = df_All[df_All.mitigation == mit][df_All.metric == s_metric]
Apache-2.0
3_2_preliminary_statistics_project_2.ipynb
cnktysz/qiskit-quantum-state-classifier
A look at $n_s$ and $n_t$
print("mitigation:",mit," metric:",s_metric ) df_mod.groupby('device')[['shots','min_r_shots']].describe(percentiles=[0.5])
mitigation: yes metric: sqeuclidean
Apache-2.0
3_2_preliminary_statistics_project_2.ipynb
cnktysz/qiskit-quantum-state-classifier
Ideal vs empirical model: no state creation - measurements delay
ADD=0+SAD+MIT #opl.plot_curves(All_data, np.append(sm,ADD+np.array([4,5,12,13,20,21,28,29,36,37,44,45])), opl.plot_curves(All_data, np.append(sm,ADD+np.array([4,5,12,13,20,21,28,29,36,37,52,53,60,61,68,69])), "Monte Carlo Simulation: Theoretical PDM ...
_____no_output_____
Apache-2.0
3_2_preliminary_statistics_project_2.ipynb
cnktysz/qiskit-quantum-state-classifier
Paired t-test and Wilcoxon test
for depvar in ['log_shots', 'log_min_r_shots']: #for depvar in ['shots', 'min_r_shots']: print("mitigation:",mit," metric:",s_metric, "variable:", depvar) df_dep = df_mod.query("id_gates == 0.0").groupby(['model'])[depvar] print(df_dep.describe(percentiles=[0.5]),"\n") # no error rate curve obtained fo...
mitigation: yes metric: sqeuclidean id_gates == 0.0 OLS Regression Results ============================================================================== Dep. Variable: log_min_r_shots R-squared: 0.833 Model: ...
Apache-2.0
3_2_preliminary_statistics_project_2.ipynb
cnktysz/qiskit-quantum-state-classifier
Ideal vs empirical model: with state creation - measurements delay of 256 id gates
ADD=72+SAD+MIT opl.plot_curves(All_data, np.append(sm,ADD+np.array([4,5,12,13,20,21,28,29,36,37,52,53,60,61,68,69])), "No noise simulator vs empirical model - $\epsilon=0.001$ - with delay", ["metric","mitigation"], ["device","mod...
_____no_output_____
Apache-2.0
3_2_preliminary_statistics_project_2.ipynb
cnktysz/qiskit-quantum-state-classifier
Paired t-test and Wilcoxon test
for depvar in ['log_shots', 'log_min_r_shots']: print("mitigation:",mit," metric:",s_metric, "variable:", depvar) df_dep = df_mod.query("id_gates == 256.0 ").groupby(['model'])[depvar] print(df_dep.describe(percentiles=[0.5]),"\n") # no error rate curve obtained for ibmqx2 with the ideal model, hence...
mitigation: yes metric: sqeuclidean id_gates == 256.0 OLS Regression Results ============================================================================== Dep. Variable: log_min_r_shots R-squared: 0.890 Model: ...
Apache-2.0
3_2_preliminary_statistics_project_2.ipynb
cnktysz/qiskit-quantum-state-classifier
Pooling results obtained in circuit sets with and without creation-measurement delay Paired t-test and Wilcoxon test
#for depvar in ['log_shots', 'log_min_r_shots']: for depvar in ['log_shots', 'log_min_r_shots']: print("mitigation:",mit," metric:",s_metric, "variable:", depvar) df_dep = df_mod.groupby(['model'])[depvar] print(df_dep.describe(percentiles=[0.5]),"\n") # no error rate curve obtained for ibmqx2 with the...
mitigation: yes metric: sqeuclidean variable: log_shots count mean std min 50% max model empirical 16.0 3.580581 0.316850 3.218876 3.510542 4.276666 ideal_sim 16.0 3.834544 0.520834 3.295837 3.701226 5.3...
Apache-2.0
3_2_preliminary_statistics_project_2.ipynb
cnktysz/qiskit-quantum-state-classifier
Statsmodel Ordinary Least Square (OLS) Analysis
print("mitigation:",mit," metric:",s_metric ) stat_model = ols("log_shots ~ model + id_gates + device + fidelity + QV" , df_mod).fit() print(stat_model.summary()) print("mitigation:",mit," metric:",s_metric ) stat_model = ols("log_min_r_shots ~ model + id_gates + device + fidelity+QV ", ...
mitigation: yes metric: sqeuclidean OLS Regression Results ============================================================================== Dep. Variable: log_min_r_shots R-squared: 0.842 Model: OLS Adj. ...
Apache-2.0
3_2_preliminary_statistics_project_2.ipynb
cnktysz/qiskit-quantum-state-classifier
Continuous Control--- 1. Import the Necessary Packages
from unityagents import UnityEnvironment import random import torch import numpy as np from collections import deque import matplotlib.pyplot as plt %matplotlib inline from ddpg_agent import Agent
_____no_output_____
MIT
Projects/p2_continuous-control/.ipynb_checkpoints/DDPG_with_20_Agent-checkpoint.ipynb
Clara-YR/Udacity-DRL
2. Instantiate the Environment and 20 Agents
# initialize the environment env = UnityEnvironment(file_name='./Reacher_20.app') # get the default brain brain_name = env.brain_names[0] brain = env.brains[brain_name] # reset the environment env_info = env.reset(train_mode=True)[brain_name] # number of agents num_agents = len(env_info.agents) print('Number of agent...
_____no_output_____
MIT
Projects/p2_continuous-control/.ipynb_checkpoints/DDPG_with_20_Agent-checkpoint.ipynb
Clara-YR/Udacity-DRL
3. Train the 20 Agents with DDPGTo amend the `ddpg` code to work for 20 agents instead of 1, here are the modifications I did in `ddpg_agent.py`:- With each step, each agent adds its experience to a replay buffer shared by all agents (line 61-61).- At first, the (local) actor and critic networks are updated 20 times i...
def ddpg(n_episodes=1000, max_t=300, print_every=100, num_agents=1): """ Params ====== n_episodes (int): maximum number of training episodes max_t (int): maximum number of timesteps per episode print_every (int): episodes interval to print training scores num_agents...
_____no_output_____
MIT
Projects/p2_continuous-control/.ipynb_checkpoints/DDPG_with_20_Agent-checkpoint.ipynb
Clara-YR/Udacity-DRL
**OPTICS Algorithm** Ordering Points to Identify the Clustering Structure (OPTICS) is a Clustering Algorithm which locates region of high density that are seperated from one another by regions of low density. For using this library in Python this comes under Scikit Learn Library. Parameters: **Reachability Distance**...
import matplotlib.pyplot as plt #Used for plotting graphs from sklearn.datasets import make_blobs #Used for creating random dataset from sklearn.cluster import OPTICS #OPTICS is provided under Scikit-Learn Extra from sklearn.metrics import silhouette_score #silhouette score for checking accuracy import numpy as np ...
_____no_output_____
MIT
Datascience_With_Python/Machine Learning/Algorithms/Optics Clustering Algorithm/optics_clustering_algorithm.ipynb
vishnupriya129/winter-of-contributing
Generating Data
data, clusters = make_blobs( n_samples=800, centers=4, cluster_std=0.3, random_state=0 ) # Originally created plot with data plt.scatter(data[:,0], data[:,1]) plt.show()
_____no_output_____
MIT
Datascience_With_Python/Machine Learning/Algorithms/Optics Clustering Algorithm/optics_clustering_algorithm.ipynb
vishnupriya129/winter-of-contributing
Model Creation
# Creating OPTICS Model optics_model = OPTICS(min_samples=50, xi=.05, min_cluster_size=.05) #min_samples : The number of samples in a neighborhood for a point to be considered as a core point. #xi : Determines the minimum steepness on the reachability plot that constitutes a cluster boundary #min_cluster_size : M...
_____no_output_____
MIT
Datascience_With_Python/Machine Learning/Algorithms/Optics Clustering Algorithm/optics_clustering_algorithm.ipynb
vishnupriya129/winter-of-contributing
Plotting our observations
print('Estimated no. of clusters: %d' % no_clusters) print('Estimated no. of noise points: %d' % no_noise) colors = list(map(lambda x: '#aa2211' if x == 1 else '#120416', optics_labels)) plt.scatter(data[:,0], data[:,1], c=colors, marker="o", picker=True) plt.title(f'OPTICS clustering') plt.xlabel('Axis X[0]') plt...
_____no_output_____
MIT
Datascience_With_Python/Machine Learning/Algorithms/Optics Clustering Algorithm/optics_clustering_algorithm.ipynb
vishnupriya129/winter-of-contributing
Accuracy of OPTICS Clustering
OPTICS_score = silhouette_score(data, optics_labels) OPTICS_score
_____no_output_____
MIT
Datascience_With_Python/Machine Learning/Algorithms/Optics Clustering Algorithm/optics_clustering_algorithm.ipynb
vishnupriya129/winter-of-contributing
My First Square Roots This is my first notebook where I am going to implement the Babylonian square root algorithm in Python.\
variable = 6 variable a = q = 1.5 a 1.5**2 1.25**2 u*u=2 u*u = 2 u**2 = 2 s*s=33 q = 1 q a=[1.5] for i in range (10): next = a [i] + 2 a.append(next) a 2 a[0] a[2.3] a[0] a[5] a[0:5] plt.plot(a) plt.plot(a, 'o') plt.title("My First Sequence") b=[1.5] for i in range (10): next = b [i] * 2 b.appen...
_____no_output_____
MIT
square_roots_intro.ipynb
izzetmert/lang_calc_2017
Finding ProbabilitiesOver the centuries, there has been considerable philosophical debate about what probabilities are. Some people think that probabilities are relative frequencies; others think they are long run relative frequencies; still others think that probabilities are a subjective measure of their own persona...
rolls = np.arange(1, 51, 1) results = Table().with_columns( 'Rolls', rolls, 'Chance of at least one 6', 1 - (5/6)**rolls ) results
_____no_output_____
MIT
Mathematics/Statistics/Statistics and Probability Python Notebooks/Computational and Inferential Thinking - The Foundations of Data Science (book)/Notebooks - by chapter/9. Randomness and Probabiltities/5. Finding_Probabilities.ipynb
okara83/Becoming-a-Data-Scientist
The chance that a 6 appears at least once rises rapidly as the number of rolls increases.
results.scatter('Rolls')
_____no_output_____
MIT
Mathematics/Statistics/Statistics and Probability Python Notebooks/Computational and Inferential Thinking - The Foundations of Data Science (book)/Notebooks - by chapter/9. Randomness and Probabiltities/5. Finding_Probabilities.ipynb
okara83/Becoming-a-Data-Scientist
In 50 rolls, you are almost certain to get at least one 6.
results.where('Rolls', are.equal_to(50))
_____no_output_____
MIT
Mathematics/Statistics/Statistics and Probability Python Notebooks/Computational and Inferential Thinking - The Foundations of Data Science (book)/Notebooks - by chapter/9. Randomness and Probabiltities/5. Finding_Probabilities.ipynb
okara83/Becoming-a-Data-Scientist
Chapter 7 1. What makes dictionaries different from sequence type containers like lists and tuples is the way the data are stored and accessed. 2.Sequence types use numeric keys only (numbered sequentially as indexed offsets from the beginning of the sequence). Mapping types may use most other object types as key...
adict={} bdict={"k":"v"} bdict
_____no_output_____
Apache-2.0
Chapter7.ipynb
yangzhou95/notes
b. another way to create dictionary is using dict() method (factory fucntion)
fdict = dict((['x', 1], ['y', 2])) cdict=dict([("k1",2),("k2",3)])
_____no_output_____
Apache-2.0
Chapter7.ipynb
yangzhou95/notes
c.dictionaries may also be created using a very convenient built-in method for creating a โ€œdefaultโ€ dictionary whose elements all have the same value (defaulting to None if not given), fromkeys():
ddict = {}.fromkeys(('x', 'y'), -1) ddict ddict={}.fromkeys(('x','y'),(2,3)) ddict
_____no_output_____
Apache-2.0
Chapter7.ipynb
yangzhou95/notes
6.How to Access Values in DictionariesTo traverse a dictionary (normally by key), you only need to cycle through its keys, like this:
dict2 = {'name': 'earth', 'port': 80} for key in dict2.keys(): print("key=%s,value=%s" %(key,dict2[key]))
key=name,value=earth key=port,value=80
Apache-2.0
Chapter7.ipynb
yangzhou95/notes
a.Beginning with Python 2.2, you no longer need to use the keys() method to extract a list of keys to loop over. Iterators were created to simplify access- ing of sequence-like objects such as dictionaries and files. Using just the dictionary name itself will cause an iterator over that dictionary to be used in a for ...
dict2 = {'name': 'earth', 'port': 80} for key in dict2: print("key=%s,value=%s" %(key,dict2[key]))
key=name,value=earth key=port,value=80
Apache-2.0
Chapter7.ipynb
yangzhou95/notes
b.To access individual dictionary elements, you use the familiar square brackets along with the key to obtain its value:
dict2['name']
_____no_output_____
Apache-2.0
Chapter7.ipynb
yangzhou95/notes
b. If we attempt to access a data item with a key that is not part of the dictio- nary, we get an error:
dict['service']
_____no_output_____
Apache-2.0
Chapter7.ipynb
yangzhou95/notes
c. The best way to check if a dic- tionary has a specific key is to use the in or not in operators
'service' in dict2
_____no_output_____
Apache-2.0
Chapter7.ipynb
yangzhou95/notes
d. number can be the keys for dictionary
dict3 = {3.2: 'xyz', 1: 'abc', '1': 3.14159}
_____no_output_____
Apache-2.0
Chapter7.ipynb
yangzhou95/notes
e. Not allowing keys to change during execution makes sense keys must be hashable, so numbers and strings are fine, but lists and other dictionaries are not. 7. update and add new dictionary
dict2['port'] = 6969 # update existing entry or add new entry
_____no_output_____
Apache-2.0
Chapter7.ipynb
yangzhou95/notes
a. the string format operator (%) is specific for dictionary
print('host %(name)s is running on port %(port)d' % dict2) dict2
_____no_output_____
Apache-2.0
Chapter7.ipynb
yangzhou95/notes
b. You may also add the contents of an entire dictionary to another dictionary by using the update() built-in method.3 8. remove dictionary elements: a. use the del statement to delete an entire dictionary
del dict2['name'] # remove entry with key 'name' dict2.pop('port') # remove and return entry with key adict.clear() # remove all entries in adict del bdict # delete entire dictionary
_____no_output_____
Apache-2.0
Chapter7.ipynb
yangzhou95/notes
Note: dict() is now a type and factory function, overriding it may cause you headaches and potential bugsDo NOT create variables with built-in names like: dict, list, file, bool, str, input, or len! 9.Dictionaries will work with all of the standard type operators but do not support operations such as concatenation an...
adict={"k":2} adict["k"] = 3 # set value in dictionary. Dictionary Key-Lookup Operator ( [ ] ) cdict = {'fruits':1} ddict = {'fruits':1}
_____no_output_____
Apache-2.0
Chapter7.ipynb
yangzhou95/notes
10. dict() function a. The dict() factory function is used for creating dictionaries. If no argument is provided, then an empty dictionary is created. The fun happens when a container object is passed in as an argument to dict(). dict()* dict() -> new empty dictionary* dict(mapping) -> new dictionary initialized fro...
dict() dict({'k':1,'k2':2}) dict([(1,2),(2,3)]) dict(((1,2),(2,3))) dict(([2,3],[3,4])) dict(zip(('x','y'),(1,2)))
_____no_output_____
Apache-2.0
Chapter7.ipynb
yangzhou95/notes
11. If it is a(nother) mapping object, i.e., a dictionary, then dict() will just create a new dictionary and copy the contents of the existing one. The new dictionary is actually a shallow copy of the original one and the same results can be accomplished by using a dictionaryโ€™s copy() built-in method. Because creating...
dict7=dict(x=1, y=2) dict8 = dict(x=1, y=2) dict9 = dict(**dict8) # not a realistic example, better use copy() dict10=dict(dict7) dict9 dict10 dict9 = dict8.copy() # better than dict9 = dict(**dict8)
_____no_output_____
Apache-2.0
Chapter7.ipynb
yangzhou95/notes
13.The len() BIF is flexible. It works with sequences, mapping types, and sets
dict2 = {'name': 'earth', 'port': 80} len(dict2)
_____no_output_____
Apache-2.0
Chapter7.ipynb
yangzhou95/notes
14. We can see that above, when referencing dict2, the items are listed in reverse order from which they were entered into the dictionary. ??????
dict2 = {'name': 'earth', 'port': 80} dict2
_____no_output_____
Apache-2.0
Chapter7.ipynb
yangzhou95/notes
15.The hash() BIF is not really meant to be used for dictionaries per se, but it can be used to determine whether an object is fit to be a dictionary key (or not).* Given an object as its argument, hash() returns the hash value of that object.* Numeric val- ues that are equal hash to the same value.* A TypeError will ...
hash([]) dict2={} dict2[{}]="foo"
_____no_output_____
Apache-2.0
Chapter7.ipynb
yangzhou95/notes
16. Mapping Type Built-in Methods* has_key() and its replacements in and not in* keys(), which returns a list of the dictionaryโ€™s keys, * values(), which returns a list of the dictionaryโ€™s values, and* items(), which returns a list of (key, value) tuple pairs.
dict2={"k1":1,"k2":2,"k3":3} for eachKey in dict2.keys(): print(eachKey,dict2[eachKey])
k1 1 k2 2 k3 3
Apache-2.0
Chapter7.ipynb
yangzhou95/notes
* dict.fromkeysc (seq, val=None): create dict where all the key in seq have teh same value val
{}.fromkeys(("k1","k2","3"),None) # fromkeysc(seq, val=None)
_____no_output_____
Apache-2.0
Chapter7.ipynb
yangzhou95/notes
* get(key,default=None): return the value corresponding to key, otherwise return None if key is not in dictionary * dict.setdefault (key, default=None): Similar to get(), but sets dict[key]=default if key is not already in dict * dict.setdefault(key, default=None): Add the key-value pairs of dict2 to dict * keys() ...
for eachKey in sorted(dict2): print(eachKey,dict2[eachKey])
k1 1 k2 2 k3 3
Apache-2.0
Chapter7.ipynb
yangzhou95/notes
* The update() method can be used to add the contents of one dictionary to another. Any existing entries with duplicate keys will be overridden by the new incoming entries. Nonexistent ones will be added. All entries in a dictio- nary can be removed with the clear() method.
dict2 dict3={"k1":"ka","kb":"kb"} dict2.update(dict3) dict2 dict3.clear() dict3 del dict3 dict3
_____no_output_____
Apache-2.0
Chapter7.ipynb
yangzhou95/notes
* The copy() method simply returns a copy of a dictionary. * the get() method is similar to using the key-lookup operator ( [ ] ), but allows you to provide a default value returned if a key does not exist.
dict2 dict4=dict2.copy() dict4 dict4.get('xgag') type(dict4.get("agasg")) type(dict4.get("agasg", "no such key")) dict2
_____no_output_____
Apache-2.0
Chapter7.ipynb
yangzhou95/notes
* f the dictionary does not have the key you are seeking, you want to set a default value and then return it. That is precisely what setdefault() does
dict2.setdefault('kk','k1') dict2
_____no_output_____
Apache-2.0
Chapter7.ipynb
yangzhou95/notes
* Currently,thekeys(),items(),andvalues()methodsreturnlists. This can be unwieldy if such data collections are large, and the main reason why iteritems(), iterkeys(), and itervalues() were added to Python * In python3, iter*() names are no longer supported. The new keys(), values(), and items() all return views * Wh...
dict1 = {' foo':789, 'foo': 'xyz'} dict1 dict1['foo']
_____no_output_____
Apache-2.0
Chapter7.ipynb
yangzhou95/notes
* most Python objects can serve as keys; however they have to be hashable objectsโ€”mutable types such as lists and dictionaries are disallowed because they cannot be hashed* All immutable types are hashable* Numbers of the same value represent the same key. In other words, the integer 1 and the float 1.0 hash to the sa...
s1=set('asgag') s2=frozenset('sbag') len(s1) type(s1) type(s2) len(s2)
_____no_output_____
Apache-2.0
Chapter7.ipynb
yangzhou95/notes
f. iterate over set or check if an item is a member of a set
'k' in s1
_____no_output_____
Apache-2.0
Chapter7.ipynb
yangzhou95/notes
g. update set
s1.add('z') s1 s1.update('abc') s1 s1.remove('a') s1
_____no_output_____
Apache-2.0
Chapter7.ipynb
yangzhou95/notes
h.As mentioned before, only mutable sets can be updated. Any attempt at such operations on immutable sets is met with an exception
s2.add('c')
_____no_output_____
Apache-2.0
Chapter7.ipynb
yangzhou95/notes
i. mixed set type operation
type(s1|s2) # set | frozenset, mix operation s3=frozenset('agg') #frozenset type(s2|s3)
_____no_output_____
Apache-2.0
Chapter7.ipynb
yangzhou95/notes
j. update mutable set: (Union) Update ( |= )
s=set('abc') s1=set("123") s |=s1 s
_____no_output_____
Apache-2.0
Chapter7.ipynb
yangzhou95/notes
k.The retention (or intersection update) operation keeps only the existing set members that are also elements of the other set. The method equivalent is intersection_update()
s=set('abc') s1=set('ab') s &=s1 s
_____no_output_____
Apache-2.0
Chapter7.ipynb
yangzhou95/notes
l.The difference update operation returns a set whose elements are members of the original set after removing elements that are (also) members of the other set. The method equivalent is difference_update().
s = set('cheeseshop') s u = frozenset(s) s -= set('shop') s
_____no_output_____
Apache-2.0
Chapter7.ipynb
yangzhou95/notes
m.The symmetric difference update operation returns a set whose members are either elements of the original or other set but not both. The method equiva- lent is symmetric_difference_update()
s=set('cheeseshop') s u=set('bookshop') u s ^=u s vari='abc' set(vari) # vari must be iterable
_____no_output_____
Apache-2.0
Chapter7.ipynb
yangzhou95/notes
Multiple Linear Regression with Normalize Data
# Importing the libraries import pandas as pd import numpy as np import matplotlib.pyplot as plt import warnings warnings.filterwarnings("ignore") # fix_yahoo_finance is used to fetch data import fix_yahoo_finance as yf yf.pdr_override() # input symbol = 'AMD' start = '2014-01-01' end = '2018-08-27' # Read data da...
Multiple Linear Score: 0.0145752513278
MIT
Stock_Algorithms/Multiple_Linear_Regression_with_Normalize_Data.ipynb
NTForked-ML/Deep-Learning-Machine-Learning-Stock
Chapter 7. ํ…์ŠคํŠธ ๋ฌธ์„œ์˜ ๋ฒ”์ฃผํ™” - (4) IMDB ์ „์ฒด ๋ฐ์ดํ„ฐ๋กœ ์ „์ดํ•™์Šต- ์•ž์„  ์ „์ดํ•™์Šต ์‹ค์Šต๊ณผ๋Š” ๋‹ฌ๋ฆฌ, IMDB ์˜ํ™”๋ฆฌ๋ทฐ ๋ฐ์ดํ„ฐ์…‹ ์ „์ฒด๋ฅผ ์‚ฌ์šฉํ•˜๋ฉฐ ๋ฌธ์žฅ ์ˆ˜๋Š” 10๊ฐœ -> 20๊ฐœ๋กœ ์กฐ์ •ํ•œ๋‹ค- IMDB ์˜ํ™” ๋ฆฌ๋ทฐ ๋ฐ์ดํ„ฐ๋ฅผ ๋‹ค์šด๋กœ๋“œ ๋ฐ›์•„ data ๋””๋ ‰ํ† ๋ฆฌ์— ์••์ถ• ํ•ด์ œํ•œ๋‹ค - ๋‹ค์šด๋กœ๋“œ : http://ai.stanford.edu/~amaas/data/sentiment/ - ์ €์žฅ๊ฒฝ๋กœ : data/aclImdb
import os import config from dataloader.loader import Loader from preprocessing.utils import Preprocess, remove_empty_docs from dataloader.embeddings import GloVe from model.cnn_document_model import DocumentModel, TrainingParameters from keras.callbacks import ModelCheckpoint, EarlyStopping import numpy as np
Using TensorFlow backend.
MIT
Chapter07/HandsOn-04_Transfer_with_IMDB_full_model.ipynb
wikibook/transfer-learning
ํ•™์Šต ํŒŒ๋ผ๋ฏธํ„ฐ ์„ค์ •
# ํ•™์Šต๋œ ๋ชจ๋ธ์„ ์ €์žฅํ•  ๋””๋ ‰ํ† ๋ฆฌ ์ƒ์„ฑ if not os.path.exists(os.path.join(config.MODEL_DIR, 'imdb')): os.makedirs(os.path.join(config.MODEL_DIR, 'imdb')) # ํ•™์Šต ํŒŒ๋ผ๋ฏธํ„ฐ ์„ค์ • train_params = TrainingParameters('imdb_transfer_tanh_activation', model_file_path = config.MODEL_DIR+ '/imdb/full_model_10.hdf5',...
_____no_output_____
MIT
Chapter07/HandsOn-04_Transfer_with_IMDB_full_model.ipynb
wikibook/transfer-learning
IMDB ๋ฐ์ดํ„ฐ์…‹ ๋กœ๋“œ
# ๋‹ค์šด๋ฐ›์€ IMDB ๋ฐ์ดํ„ฐ ๋กœ๋“œ: ํ•™์Šต์…‹ ์ „์ฒด ์‚ฌ์šฉ train_df = Loader.load_imdb_data(directory = 'train') # train_df = train_df.sample(frac=0.05, random_state = train_params.seed) print(f'train_df.shape : {train_df.shape}') test_df = Loader.load_imdb_data(directory = 'test') print(f'test_df.shape : {test_df.shape}') # ํ…์ŠคํŠธ ๋ฐ์ดํ„ฐ, ๋ ˆ์ด๋ธ” ์ถ”์ถœ corp...
train_df.shape : (25000, 2) test_df.shape : (25000, 2) corpus size : 25000 target size : 25000
MIT
Chapter07/HandsOn-04_Transfer_with_IMDB_full_model.ipynb
wikibook/transfer-learning
์ธ๋ฑ์Šค ์‹œํ€€์Šค ์ƒ์„ฑ
# ์•ž์„  ์ „์ดํ•™์Šต ์‹ค์Šต๊ณผ ๋‹ฌ๋ฆฌ, ๋ฌธ์žฅ ๊ฐœ์ˆ˜๋ฅผ 10๊ฐœ -> 20๊ฐœ๋กœ ์ƒํ–ฅ Preprocess.NUM_SENTENCES = 20 # ํ•™์Šต์…‹์„ ์ธ๋ฑ์Šค ์‹œํ€€์Šค๋กœ ๋ณ€ํ™˜ preprocessor = Preprocess(corpus=corpus) corpus_to_seq = preprocessor.fit() print(f'corpus_to_seq size : {len(corpus_to_seq)}') print(f'corpus_to_seq[0] size : {len(corpus_to_seq[0])}') # ํ…Œ์ŠคํŠธ์…‹์„ ์ธ๋ฑ์Šค ์‹œํ€€์Šค๋กœ ๋ณ€ํ™˜ test_corpus = test_df['r...
x_train.shape : (25000, 600) y_train.shape : (25000,) x_test.shape : (25000, 600) y_test.shape : (25000,)
MIT
Chapter07/HandsOn-04_Transfer_with_IMDB_full_model.ipynb
wikibook/transfer-learning
GloVe ์ž„๋ฒ ๋”ฉ ์ดˆ๊ธฐํ™”
# GloVe ์ž„๋ฒ ๋”ฉ ์ดˆ๊ธฐํ™” - glove.6B.50d.txt pretrained ๋ฒกํ„ฐ ์‚ฌ์šฉ glove = GloVe(50) initial_embeddings = glove.get_embedding(preprocessor.word_index) print(f'initial_embeddings.shape : {initial_embeddings.shape}')
Reading 50 dim GloVe vectors Found 400000 word vectors. words not found in embeddings: 499 initial_embeddings.shape : (28656, 50)
MIT
Chapter07/HandsOn-04_Transfer_with_IMDB_full_model.ipynb
wikibook/transfer-learning
ํ›ˆ๋ จ๋œ ๋ชจ๋ธ ๋กœ๋“œ- HandsOn03์—์„œ ์•„๋งˆ์กด ๋ฆฌ๋ทฐ ๋ฐ์ดํ„ฐ๋กœ ํ•™์Šตํ•œ CNN ๋ชจ๋ธ์„ ๋กœ๋“œํ•œ๋‹ค.- DocumentModel ํด๋ž˜์Šค์˜ load_model๋กœ ๋ชจ๋ธ์„ ๋กœ๋“œํ•˜๊ณ , load_model_weights๋กœ ํ•™์Šต๋œ ๊ฐ€์ค‘์น˜๋ฅผ ๊ฐ€์ ธ์˜จ๋‹ค. - ๊ทธ ํ›„, GloVe.update_embeddings ํ•จ์ˆ˜๋กœ GloVe ์ดˆ๊ธฐํ™” ์ž„๋ฒ ๋”ฉ์„ ์—…๋ฐ์ดํŠธํ•œ๋‹ค
# ๋ชจ๋ธ ํ•˜์ดํผํŒŒ๋ผ๋ฏธํ„ฐ ๋กœ๋“œ model_json_path = os.path.join(config.MODEL_DIR, 'amazonreviews/model_06.json') amazon_review_model = DocumentModel.load_model(model_json_path) # ๋ชจ๋ธ ๊ฐ€์ค‘์น˜ ๋กœ๋“œ model_hdf5_path = os.path.join(config.MODEL_DIR, 'amazonreviews/model_06.hdf5') amazon_review_model.load_model_weights(model_hdf5_path) # ๋ชจ๋ธ ์ž„๋ฒ ๋”ฉ ๋ ˆ...
learned_embeddings size : 43197 23629 words are updated out of 28654
MIT
Chapter07/HandsOn-04_Transfer_with_IMDB_full_model.ipynb
wikibook/transfer-learning
IMDB ์ „์ดํ•™์Šต ๋ชจ๋ธ ์ƒ์„ฑ
# ๋ถ„๋ฅ˜ ๋ชจ๋ธ ์ƒ์„ฑ : IMDB ๋ฆฌ๋ทฐ ๋ฐ์ดํ„ฐ๋ฅผ ์ž…๋ ฅ๋ฐ›์•„ ์ด์ง„๋ถ„๋ฅ˜๋ฅผ ์ˆ˜ํ–‰ํ•˜๋Š” ๋ชจ๋ธ ์ƒ์„ฑ imdb_model = DocumentModel(vocab_size=preprocessor.get_vocab_size(), word_index = preprocessor.word_index, num_sentences=Preprocess.NUM_SENTENCES, embedding_weights=initial_embeddings, ...
Vocab Size = 28656 and the index of vocabulary words passed has 28654 words
MIT
Chapter07/HandsOn-04_Transfer_with_IMDB_full_model.ipynb
wikibook/transfer-learning
๋ชจ๋ธ ํ•™์Šต ๋ฐ ํ‰๊ฐ€
# ๋ชจ๋ธ ์ปดํŒŒ์ผ imdb_model.get_classification_model().compile(loss="binary_crossentropy", optimizer='rmsprop', metrics=["accuracy"]) # callback (1) - ์ฒดํฌํฌ์ธํŠธ checkpointer = ModelCheckpoint(filepath=train_params.model_file...
_____no_output_____
MIT
Chapter07/HandsOn-04_Transfer_with_IMDB_full_model.ipynb
wikibook/transfer-learning
**Basic chatbot**
import ast from google.colab import drive questions = [] answers = [] drive.mount("/content/drive") with open("/content/drive/My Drive/data/chatbot/qa_Electronics.json") as f: for line in f: data = ast.literal_eval(line) questions.append(data["question"].lower()) answers.append(data["answer"].lower()) f...
Please enter your username: pepe Q&A support: Hi, welcome to Q&A support. How can I help you? pepe: I want to buy an iPhone Q&A support: i am sure amazon has all types.
Apache-2.0
3.Statistical_NLP/2_chatbot.ipynb
bonigarcia/nlp-examples
Lgbm and Optuna* changed with cross validation
import pandas as pd import numpy as np # the GBM used mport xgboost as xgb import catboost as cat import lightgbm as lgb from sklearn.model_selection import cross_validate from sklearn.metrics import make_scorer # to encode categoricals from sklearn.preprocessing import LabelEncoder # see utils.py from utils import...
_____no_output_____
MIT
.ipynb_checkpoints/lgbm-optuna-cross-validate-checkpoint.ipynb
luigisaetta/bike-sharing-forecast
train the model on entire train set and save
%%time # maybe I shoud add save best model (see nu_iteration in cell below) model = lgb.LGBMRegressor(**study.best_params) model.fit(X, y) model_file = "lgboost.txt" model.booster_.save_model(model_file, num_iteration=study.best_params['num_iterations'])
_____no_output_____
MIT
.ipynb_checkpoints/lgbm-optuna-cross-validate-checkpoint.ipynb
luigisaetta/bike-sharing-forecast
TensorFlow Tutorial 01 Simple Linear Modelby [Magnus Erik Hvass Pedersen](http://www.hvass-labs.org/)/ [GitHub](https://github.com/Hvass-Labs/TensorFlow-Tutorials) / [Videos on YouTube](https://www.youtube.com/playlist?list=PL9Hr9sNUjfsmEu1ZniY0XpHSzl5uihcXZ) IntroductionThis tutorial demonstrates the basic workflow ...
%matplotlib inline import matplotlib.pyplot as plt from matplotlib.colors import LogNorm import tensorflow as tf import numpy as np from sklearn.metrics import confusion_matrix
/home/magnus/anaconda3/envs/tf-gpu/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_con...
MIT
01_Simple_Linear_Model.ipynb
Asciotti/TensorFlow-Tutorials
This was developed using Python 3.6 (Anaconda) and TensorFlow version:
tf.__version__
_____no_output_____
MIT
01_Simple_Linear_Model.ipynb
Asciotti/TensorFlow-Tutorials
Load Data The MNIST data-set is about 12 MB and will be downloaded automatically if it is not located in the given path.
from mnist import MNIST data = MNIST(data_dir="data/MNIST/")
_____no_output_____
MIT
01_Simple_Linear_Model.ipynb
Asciotti/TensorFlow-Tutorials
The MNIST data-set has now been loaded and consists of 70.000 images and class-numbers for the images. The data-set is split into 3 mutually exclusive sub-sets. We will only use the training and test-sets in this tutorial.
print("Size of:") print("- Training-set:\t\t{}".format(data.num_train)) print("- Validation-set:\t{}".format(data.num_val)) print("- Test-set:\t\t{}".format(data.num_test))
Size of: - Training-set: 55000 - Validation-set: 5000 - Test-set: 10000
MIT
01_Simple_Linear_Model.ipynb
Asciotti/TensorFlow-Tutorials
Copy some of the data-dimensions for convenience.
# The images are stored in one-dimensional arrays of this length. img_size_flat = data.img_size_flat # Tuple with height and width of images used to reshape arrays. img_shape = data.img_shape # Number of classes, one class for each of 10 digits. num_classes = data.num_classes
_____no_output_____
MIT
01_Simple_Linear_Model.ipynb
Asciotti/TensorFlow-Tutorials
One-Hot Encoding The output-data is loaded as both integer class-numbers and so-called One-Hot encoded arrays. This means the class-numbers have been converted from a single integer to a vector whose length equals the number of possible classes. All elements of the vector are zero except for the $i$'th element which i...
data.y_test[0:5, :]
_____no_output_____
MIT
01_Simple_Linear_Model.ipynb
Asciotti/TensorFlow-Tutorials
We also need the classes as integers for various comparisons and performance measures. These can be found from the One-Hot encoded arrays by taking the index of the highest element using the `np.argmax()` function. But this has already been done for us when the data-set was loaded, so we can see the class-number for th...
data.y_test_cls[0:5]
_____no_output_____
MIT
01_Simple_Linear_Model.ipynb
Asciotti/TensorFlow-Tutorials