markdown
stringlengths 0
37k
| code
stringlengths 1
33.3k
| path
stringlengths 8
215
| repo_name
stringlengths 6
77
| license
stringclasses 15
values |
---|---|---|---|---|
Connection
You use a connection.Session to interact with the Ovaiton REST API. Use the connect method to create an authenticated Session. You can provide your Ovation password with the password= parameter, but please keep your Ovation password secure. Don't put your password in your source code. It's much better to let connect prompt you for your password when needed. For scripts run on the server, it's best to provide your password via an environment variable:
connect(my_email, password=os.environ['OVATION_PASSWORD'])
for example. | session = connect(input('Email: '), org=int(input("Organization (enter for default): ") or 0)) | examples/attributes-and-annotations.ipynb | physion/ovation-python | gpl-3.0 |
Attributes
Ovation entities have an attributes object for user data. For example, the Ovation web app uses the attributes object to store the name of a Folder or File. You can see the names of these 'built-in' attributes for each entity at https://api.ovation.io/index.html.
You can update the attributes of an entity by modifying the attributes object and PUTing the entity. | project_id = input('Project UUID: ')
project = session.get(session.path('projects', id=project_id))
pprint(project)
# Add a new attribute
project.attributes.my_attribute = 'Wow!'
# PUT the entity to save it
project = session.put(project.links.self, entity=project)
pprint(project) | examples/attributes-and-annotations.ipynb | physion/ovation-python | gpl-3.0 |
You can delete attributes by removing them from the attributes object. | # Remove an attribute
del project.attributes['my_attribute']
# PUT the entity to save it
project = session.put(project.links.self, entity=project) | examples/attributes-and-annotations.ipynb | physion/ovation-python | gpl-3.0 |
Annotations
Unlike attributes which must have a single value for an entity, annotations any user to add their own information to an entity. User annotations are kept separate, so one user's annotation can't interfere with an other user's. Anyone with permission to see an entity can read all annotations on that entity, however.
Annotations can be keyword tags, properties (key-value pairs), text notes, and events. | # Create a new keyword tag
session.post(project.links.tags, data={'tags': [{'tag': 'mytag'}]})
# Get the tags for project
tags = session.get(project.links.tags)
pprint(tags)
# Delete a tag
session.delete(project.links.tags + "/" + tags[0]._id) | examples/attributes-and-annotations.ipynb | physion/ovation-python | gpl-3.0 |
Load the data | #code here
#train = pd.read_csv | product-buy/notebook/propensity_to_buy.ipynb | amitkaps/full-stack-data-science | mit |
3. Refine | # View the first few rows
# What are the columns
# What are the column types?
# How many observations are there?
# View summary of the raw data
# Check for missing values. If they exist, treat them
| product-buy/notebook/propensity_to_buy.ipynb | amitkaps/full-stack-data-science | mit |
4. Explore | # Single variate analysis
# histogram of target variable
# Bi-variate analysis
| product-buy/notebook/propensity_to_buy.ipynb | amitkaps/full-stack-data-science | mit |
5. Transform | # encode the categorical variables
| product-buy/notebook/propensity_to_buy.ipynb | amitkaps/full-stack-data-science | mit |
6. Model | # Create train-test dataset
# Build decision tree model - depth 2
# Find accuracy of model
# Visualize decision tree
# Build decision tree model - depth none
# find accuracy of model
# Build random forest model
# Find accuracy model
# Bonus: Do cross-validation
| product-buy/notebook/propensity_to_buy.ipynb | amitkaps/full-stack-data-science | mit |
Create Date And Time Data | # Create dates
dates = pd.Series(pd.date_range('2/2/2002', periods=3, freq='M'))
# View data
dates | machine-learning/encode_days_of_the_week.ipynb | tpin3694/tpin3694.github.io | mit |
Show Days Of The Week | # Show days of the week
dates.dt.weekday_name | machine-learning/encode_days_of_the_week.ipynb | tpin3694/tpin3694.github.io | mit |
Problem 1: Processing Tabular Data from File
In this problem, we practice reading csv formatted data and doing some very simple data exploration.
Part (a): Reading CSV Data with Numpy
Open the file $\mathtt{dataset}$_$\mathtt{HW0.txt}$, containing birth biometrics as well as maternal data for a number of U.S. births, and inspect the csv formatting of the data. Load the data, without the column headers, into an numpy array.
Do some preliminary explorations of the data by printing out the dimensions as well as the first three rows of the array. Finally, for each column, print out the range of the values.
<b>Prettify your output</b>, add in some text and formatting to make sure your outputs are readable (e.g. "36x4" is less readable than "array dimensions: 36x4"). | #create a variable for the file dataset_HW0.txt
fname = 'dataset_HW0.txt'
#fname
# Option 1: Open the file and load the data into the numpy array; skip the headers
with open(fname) as f:
lines = (line for line in f if not line.startswith('#'))
data = np.loadtxt(lines, delimiter=',', skiprows=1)
# What is the shape of the data
data.shape
#Option 2: Open the file and load the data into the numpy array; skip the headers
data = np.loadtxt('dataset_HW0.txt', delimiter=',', skiprows=1)
data.shape
# print the first 3 rows of the data
data[0:3]
#data[:,0]
# show the range of values for birth weight
fig = plt.figure()
axes = fig.add_subplot(111)
plt.xlabel("birth weight")
axes.hist(data[:,0])
# show the range of values for the femur length
fig = plt.figure()
axes = fig.add_subplot(111)
plt.xlabel("femur length")
axes.hist(data[:,1]) | Datascience_Lab0.ipynb | scheema/Machine-Learning | mit |
Part (b): Simple Data Statistics
Compute the mean birth weight and mean femur length for the entire dataset. Now, we want to split the birth data into three groups based on the mother's age:
Group I: ages 0-17
Group II: ages 18-34
Group III: ages 35-50
For each maternal age group, compute the mean birth weight and mean femure length.
<b>Prettify your output.</b>
Compare the group means with each other and with the overall mean, what can you conclude? | #calculate the overall means
birth_weight_mean = data[:,0].mean()
birth_weight_mean
#calculagte the overall mean for Femur Length
femur_length_mean = data[:,1].mean()
femur_length_mean
# Capture the birth weight
birth_weight = data[:,0]
#Capture the Femur length
femur_length = data[:,1]
# Capture the maternal age
maternal_age = data[:,2]
maternal_age.shape
# Create indexes for the different maternal age groups
#group_1
group_1 = maternal_age <= 17
#group_2
group_2 = [(maternal_age >= 18) & (maternal_age <= 34)]
#group_3
group_3 = [(maternal_age >= 35) & (maternal_age <= 50)]
bw_g1 = data[:, 0][group_1]
age0_17 = data[:, 2][group_1]
bw_g1.mean()
fl_g1 = data[:, 1][group_1]
fl_g1.mean()
bw_g2 = data[:, 0][group_2]
age18_34 = data[:, 2][group_2]
bw_g2.mean()
fl_g2 = data[:, 1][group_2]
fl_g2.mean()
bw_g3 = data[:, 0][group_3]
age35_50 = data[:, 2][group_3]
bw_g3.mean()
fl_g3 = data[:, 1][group_3]
fl_g3.mean() | Datascience_Lab0.ipynb | scheema/Machine-Learning | mit |
Part (c): Simple Data Visualization
Visualize the data using a 3-D scatter plot (label the axes and title your plot). How does your visual analysis compare with the stats you've computed in Part (b)? |
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
for c, m in [('r', 'o')]:
ax.scatter(bw_g1, fl_g1, age0_17, edgecolor=c,facecolors=(0,0,0,0), marker=m, s=40)
for c, m in [('b', 's')]:
ax.scatter(bw_g2, fl_g2, age18_34, edgecolor=c,facecolors=(0,0,0,0), marker=m, s=40)
for c, m in [('g', '^')]:
ax.scatter(bw_g3, fl_g3, age35_50, edgecolor=c,facecolors=(0,0,0,0), marker=m, s=40)
fig.suptitle('3D Data Visualization', fontsize=14, fontweight='bold')
ax.set_title('Birth Weigth vs Femur Length vs Weight Plot')
ax.set_xlabel('birth_weight')
ax.set_ylabel('femur_length')
ax.set_zlabel('maternal_age')
plt.show() | Datascience_Lab0.ipynb | scheema/Machine-Learning | mit |
Part (d): Simple Data Visualization (Continued)
Visualize two data attributes at a time,
maternal age against birth weight
maternal age against femur length
birth weight against femur length
using 2-D scatter plots.
Compare your visual analysis with your analysis from Part (b) and (c). | plt.scatter(maternal_age,birth_weight, color='r', marker='o')
plt.xlabel("maternal age")
plt.ylabel("birth weight")
plt.show()
plt.scatter(maternal_age,femur_length, color='b', marker='s')
plt.xlabel("maternal age")
plt.ylabel("femur length")
plt.show()
plt.scatter(birth_weight,femur_length, color='g', marker='^')
plt.xlabel("birth weight")
plt.ylabel("femur length")
plt.show() | Datascience_Lab0.ipynb | scheema/Machine-Learning | mit |
Problem 2: Processing Web Data
In this problem we practice some basic web-scrapping using Beautiful Soup.
Part (a): Opening and Reading Webpages
Open and load the page (Kafka's The Metamorphosis) at
$\mathtt{http://www.gutenberg.org/files/5200/5200-h/5200-h.htm}$
into a BeautifulSoup object.
The object we obtain is a parse tree (a data structure representing all tags and relationship between tags) of the html file. To concretely visualize this object, print out the first 1000 characters of a representation of the parse tree using the $\mathtt{prettify()}$ function. | # load the file into a beautifulsoup object
page = urllib.request.urlopen("http://www.gutenberg.org/files/5200/5200-h/5200-h.htm").read()
# prettify the data read from the url and print the first 1000 characters
soup = BeautifulSoup(page, "html.parser")
print(soup.prettify()[0:1000]) | Datascience_Lab0.ipynb | scheema/Machine-Learning | mit |
Part (b): Exploring the Parsed HTML
Explore the nested data structure you obtain in Part (a) by printing out the following:
the content of the head tag
the string inside the head tag
each child of the head tag
the string inside the title tag
the string inside the preformatted text (pre) tag
the string inside the first paragraph (p) tag
Make your output readable. | # print the content of the head tag
soup.head
# print the string inside the head tag
soup.head.title
# print each child of the head tag
soup.head.meta
# print the string inside the title tag
soup.head.title.string
# print the string inside the pre-formatbted text (pre) tag
print(soup.body.pre.string)
# print the string inside first paragraph (p) tag
print(soup.body.p.string) | Datascience_Lab0.ipynb | scheema/Machine-Learning | mit |
Part (c): Extracting Text
Now we want to extract the text of The Metamorphosis and do some simple analysis. Beautiful Soup provides a way to extract all text from a webpage via the $\mathtt{get}$_$\mathtt{text()}$ function.
Print the first and last 1000 characters of the text returned by $\mathtt{get}$_$\mathtt{text()}$. Is this the content of the novela? Where is the content of The Metamorphosis stored in the BeautifulSoup object? | print(soup.get_text()[1:1000]) | Datascience_Lab0.ipynb | scheema/Machine-Learning | mit |
Part (d): Extracting Text (Continued)
Using the $\mathtt{find}$_$\mathtt{all()}$ function, extract the text of The Metamorphosis and concatenate the result into a single string. Print out the first 1000 characters of the string as a sanity check. | p = soup.find_all('p')
combined_text = ''
for node in soup.findAll('p'):
combined_text += "".join(node.findAll(text=True))
print(combined_text[0:1000])
| Datascience_Lab0.ipynb | scheema/Machine-Learning | mit |
Part (e): Word Count
Count the number of words in The Metamorphosis. Compute the average word length and plot a histogram of word lengths.
You'll need to adjust the number of bins for each histogram.
Hint: You'll need to pre-process the text in order to obtain the correct word/sentence length and count. | word_list = combined_text.lower().replace(':','').replace('.','').replace(',', '').replace('"','').replace('!','').replace('?','').replace(';','').split()
#print(word_list[0:100])
word_length = [len(n) for n in word_list]
print(word_length[0:100])
total_word_length = sum(word_length)
print("The total word length: ", total_word_length)
wordcount = len(word_list)
print("The total number of words: ", wordcount)
avg_word_length = total_word_length / wordcount
print("The average word length is: ", avg_word_length)
# function to calculate the number of uniques words
# wordcount = {}
# for word in word_list:
# if word not in wordcount:
# wordcount[word] = 1
# else:
# wordcount[word] += 1
# for k,v in wordcount.items():
# print (len(k), v)
# Print the histogram for the word lengths
fig = plt.figure()
axes = fig.add_subplot(111)
plt.xlabel("Word Lengths")
plt.xlabel("Count")
#axes.hist(word_length)
plt.hist(word_length, bins=np.arange(min(word_length), max(word_length) + 1, 1)) | Datascience_Lab0.ipynb | scheema/Machine-Learning | mit |
3. Affine decomposition
In order to obtain an affine decomposition, we proceed as in the previous tutorial and recast the problem on a fixed, parameter independent, reference domain $\Omega$. As reference domain which choose the one characterized by $\mu_0 = 1$ which we generate through the generate_mesh notebook provided in the data folder.
As in the previous tutorial, we pull back the problem to the reference domain $\Omega$. | @SCM()
@PullBackFormsToReferenceDomain()
@ShapeParametrization(
("x[0]", "x[1]"), # subdomain 1
("mu[0]*(x[0] - 1) + 1", "x[1]"), # subdomain 2
)
class Graetz(EllipticCoerciveProblem):
# Default initialization of members
@generate_function_space_for_stability_factor
def __init__(self, V, **kwargs):
# Call the standard initialization
EllipticCoerciveProblem.__init__(self, V, **kwargs)
# ... and also store FEniCS data structures for assembly
assert "subdomains" in kwargs
assert "boundaries" in kwargs
self.subdomains, self.boundaries = kwargs["subdomains"], kwargs["boundaries"]
self.u = TrialFunction(V)
self.v = TestFunction(V)
self.dx = Measure("dx")(subdomain_data=subdomains)
self.ds = Measure("ds")(subdomain_data=boundaries)
# Store the velocity expression
self.vel = Expression("x[1]*(1-x[1])", element=self.V.ufl_element())
# Customize eigen solver parameters
self._eigen_solver_parameters.update({
"bounding_box_minimum": {
"problem_type": "gen_hermitian", "spectral_transform": "shift-and-invert",
"spectral_shift": 1.e-5, "linear_solver": "mumps"
},
"bounding_box_maximum": {
"problem_type": "gen_hermitian", "spectral_transform": "shift-and-invert",
"spectral_shift": 1.e5, "linear_solver": "mumps"
},
"stability_factor": {
"problem_type": "gen_hermitian", "spectral_transform": "shift-and-invert",
"spectral_shift": 1.e-5, "linear_solver": "mumps"
}
})
# Return custom problem name
def name(self):
return "Graetz2"
# Return theta multiplicative terms of the affine expansion of the problem.
@compute_theta_for_stability_factor
def compute_theta(self, term):
mu = self.mu
if term == "a":
theta_a0 = mu[1]
theta_a1 = 1.0
return (theta_a0, theta_a1)
elif term == "f":
theta_f0 = 1.0
return (theta_f0, )
elif term == "dirichlet_bc":
theta_bc0 = mu[2]
theta_bc1 = mu[3]
return (theta_bc0, theta_bc1)
else:
raise ValueError("Invalid term for compute_theta().")
# Return forms resulting from the discretization of the affine expansion of the problem operators.
@assemble_operator_for_stability_factor
def assemble_operator(self, term):
v = self.v
dx = self.dx
if term == "a":
u = self.u
vel = self.vel
a0 = inner(grad(u), grad(v)) * dx
a1 = vel * u.dx(0) * v * dx
return (a0, a1)
elif term == "f":
f0 = Constant(0.0) * v * dx
return (f0,)
elif term == "dirichlet_bc":
bc0 = [DirichletBC(self.V, Constant(0.0), self.boundaries, 1),
DirichletBC(self.V, Constant(1.0), self.boundaries, 2),
DirichletBC(self.V, Constant(0.0), self.boundaries, 3),
DirichletBC(self.V, Constant(0.0), self.boundaries, 5),
DirichletBC(self.V, Constant(1.0), self.boundaries, 6),
DirichletBC(self.V, Constant(0.0), self.boundaries, 7),
DirichletBC(self.V, Constant(0.0), self.boundaries, 8)]
bc1 = [DirichletBC(self.V, Constant(0.0), self.boundaries, 1),
DirichletBC(self.V, Constant(0.0), self.boundaries, 2),
DirichletBC(self.V, Constant(1.0), self.boundaries, 3),
DirichletBC(self.V, Constant(1.0), self.boundaries, 5),
DirichletBC(self.V, Constant(0.0), self.boundaries, 6),
DirichletBC(self.V, Constant(0.0), self.boundaries, 7),
DirichletBC(self.V, Constant(0.0), self.boundaries, 8)]
return (bc0, bc1)
elif term == "inner_product":
u = self.u
x0 = inner(grad(u), grad(v)) * dx
return (x0,)
else:
raise ValueError("Invalid term for assemble_operator().") | tutorials/04_graetz/tutorial_graetz_2.ipynb | mathLab/RBniCS | lgpl-3.0 |
4. Main program
4.1. Read the mesh for this problem
The mesh was generated by the data/generate_mesh_2.ipynb notebook. | mesh = Mesh("data/graetz_2.xml")
subdomains = MeshFunction("size_t", mesh, "data/graetz_physical_region_2.xml")
boundaries = MeshFunction("size_t", mesh, "data/graetz_facet_region_2.xml") | tutorials/04_graetz/tutorial_graetz_2.ipynb | mathLab/RBniCS | lgpl-3.0 |
4.3. Allocate an object of the Graetz class | problem = Graetz(V, subdomains=subdomains, boundaries=boundaries)
mu_range = [(0.1, 10.0), (0.01, 10.0), (0.5, 1.5), (0.5, 1.5)]
problem.set_mu_range(mu_range) | tutorials/04_graetz/tutorial_graetz_2.ipynb | mathLab/RBniCS | lgpl-3.0 |
4.4. Prepare reduction with a reduced basis method | reduction_method = ReducedBasis(problem)
reduction_method.set_Nmax(30, SCM=50)
reduction_method.set_tolerance(1e-5, SCM=1e-3) | tutorials/04_graetz/tutorial_graetz_2.ipynb | mathLab/RBniCS | lgpl-3.0 |
4.5. Perform the offline phase | lifting_mu = (1.0, 1.0, 1.0, 1.0)
problem.set_mu(lifting_mu)
reduction_method.initialize_training_set(500, SCM=250)
reduced_problem = reduction_method.offline() | tutorials/04_graetz/tutorial_graetz_2.ipynb | mathLab/RBniCS | lgpl-3.0 |
4.6. Perform an online solve | online_mu = (10.0, 0.01, 1.0, 1.0)
reduced_problem.set_mu(online_mu)
reduced_solution = reduced_problem.solve()
plot(reduced_solution, reduced_problem=reduced_problem) | tutorials/04_graetz/tutorial_graetz_2.ipynb | mathLab/RBniCS | lgpl-3.0 |
11: Largest product in a grid
In the 20Γ20 grid below, four numbers along a diagonal line have been bolded.
\begin{matrix}
08&02&22&97&38&15&00&40&00&75&04&05&07&78&52&12&50&77&91&08\
49&49&99&40&17&81&18&57&60&87&17&40&98&43&69&48&04&56&62&00\
81&49&31&73&55&79&14&29&93&71&40&67&53&88&30&03&49&13&36&65\
52&70&95&23&04&60&11&42&69&24&68&56&01&32&56&71&37&02&36&91\
22&31&16&71&51&67&63&89&41&92&36&54&22&40&40&28&66&33&13&80\
24&47&32&60&99&03&45&02&44&75&33&53&78&36&84&20&35&17&12&50\
32&98&81&28&64&23&67&10&\textbf{26}&38&40&67&59&54&70&66&18&38&64&70\
67&26&20&68&02&62&12&20&95&\textbf{63}&94&39&63&08&40&91&66&49&94&21\
24&55&58&05&66&73&99&26&97&17&\textbf{78}&78&96&83&14&88&34&89&63&72\
21&36&23&09&75&00&76&44&20&45&35&\textbf{14}&00&61&33&97&34&31&33&95\
78&17&53&28&22&75&31&67&15&94&03&80&04&62&16&14&09&53&56&92\
16&39&05&42&96&35&31&47&55&58&88&24&00&17&54&24&36&29&85&57\
86&56&00&48&35&71&89&07&05&44&44&37&44&60&21&58&51&54&17&58\
19&80&81&68&05&94&47&69&28&73&92&13&86&52&17&77&04&89&55&40\
04&52&08&83&97&35&99&16&07&97&57&32&16&26&26&79&33&27&98&66\
88&36&68&87&57&62&20&72&03&46&33&67&46&55&12&32&63&93&53&69\
04&42&16&73&38&25&39&11&24&94&72&18&08&46&29&32&40&62&76&36\
20&69&36&41&72&30&23&88&34&62&99&69&82&67&59&85&74&04&36&16\
20&73&35&29&78&31&90&01&74&31&49&71&48&86&81&16&23&57&05&54\
01&70&54&71&83&51&54&69&16&92&33&48&61&43&52&01&89&19&67&48\
\end{matrix}
The product of these numbers is 26 Γ 63 Γ 78 Γ 14 = 1788696.
What is the greatest product of four adjacent numbers in the same direction (up, down, left, right, or diagonally) in the 20Γ20 grid? | input_mat = np.array([[ 8, 2,22,97,38,15, 0,40, 0,75, 4, 5, 7,78,52,12,50,77,91, 8],
[49,49,99,40,17,81,18,57,60,87,17,40,98,43,69,48, 4,56,62, 0],
[81,49,31,73,55,79,14,29,93,71,40,67,53,88,30, 3,49,13,36,65],
[52,70,95,23, 4,60,11,42,69,24,68,56, 1,32,56,71,37, 2,36,91],
[22,31,16,71,51,67,63,89,41,92,36,54,22,40,40,28,66,33,13,80],
[24,47,32,60,99, 3,45, 2,44,75,33,53,78,36,84,20,35,17,12,50],
[32,98,81,28,64,23,67,10,26,38,40,67,59,54,70,66,18,38,64,70],
[67,26,20,68, 2,62,12,20,95,63,94,39,63, 8,40,91,66,49,94,21],
[24,55,58, 5,66,73,99,26,97,17,78,78,96,83,14,88,34,89,63,72],
[21,36,23, 9,75, 0,76,44,20,45,35,14, 0,61,33,97,34,31,33,95],
[78,17,53,28,22,75,31,67,15,94, 3,80, 4,62,16,14, 9,53,56,92],
[16,39, 5,42,96,35,31,47,55,58,88,24, 0,17,54,24,36,29,85,57],
[86,56, 0,48,35,71,89, 7, 5,44,44,37,44,60,21,58,51,54,17,58],
[19,80,81,68, 5,94,47,69,28,73,92,13,86,52,17,77, 4,89,55,40],
[ 4,52, 8,83,97,35,99,16, 7,97,57,32,16,26,26,79,33,27,98,66],
[88,36,68,87,57,62,20,72, 3,46,33,67,46,55,12,32,63,93,53,69],
[ 4,42,16,73,38,25,39,11,24,94,72,18, 8,46,29,32,40,62,76,36],
[20,69,36,41,72,30,23,88,34,62,99,69,82,67,59,85,74, 4,36,16],
[20,73,35,29,78,31,90, 1,74,31,49,71,48,86,81,16,23,57, 5,54],
[ 1,70,54,71,83,51,54,69,16,92,33,48,61,43,52, 1,89,19,67,48]])
class Direction(Enum):
RIGHT = 0
DOWNR = 1
DOWN = 2
DOWNL = 3
def get_array(mat, start, direction, length=4):
x, y = start
w, h = mat.shape
assert x in range(w)
assert y in range(h)
x_in_range = False
y_in_range = False
if direction == Direction.RIGHT:
if x+length <= w:
return np.ravel(mat[y, x:x+length])
elif direction == Direction.DOWN:
if y+length <= h:
return np.ravel(mat[y:y+length, x])
elif direction == Direction.DOWNR:
if y+length <= h and x+length <= w:
return np.diag(mat, x-y)[y:y+length]
elif direction == Direction.DOWNL:
mat = np.fliplr(mat)
x = w-1-x
if y+length <= h and x+length <= w:
return np.diag(mat, x-y)[y:y+length]
it = np.nditer(input_mat, flags=['multi_index'])
max_prod = (0, [], (0,0), Direction.RIGHT)
while not it.finished:
for dir in Direction:
arr = get_array(input_mat, it.multi_index, dir)
if arr is not None:
prod = np.prod(arr)
if prod > max_prod[0]:
max_prod = (prod, arr, it.multi_index, dir)
it.iternext()
max_prod[0] | Euler/euler_11-20.ipynb | andrewzwicky/puzzles | mit |
12: Highly divisible triangular number
The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be:
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
Let us list the factors of the first seven triangle numbers:
1: 1
3: 1,3
6: 1,2,3,6
10: 1,2,5,10
15: 1,3,5,15
21: 1,3,7,21
28: 1,2,4,7,14,28
We can see that 28 is the first triangle number to have over five divisors.
What is the value of the first triangle number to have over five hundred divisors? | for tri in triangle_gen():
if len(factors(tri)) > 500:
break
tri | Euler/euler_11-20.ipynb | andrewzwicky/puzzles | mit |
13: Large sum
Work out the first ten digits of the sum of the following one-hundred 50-digit numbers.
37107287533902102798797998220837590246510135740250
46376937677490009712648124896970078050417018260538
74324986199524741059474233309513058123726617309629
91942213363574161572522430563301811072406154908250
23067588207539346171171980310421047513778063246676
89261670696623633820136378418383684178734361726757
28112879812849979408065481931592621691275889832738
44274228917432520321923589422876796487670272189318
47451445736001306439091167216856844588711603153276
70386486105843025439939619828917593665686757934951
62176457141856560629502157223196586755079324193331
64906352462741904929101432445813822663347944758178
92575867718337217661963751590579239728245598838407
58203565325359399008402633568948830189458628227828
80181199384826282014278194139940567587151170094390
35398664372827112653829987240784473053190104293586
86515506006295864861532075273371959191420517255829
71693888707715466499115593487603532921714970056938
54370070576826684624621495650076471787294438377604
53282654108756828443191190634694037855217779295145
36123272525000296071075082563815656710885258350721
45876576172410976447339110607218265236877223636045
17423706905851860660448207621209813287860733969412
81142660418086830619328460811191061556940512689692
51934325451728388641918047049293215058642563049483
62467221648435076201727918039944693004732956340691
15732444386908125794514089057706229429197107928209
55037687525678773091862540744969844508330393682126
18336384825330154686196124348767681297534375946515
80386287592878490201521685554828717201219257766954
78182833757993103614740356856449095527097864797581
16726320100436897842553539920931837441497806860984
48403098129077791799088218795327364475675590848030
87086987551392711854517078544161852424320693150332
59959406895756536782107074926966537676326235447210
69793950679652694742597709739166693763042633987085
41052684708299085211399427365734116182760315001271
65378607361501080857009149939512557028198746004375
35829035317434717326932123578154982629742552737307
94953759765105305946966067683156574377167401875275
88902802571733229619176668713819931811048770190271
25267680276078003013678680992525463401061632866526
36270218540497705585629946580636237993140746255962
24074486908231174977792365466257246923322810917141
91430288197103288597806669760892938638285025333403
34413065578016127815921815005561868836468420090470
23053081172816430487623791969842487255036638784583
11487696932154902810424020138335124462181441773470
63783299490636259666498587618221225225512486764533
67720186971698544312419572409913959008952310058822
95548255300263520781532296796249481641953868218774
76085327132285723110424803456124867697064507995236
37774242535411291684276865538926205024910326572967
23701913275725675285653248258265463092207058596522
29798860272258331913126375147341994889534765745501
18495701454879288984856827726077713721403798879715
38298203783031473527721580348144513491373226651381
34829543829199918180278916522431027392251122869539
40957953066405232632538044100059654939159879593635
29746152185502371307642255121183693803580388584903
41698116222072977186158236678424689157993532961922
62467957194401269043877107275048102390895523597457
23189706772547915061505504953922979530901129967519
86188088225875314529584099251203829009407770775672
11306739708304724483816533873502340845647058077308
82959174767140363198008187129011875491310547126581
97623331044818386269515456334926366572897563400500
42846280183517070527831839425882145521227251250327
55121603546981200581762165212827652751691296897789
32238195734329339946437501907836945765883352399886
75506164965184775180738168837861091527357929701337
62177842752192623401942399639168044983993173312731
32924185707147349566916674687634660915035914677504
99518671430235219628894890102423325116913619626622
73267460800591547471830798392868535206946944540724
76841822524674417161514036427982273348055556214818
97142617910342598647204516893989422179826088076852
87783646182799346313767754307809363333018982642090
10848802521674670883215120185883543223812876952786
71329612474782464538636993009049310363619763878039
62184073572399794223406235393808339651327408011116
66627891981488087797941876876144230030984490851411
60661826293682836764744779239180335110989069790714
85786944089552990653640447425576083659976645795096
66024396409905389607120198219976047599490197230297
64913982680032973156037120041377903785566085089252
16730939319872750275468906903707539413042652315011
94809377245048795150954100921645863754710598436791
78639167021187492431995700641917969777599028300699
15368713711936614952811305876380278410754449733078
40789923115535562561142322423255033685442488917353
44889911501440648020369068063960672322193204149535
41503128880339536053299340368006977710650566631954
81234880673210146739058568557934581403627822703280
82616570773948327592232845941706525094512325230608
22918802058777319719839450180888072429661980811197
77158542502016545090413245809786882778948721859617
72107838435069186155435662884062257473692284509516
20849603980134001723930671666823555245252804609722
53503534226472524250874054075591789781264330331690 | nums = [37107287533902102798797998220837590246510135740250,
46376937677490009712648124896970078050417018260538,
74324986199524741059474233309513058123726617309629,
91942213363574161572522430563301811072406154908250,
23067588207539346171171980310421047513778063246676,
89261670696623633820136378418383684178734361726757,
28112879812849979408065481931592621691275889832738,
44274228917432520321923589422876796487670272189318,
47451445736001306439091167216856844588711603153276,
70386486105843025439939619828917593665686757934951,
62176457141856560629502157223196586755079324193331,
64906352462741904929101432445813822663347944758178,
92575867718337217661963751590579239728245598838407,
58203565325359399008402633568948830189458628227828,
80181199384826282014278194139940567587151170094390,
35398664372827112653829987240784473053190104293586,
86515506006295864861532075273371959191420517255829,
71693888707715466499115593487603532921714970056938,
54370070576826684624621495650076471787294438377604,
53282654108756828443191190634694037855217779295145,
36123272525000296071075082563815656710885258350721,
45876576172410976447339110607218265236877223636045,
17423706905851860660448207621209813287860733969412,
81142660418086830619328460811191061556940512689692,
51934325451728388641918047049293215058642563049483,
62467221648435076201727918039944693004732956340691,
15732444386908125794514089057706229429197107928209,
55037687525678773091862540744969844508330393682126,
18336384825330154686196124348767681297534375946515,
80386287592878490201521685554828717201219257766954,
78182833757993103614740356856449095527097864797581,
16726320100436897842553539920931837441497806860984,
48403098129077791799088218795327364475675590848030,
87086987551392711854517078544161852424320693150332,
59959406895756536782107074926966537676326235447210,
69793950679652694742597709739166693763042633987085,
41052684708299085211399427365734116182760315001271,
65378607361501080857009149939512557028198746004375,
35829035317434717326932123578154982629742552737307,
94953759765105305946966067683156574377167401875275,
88902802571733229619176668713819931811048770190271,
25267680276078003013678680992525463401061632866526,
36270218540497705585629946580636237993140746255962,
24074486908231174977792365466257246923322810917141,
91430288197103288597806669760892938638285025333403,
34413065578016127815921815005561868836468420090470,
23053081172816430487623791969842487255036638784583,
11487696932154902810424020138335124462181441773470,
63783299490636259666498587618221225225512486764533,
67720186971698544312419572409913959008952310058822,
95548255300263520781532296796249481641953868218774,
76085327132285723110424803456124867697064507995236,
37774242535411291684276865538926205024910326572967,
23701913275725675285653248258265463092207058596522,
29798860272258331913126375147341994889534765745501,
18495701454879288984856827726077713721403798879715,
38298203783031473527721580348144513491373226651381,
34829543829199918180278916522431027392251122869539,
40957953066405232632538044100059654939159879593635,
29746152185502371307642255121183693803580388584903,
41698116222072977186158236678424689157993532961922,
62467957194401269043877107275048102390895523597457,
23189706772547915061505504953922979530901129967519,
86188088225875314529584099251203829009407770775672,
11306739708304724483816533873502340845647058077308,
82959174767140363198008187129011875491310547126581,
97623331044818386269515456334926366572897563400500,
42846280183517070527831839425882145521227251250327,
55121603546981200581762165212827652751691296897789,
32238195734329339946437501907836945765883352399886,
75506164965184775180738168837861091527357929701337,
62177842752192623401942399639168044983993173312731,
32924185707147349566916674687634660915035914677504,
99518671430235219628894890102423325116913619626622,
73267460800591547471830798392868535206946944540724,
76841822524674417161514036427982273348055556214818,
97142617910342598647204516893989422179826088076852,
87783646182799346313767754307809363333018982642090,
10848802521674670883215120185883543223812876952786,
71329612474782464538636993009049310363619763878039,
62184073572399794223406235393808339651327408011116,
66627891981488087797941876876144230030984490851411,
60661826293682836764744779239180335110989069790714,
85786944089552990653640447425576083659976645795096,
66024396409905389607120198219976047599490197230297,
64913982680032973156037120041377903785566085089252,
16730939319872750275468906903707539413042652315011,
94809377245048795150954100921645863754710598436791,
78639167021187492431995700641917969777599028300699,
15368713711936614952811305876380278410754449733078,
40789923115535562561142322423255033685442488917353,
44889911501440648020369068063960672322193204149535,
41503128880339536053299340368006977710650566631954,
81234880673210146739058568557934581403627822703280,
82616570773948327592232845941706525094512325230608,
22918802058777319719839450180888072429661980811197,
77158542502016545090413245809786882778948721859617,
72107838435069186155435662884062257473692284509516,
20849603980134001723930671666823555245252804609722,
53503534226472524250874054075591789781264330331690]
str(np.sum(nums))[:10] | Euler/euler_11-20.ipynb | andrewzwicky/puzzles | mit |
14: Longest Collatz sequence
The following iterative sequence is defined for the set of positive integers:
$n$ β $n/2$ ($n$ is even)
$n$ β $3n + 1$ ($n$ is odd)
Using the rule above and starting with 13, we generate the following sequence:
13 β 40 β 20 β 10 β 5 β 16 β 8 β 4 β 2 β 1
It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.
Which starting number, under one million, produces the longest chain?
NOTE: Once the chain starts the terms are allowed to go above one million. | collatz_results = {}
def collatz_gen(n):
yield n
while n != 1:
if n % 2 == 0:
n = n // 2
else:
n = 3*n + 1
yield n
for i in range(1,1000000):
if i not in collatz_results.keys():
temp_dict = {}
length = 0
for term in collatz_gen(i):
try:
length += collatz_results[term]
for k in temp_dict.keys():
temp_dict[k] += collatz_results[term]
break
except KeyError:
length += 1
for k in temp_dict.keys():
temp_dict[k] += 1
temp_dict[term] = 1
for k,v in temp_dict.items():
collatz_results[k] = v
max_num = 0
current_max = 0
for k,v in collatz_results.items():
if v > current_max:
current_max = v
max_num = k
max_num | Euler/euler_11-20.ipynb | andrewzwicky/puzzles | mit |
15: Lattice paths
Starting in the top left corner of a 2Γ2 grid, and only being able to move to the right and down, there are exactly 6 routes to the bottom right corner.
How many such routes are there through a 20Γ20 grid | int(factorial(40) / factorial(20)**2) | Euler/euler_11-20.ipynb | andrewzwicky/puzzles | mit |
16: Power digit sum
$2^{15}$ = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
What is the sum of the digits of the number $2^{1000}$? | np.sum(list(map(int, str(2**1000)))) | Euler/euler_11-20.ipynb | andrewzwicky/puzzles | mit |
17: Number letter counts
If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.
If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used?
NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20 letters. The use of "and" when writing out numbers is in compliance with British usage. | def translate(n):
result = ''
basic_nums = {
1:'one',
2:'two',
3:'three',
4:'four',
5:'five',
6:'six',
7:'seven',
8:'eight',
9:'nine',
10:'ten',
11:'eleven',
12:'twelve',
13:'thirteen',
14:'fourteen',
15:'fifteen',
16:'sixteen',
17:'seventeen',
18:'eighteen',
19:'nineteen',
20:'twenty',
30:'thirty',
40:'forty',
50:'fifty',
60:'sixty',
70:'seventy',
80:'eighty',
90:'ninety',
}
try:
result = basic_nums[n]
except KeyError:
thousands = n // 1000
n %= 1000
if thousands > 0:
result += basic_nums[thousands]
result += 'thousand'
if n == 0:
return result
hundreds = n // 100
n %= 100
if hundreds > 0:
result += basic_nums[hundreds]
result += 'hundred'
if n == 0:
return result
else:
result += 'and'
try:
result += basic_nums[n]
except KeyError:
tens = n // 10
leftover = n % 10
result += basic_nums[tens*10]
result += basic_nums[leftover]
return result
char_count = 0
for num in range(1,1001):
char_count += len(translate(num))
char_count | Euler/euler_11-20.ipynb | andrewzwicky/puzzles | mit |
18: Maximum path sum I
By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23.
3
7 4
2 4 6
8 5 9 3
That is, 3 + 7 + 4 + 9 = 23.
Find the maximum total from top to bottom of the triangle below:
75
95 64
17 47 82
18 35 87 10
20 04 82 47 65
19 01 23 75 03 34
88 02 77 73 07 63 67
99 65 04 28 06 16 70 92
41 41 26 56 83 40 80 70 33
41 48 72 33 47 32 37 16 94 29
53 71 44 65 25 43 91 52 97 51 14
70 11 33 28 77 73 17 78 39 68 17 57
91 71 52 38 17 14 91 43 58 50 27 29 48
63 66 04 68 89 53 67 30 73 16 69 87 40 31
04 62 98 27 23 09 70 98 73 93 38 53 60 04 23 | input_tri = [[75],
[95, 64],
[17, 47, 82],
[18, 35, 87, 10],
[20, 4, 82, 47, 65],
[19, 1, 23, 75, 3, 34],
[88, 2, 77, 73, 7, 63, 67],
[99, 65, 4, 28, 6, 16, 70, 92],
[41, 41, 26, 56, 83, 40, 80, 70, 33],
[41, 48, 72, 33, 47, 32, 37, 16, 94, 29],
[53, 71, 44, 65, 25, 43, 91, 52, 97, 51, 14],
[70, 11, 33, 28, 77, 73, 17, 78, 39, 68, 17, 57],
[91, 71, 52, 38, 17, 14, 91, 43, 58, 50, 27, 29, 48], # 2
[63, 66, 4, 68, 89, 53, 67, 30, 73, 16, 69, 87, 40, 31], # 1, 12
[ 4, 62, 98, 27, 23, 9, 70, 98, 73, 93, 38, 53, 60, 4, 23]] # 0 , 13
def combine(row_in):
if len(row_in) <= 1:
return [row_in]
return [max(row_in[i:i+2]) for i in range(len(row_in)-1)]
height = len(input_tri)
tally_tri = [input_tri[-1]]
for row in reversed(input_tri[:-1]):
r = row
c = combine(tally_tri[-1])
res = [a+b for a,b in zip(r,c)]
tally_tri.append(res)
tally_tri[-1][0] | Euler/euler_11-20.ipynb | andrewzwicky/puzzles | mit |
19: Counting Sundays
You are given the following information, but you may prefer to do some research for yourself.
1 Jan 1900 was a Monday.
Thirty days has September, April, June and November. All the rest have thirty-one, Saving February alone, Which has twenty-eight, rain or shine. And on leap years, twenty-nine.
A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.
How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)? | months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
day = 1
sunday_first_count = 0
for year in range(1900,2001):
for month_num, days_in_month in enumerate(months):
if month_num == 1:
leap = (year % 4 == 0 and not year % 100 == 0) or year % 400 == 0
if leap:
days_in_month += 1
if day == 0 and year > 1900:
sunday_first_count += 1
day = (day + days_in_month) % 7
sunday_first_count | Euler/euler_11-20.ipynb | andrewzwicky/puzzles | mit |
20: Factorial digit sum
n! means n Γ (n β 1) Γ ... Γ 3 Γ 2 Γ 1
For example, 10! = 10 Γ 9 Γ ... Γ 3 Γ 2 Γ 1 = 3628800,
and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
Find the sum of the digits in the number 100! | np.sum(list(map(int, str(factorial(100))))) | Euler/euler_11-20.ipynb | andrewzwicky/puzzles | mit |
What did this accomplish?
Model can be trained and tested on different data
Response values are known for the testing set, and thus predictions can be evaluated
Testing accuracy is a better estimate than training accuracy of out-of-sample performance | # STEP 1: split X and y into training and testing sets
from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=4)
# print the shapes of the new X objects
print X_train.shape
print X_test.shape
# print the shapes of the new y objects
print y_train.shape
print y_test.shape
from sklearn.linear_model import LogisticRegression
# STEP 2: train the model on the training set
logreg = LogisticRegression()
logreg.fit(X_train, y_train)
# STEP 3: make predictions on the testing set
y_pred = logreg.predict(X_test)
from sklearn import metrics
# compare actual response values (y_test) with predicted response values (y_pred)
print metrics.accuracy_score(y_test, y_pred) | Day1/05_model_evaluation_tts.ipynb | dtamayo/MachineLearning | gpl-3.0 |
Repeat for KNN with K=5: | from sklearn.neighbors import KNeighborsClassifier
knn = KNeighborsClassifier(n_neighbors=5)
knn.fit(X_train, y_train)
y_pred = knn.predict(X_test)
print metrics.accuracy_score(y_test, y_pred) | Day1/05_model_evaluation_tts.ipynb | dtamayo/MachineLearning | gpl-3.0 |
Can you find an even better value for K? | # try K=1 through K=25 and record testing accuracy
k_range = range(1, 26)
scores = [] # calculate accuracies for each value of K!
#Now we plot:
import matplotlib.pyplot as plt
# allow plots to appear within the notebook
%matplotlib inline
plt.plot(k_range, scores)
plt.xlabel('Value of K for KNN')
plt.ylabel('Testing Accuracy') | Day1/05_model_evaluation_tts.ipynb | dtamayo/MachineLearning | gpl-3.0 |
Implement an SVM!
We've already learned about support vector machines. Now we're going to implement one.
We need to find out how to use this thing! We ran some code in the previous notebook that did this for us, but now we need to make things work on our own. Googling for "svm sklearn classifier" gets us to this page. This page has documentation for the package. Partway down the page, we see: "SVC, NuSVC and LinearSVC are classes capable of performing multi-class classification on a dataset." As we keep reading, we see that SVC provides an implementation. Let's try that!
We get to the documentation for SVC and it says many things. At the top, there's a box that says:
class sklearn.svm.SVC(C=1.0, kernel='rbf', degree=3, gamma='auto', coef0=0.0, shrinking=True, probability=False, tol=0.001, cache_size=200, class_weight=None, verbose=False, max_iter=-1, decision_function_shape=None, random_state=None)
How should we interpret all of this?
The first part tells us where a function lives, so the SVC function lives in sklearn.svm. It seems we're going to need to import it from there. | # First we need to import svms from sklearn
from sklearn.svm import SVC
| 30_ML-III/ML_3_Inclass_Homework.ipynb | greenelab/GCB535 | bsd-3-clause |
The parts inside the parentheses give us the ability to set or change parameters. Anything with an equals sign after it has a default parameter set. In this case, the default C is set to 1.0. There's also a box that gives some description of what each parameter is (only a few of them may make sense to us right now). If we scroll to the bottom of the box, we'll get some examples provided by the helpful sklearn team, though they don't know about the names of our datasets. They'll often use the standard name X for features and y for labels.
Let's go ahead and run an SVM using all the defaults on our data | # Get an SVC with default parameters as our algorithm
classifier = SVC()
# Fit the classifier to our datasets
classifier.fit(X1, y1)
# Apply the classifier back to our data and get an accuracy measure
train_score = classifier.score(X1, y1)
# Print the accuracy
print(train_score) | 30_ML-III/ML_3_Inclass_Homework.ipynb | greenelab/GCB535 | bsd-3-clause |
Ouch! Only about 50% accuracy. That's painful! We learned that we could modify C to make the algorithm try to fit the data we show it better. Let's ramp up C and see what happens! | # Get an SVC with a high C
classifier = SVC(C = 100)
# Fit the classifier to our datasets
classifier.fit(X1, y1)
# Apply the classifier back to our data and get an accuracy measure
train_score = classifier.score(X1, y1)
# Print the accuracy
print(train_score)
import sklearn
| 30_ML-III/ML_3_Inclass_Homework.ipynb | greenelab/GCB535 | bsd-3-clause |
Nice! 100% accuracy. This seems like we're on the right track. What we'd really like to do is figure out how we do on held out testing data though. Fortunately, sklearn provides a helper function to make holding out some of the data easy. This function is called train_test_split and we can find its documentation. If we weren't sure where to go, the sklearn documentation has a full section on cross validation.
Note: Software changes over time. The current release of sklearn on CoCalc is 0.17. There's a new version, 0.18, also available. There are also minor version numbers (e.g. the final 1 in 0.17.1). These don't change functionality. Between the two major versions the location of the train_test_split function changed. If you ever want to know what version of sklearn you're working with, you can create a code block and run this code:
import sklearn
print(sklearn.__version__)
Make sure that when you look at the documentation, you choose the version that matches what you're working with.
Let's go ahead and split our data into training and testing portions. | # Import the function to split our data:
from sklearn.cross_validation import train_test_split
# Split things into training and testing - let's have 30% of our data end up as testing
X1_train, X1_test, y1_train, y1_test = train_test_split(X1, y1, test_size=.33) | 30_ML-III/ML_3_Inclass_Homework.ipynb | greenelab/GCB535 | bsd-3-clause |
Now let's go ahead and train our classifier on the training data and test it on some held out test data | # Get an SVC again using C = 100
classifier = SVC(C = 100)
# Fit the classifier to the training data:
classifier.fit(X1_train, y1_train)
# Now we're going to apply it to the training labels first:
train_score = classifier.score(X1_train, y1_train)
# We're also going to applying it to the testing labels:
test_score = classifier.score(X1_test, y1_test)
print("Training Accuracy: " + str(train_score))
print("Testing Accuracy: " + str(test_score)) | 30_ML-III/ML_3_Inclass_Homework.ipynb | greenelab/GCB535 | bsd-3-clause |
Nice! Now we can see that while our training accuracy is very high, our testing accuracy is much lower. We could say that our model has "overfit" to the data. We learned about overfitting before. You'll get a chance to play with this SVM a bit more below. Before we move to that though, we want to show you how easy it is to use a different classifier. You might imagine that a classifier could be composed of a cascading series of rules. If this is true, then consider that. Otherwise, consider this other thing. This type of algorithm is called a decision tree, and we're going to rain one now.
sklearn has a handy decision tree classifier that we can use. By using the SVM classifier, we've already learned most of what we need to know to use it. | # First, we need to import the classifier
from sklearn.tree import DecisionTreeClassifier
# Now we're going to get a decision tree classifier with the default parameters
classifier = DecisionTreeClassifier()
# The 'fit' syntax is the same
classifier.fit(X1_train, y1_train)
# As is the 'score' syntax
train_score = classifier.score(X1_train, y1_train)
test_score = classifier.score(X1_test, y1_test)
print("Training Accuracy: " + str(train_score))
print("Testing Accuracy: " + str(test_score)) | 30_ML-III/ML_3_Inclass_Homework.ipynb | greenelab/GCB535 | bsd-3-clause |
Oof! That's pretty overfit! We're perfect on the training data but basically flipping a coin on the held out data. A DecisionTreeClassifier has two parameters max_features and max_depth that can really help us prevent overfitting. Let's train a very small tree (no more than 8 features) that's very short (no more than 3 deep). | # Now we're going to get a decision tree classifier with selected parameters
classifier = DecisionTreeClassifier(max_features=8, max_depth=3)
# The 'fit' syntax is the same
classifier.fit(X1_train, y1_train)
# As is the 'score' syntax
train_score = classifier.score(X1_train, y1_train)
test_score = classifier.score(X1_test, y1_test)
print("Training Accuracy: " + str(train_score))
print("Testing Accuracy: " + str(test_score)) | 30_ML-III/ML_3_Inclass_Homework.ipynb | greenelab/GCB535 | bsd-3-clause |
See the documentation of vcsn.automaton for more details about this function. The syntax used to define the automaton is, however, described here.
In order to facilitate the definition of automata, Vcsn provides additional ''magic commands'' to the IPython Notebook. We will see through this guide how use this command.
%%automaton: Entering an Automaton
IPython supports so-called "cell magic-commands", that start with %%. Vcsn provides the %%automaton magic command to enter the literal description of an automaton. For instance, the automaton above can entered as follows: | %%automaton a
context = "lal_char(ab), z"
$ -> p <2>
p -> q <3>a, <4>b
q -> q a
q -> $ | doc/notebooks/Automata.ipynb | pombredanne/https-gitlab.lrde.epita.fr-vcsn-vcsn | gpl-3.0 |
The first argument, here a, is the name of the variable in which this automaton is stored: | a | doc/notebooks/Automata.ipynb | pombredanne/https-gitlab.lrde.epita.fr-vcsn-vcsn | gpl-3.0 |
You may pass the option -s or --strip to strip the automaton from its layer that keeps the state name you have chosen. In that case, the internal numbers are used, unrelated to the user names (actually, the numbers are assigned to state names as they are encountered starting from 0). | %%automaton --strip a
context = "lal_char(ab), z"
$ -> p <2>
p -> q <3>a, <4>b
q -> q a
q -> $
a | doc/notebooks/Automata.ipynb | pombredanne/https-gitlab.lrde.epita.fr-vcsn-vcsn | gpl-3.0 |
The second argument specifies the format in which the automaton is described, defaulting to auto, which means "guess the format": | %%automaton a dot
digraph
{
vcsn_context = "lal_char(ab), z"
I -> p [label = "<2>"]
p -> q [label = "<3>a, <4>b"]
q -> q [label = a]
q -> F
}
%%automaton a
digraph
{
vcsn_context = "lal_char(ab), z"
I -> p [label = "<2>"]
p -> q [label = "<3>a, <4>b"]
q -> q [label = a]
q -> F
} | doc/notebooks/Automata.ipynb | pombredanne/https-gitlab.lrde.epita.fr-vcsn-vcsn | gpl-3.0 |
Automata entered this way are persistent: they are stored in the notebook and will be recovered when the page is reopened.
%automaton: Text-Based Edition of an Automaton
In IPython "line magic commands" begin with a single %. The line magic %automaton takes three arguments:
1. the name of the automaton
2. the format you want the textual description of the automaton. Defaults to auto.
3. the display mode: h for horizontal and v for vertical. Defaults to h.
Contrary to the cell magic, the %automaton can be used to update an existing automaton: | %automaton a | doc/notebooks/Automata.ipynb | pombredanne/https-gitlab.lrde.epita.fr-vcsn-vcsn | gpl-3.0 |
The real added value is that now you can interactively edit this automaton: changes in the text are immediately propagated on the rendered automaton.
When given a fresh variable name, %automaton creates a dummy automaton that you can use as a starting point: | %automaton b fado | doc/notebooks/Automata.ipynb | pombredanne/https-gitlab.lrde.epita.fr-vcsn-vcsn | gpl-3.0 |
Beware however that these automata are not persistent: changes will be lost when the notebook is closed.
Automata Formats
Vcsn supports differents input and output formats. Some, such as tikz, are only export-only formats: they cannot be read by Vcsn.
daut (read/write)
This simple format is work in progress: its precise syntax is still subject to changes. It is roughly a simplification of the dot syntax. The following example should suffice to understand the syntax. If "guessable", the context can be left implicit. | %%automaton a
context = "lal_char(ab), z"
$ -> p <2>
p -> q <3>a, <4>b
q -> q a
q -> $ | doc/notebooks/Automata.ipynb | pombredanne/https-gitlab.lrde.epita.fr-vcsn-vcsn | gpl-3.0 |
dot (read/write)
This format relies on the "dot" language of the GraphViz toolkit (http://graphviz.org). This is the default format for I/O in Vcsn.
An automaton looks as follows: | %%automaton a dot
// The comments are introduced with //, or /* ... */
//
// The overall syntax is that of Dot for directed graph ("digraph").
digraph
{
// The following attribute defines the context of the automaton.
vcsn_context = "lal_char, b"
// Initial states are denoted by an edge between a node whose name starts
// with an "I". So "0" is a initial state.
I -> 0
// Transitions are edges whose label is that of the transition.
0 -> 0 [label = "a"]
0 -> 0 [label = "b"]
0 -> 1 [label = "c, d"]
// Final states are denoted by an edge to a node whose name starts with "F".
1 -> Finish
} | doc/notebooks/Automata.ipynb | pombredanne/https-gitlab.lrde.epita.fr-vcsn-vcsn | gpl-3.0 |
efsm (read/write)
This format is designed to support import/export with OpenFST (http://openfst.org): it wraps its multi-file format (one file describes the automaton with numbers as transition labels, and one or several others define these labels) into a single format. It is not designed to be used by humans, but rather to be handled by two tools:
- efstcompile to compile such a file into the OpenFST binary file format,
- efstdecompile to extract an efsm file from a binary OpenFST file.
efsm for acceptors (single tape automata)
As an example, consider the following exchange between Vcsn and OpenFST. | a = vcsn.context('lal_char(ab), zmin').expression('[ab]*a(<2>[ab])').automaton()
a
efsm = a.format('efsm')
print(efsm) | doc/notebooks/Automata.ipynb | pombredanne/https-gitlab.lrde.epita.fr-vcsn-vcsn | gpl-3.0 |
The following sequence of operations uses OpenFST to determinize this automaton, and to load it back into Vcsn. | import os
# Save the EFSM description of the automaton in a file.
with open("a.efsm", "w") as file:
print(efsm, file=file)
# Compile the EFSM into an OpenFST file.
os.system("efstcompile a.efsm >a.fst")
# Call OpenFST's determinization.
os.system("fstdeterminize a.fst >d.fst")
# Convert from OpenFST format to EFSM.
os.system("efstdecompile d.fst >d.efsm")
# Load this file into Python.
with open("d.efsm", "r") as file:
d = file.read()
# Show the result.
print(d)
# Now read it as an automaton.
d_ofst = vcsn.automaton(d, 'efsm')
d_ofst | doc/notebooks/Automata.ipynb | pombredanne/https-gitlab.lrde.epita.fr-vcsn-vcsn | gpl-3.0 |
For what it's worth, the above sequence of actions is realized by a.fstdeterminize().
Vcsn and OpenFST compute the same automaton. | a.determinize() | doc/notebooks/Automata.ipynb | pombredanne/https-gitlab.lrde.epita.fr-vcsn-vcsn | gpl-3.0 |
efsm for transducers (two-tape automata)
The following sequence shows the round-trip of a transducer between Vcsn and OpenFST. | t = a.partial_identity()
t
tefsm = t.format('efsm')
print(tefsm)
vcsn.automaton(tefsm) | doc/notebooks/Automata.ipynb | pombredanne/https-gitlab.lrde.epita.fr-vcsn-vcsn | gpl-3.0 |
Details about the EFSM format
The EFSM format is a simple format that puts together the various files that OpenFST uses to serialize and deserialize automata: one or two files to describe the labels (called "symbol tables"), and one to list the transitions. More details about these files can be found on FSM Man Pages.
When reading an EFSM file, Vcsn expects the following bits:
a line arc_type=TYPE which specifies the weightset. If TYPE is log or log64, this is mapped to the log weightset, if it is standard, then it is mapped to zmin or rmin, depending on whether floatting points were used.
a "here-document" (the Unix name for embedded files, delimited by <<EOF to a line equal to EOF) for the first symbol table. If the here-document is named isymbols.txt, then the automaton is a transducer, otherwise it is considered an acceptor.
if the automaton is a transducer, a second symbol table, osymbols.txt, to describe the labels of the second tape.
then a final here-document, transitions.fsm, which list the transitions.
fado (read/write)
This is the native language of the FAdo platform (http://fado.dcc.fc.up.pt). Weighted automata are not supported. | a = vcsn.B.expression('a+b').standard()
a
print(a.format('fado')) | doc/notebooks/Automata.ipynb | pombredanne/https-gitlab.lrde.epita.fr-vcsn-vcsn | gpl-3.0 |
grail (write)
This format is made to exchange automata with the Grail (http://grailplus.org). Weighted automata are not supported. | a = vcsn.B.expression('a+b').standard()
a
print(a.format('grail')) | doc/notebooks/Automata.ipynb | pombredanne/https-gitlab.lrde.epita.fr-vcsn-vcsn | gpl-3.0 |
tikz (write)
This format generates a LaTeX document that uses TikZ syntax to draw the automaton. Note that the layout is not computed: all the states are simply reported in a row. You will have to tune the positions of the states by hand. However, it remains a convenient way to start. | a = vcsn.Q.expression('<2>a+<3>b').standard()
a
print(a.format('tikz')) | doc/notebooks/Automata.ipynb | pombredanne/https-gitlab.lrde.epita.fr-vcsn-vcsn | gpl-3.0 |
Mairhuber-Curtis Theorem | # Initializing a R^2
sequencer = ghalton.Halton(2)
sequencer.reset()
xH=np.array(sequencer.get(9))
print(xH)
def show_MC_theorem(s_local=0):
i=3
j=4
NC=40
sequencer.reset()
xH=np.array(sequencer.get(9))
phi1= lambda s: (s-0.5)*(s-1)/((0-0.5)*(0-1))
phi2= lambda s: (s-0)*(s-1)/((0.5-0)*(0.5-1))
phi3= lambda s: (s-0)*(s-0.5)/((1-0)*(1-0.5))
C1=lambda s: xH[i,:]*phi1(s)+np.array([0.45,0.55])*phi2(s)+xH[j,:]*phi3(s)
C2=lambda s: xH[j,:]*phi1(s)+np.array([0.15,0.80])*phi2(s)+xH[i,:]*phi3(s)
C1v=np.vectorize(C1,otypes=[np.ndarray])
C2v=np.vectorize(C2,otypes=[np.ndarray])
ss=np.linspace(0,1,NC).reshape((-1, 1))
C1o=np.array(C1v(ss))
C2o=np.array(C2v(ss))
C1plot=np.zeros((NC,2))
C2plot=np.zeros((NC,2))
for k in np.arange(0,NC):
C1plot[k,0]=C1o[k][0][0]
C1plot[k,1]=C1o[k][0][1]
C2plot[k,0]=C2o[k][0][0]
C2plot[k,1]=C2o[k][0][1]
plt.figure(figsize=(2*M,M))
plt.subplot(121)
plt.plot(C1plot[:,0],C1plot[:,1],'r--')
plt.plot(C2plot[:,0],C2plot[:,1],'g--')
plt.scatter(xH[:,0], xH[:,1], s=300, c="b", alpha=1.0, marker='.',
label="Halton")
plt.scatter(C1(s_local)[0], C1(s_local)[1], s=300, c="r", alpha=1.0, marker='d')
plt.scatter(C2(s_local)[0], C2(s_local)[1], s=300, c="g", alpha=1.0, marker='d')
plt.axis([0,1,0,1])
plt.title(r'Quasi-random points (Halton)')
plt.grid(True)
xHm=np.copy(xH)
xHm[i,:]=C1(s_local)
xHm[j,:]=C2(s_local)
R=distance_matrix(xHm, xH)
det_s_local=np.linalg.det(R)
plt.subplot(122)
plt.title(r'det(R_fixed)='+str(det_s_local))
det_s=np.zeros_like(ss)
for k, s in enumerate(ss):
xHm[i,:]=C1plot[k,:]
xHm[j,:]=C2plot[k,:]
R=distance_matrix(xHm, xH)
det_s[k]=np.linalg.det(R)
plt.plot(ss,det_s,'-')
plt.plot(s_local,det_s_local,'dk',markersize=16)
plt.grid(True)
plt.show()
interact(show_MC_theorem,s_local=(0,1,0.1)) | SC3/01_MC_theorem_Halton_distance_matrix_and_RBF_interpolation.ipynb | tclaudioe/Scientific-Computing | bsd-3-clause |
Halton points vs pseudo-random points in 2D | def plot_random_vs_Halton(n=100):
# Number of points to be generated
# n=1000
# I am reseting the sequence everytime I generated just to get the same points
sequencer.reset()
xH=np.array(sequencer.get(n))
np.random.seed(0)
xR=np.random.rand(n,2)
plt.figure(figsize=(2*M,M))
plt.subplot(121)
plt.scatter(xR[:,0], xR[:,1], s=100, c="r", alpha=1.0, marker='.',
label="Random", edgecolors='None')
plt.axis([0,1,0,1])
plt.title(r'Pseudo-random points')
plt.grid(True)
plt.subplot(122)
plt.scatter(xH[:,0], xH[:,1], s=100, c="b", alpha=1.0, marker='.',
label="Halton")
plt.axis([0,1,0,1])
plt.title(r'Quasi-random points (Halton)')
plt.grid(True)
plt.show()
interact(plot_random_vs_Halton,n=(20,500,20)) | SC3/01_MC_theorem_Halton_distance_matrix_and_RBF_interpolation.ipynb | tclaudioe/Scientific-Computing | bsd-3-clause |
Interpolation with Distance Matrix from Halton points | def show_R(mH=10):
fig= plt.figure(figsize=(2*M*mH/12,M*mH/12))
ax = plt.gca()
sequencer.reset()
X=np.array(sequencer.get(mH))
R=distance_matrix(X, X)
plot_matrices_with_values(ax,R)
interact(show_R,mH=(2,20,1)) | SC3/01_MC_theorem_Halton_distance_matrix_and_RBF_interpolation.ipynb | tclaudioe/Scientific-Computing | bsd-3-clause |
Defining a test function | # The function to be interpolated
f=lambda x,y: 16*x*(1-x)*y*(1-y)
def showing_f(n=10, elev=40, azim=230):
fig = plt.figure(figsize=(2*M,M))
# Creating regular mesh
Xr = np.linspace(0, 1, n)
Xm, Ym = np.meshgrid(Xr,Xr)
Z = f(Xm,Ym)
# Wireframe
plt.subplot(221,projection='3d')
ax = fig.gca()
ax.plot_wireframe(Xm, Ym, Z)
ax.view_init(elev,azim)
# imshow
plt.subplot(222)
#plt.imshow(Z,interpolation='none', extent=[0, 1, 0, 1])
plt.contourf(Xm, Ym, Z, 20)
plt.ylabel('$y$')
plt.xlabel('$x$')
plt.axis('equal')
plt.xlim(0,1)
plt.colorbar()
# Contour plot
plt.subplot(223)
plt.contour(Xm, Ym, Z, 20)
plt.axis('equal')
plt.colorbar()
# Surface
plt.subplot(224,projection='3d')
ax = fig.gca()
surf = ax.plot_surface(Xm, Ym, Z, rstride=1, cstride=1, cmap=cm.coolwarm,
linewidth=0, antialiased=False)
fig.colorbar(surf)
ax.view_init(elev,azim)
plt.show()
| SC3/01_MC_theorem_Halton_distance_matrix_and_RBF_interpolation.ipynb | tclaudioe/Scientific-Computing | bsd-3-clause |
Let's look at $f$ | elev_widget = IntSlider(min=0, max=180, step=10, value=40)
azim_widget = IntSlider(min=0, max=360, step=10, value=230)
interact(showing_f,n=(5,50,5),elev=elev_widget,azim=azim_widget)
def eval_interp_distance_matrix(C,X,x,y):
R=distance_matrix(X, np.array([[x,y]]))
return np.dot(C,R)
def showing_f_interpolated(n=10, mH=10, elev=40, azim=230):
fig = plt.figure(figsize=(2*M,M))
## Building distance matrix and solving linear system
sequencer.reset()
X=np.array(sequencer.get(mH))
R=distance_matrix(X, X)
Zs=f(X[:,0],X[:,1])
C=np.linalg.solve(R,Zs)
# f interpolated with distance function
fIR=np.vectorize(eval_interp_distance_matrix, excluded=[0,1])
# Creating regular mesh
Xr = np.linspace(0, 1, n)
Xm, Ym = np.meshgrid(Xr,Xr)
Z = f(Xm,Ym)
# Contour plot - Original Data
plt.subplot(221)
plt.contour(Xm, Ym, Z, 20)
plt.colorbar()
plt.axis('equal')
plt.title(r'$f(x,y)$')
# Surface - Original Data
plt.subplot(222,projection='3d')
ax = fig.gca()
surf = ax.plot_surface(Xm, Ym, Z, rstride=1, cstride=1, cmap=cm.coolwarm,
linewidth=0, antialiased=False)
fig.colorbar(surf)
ax.view_init(elev,azim)
plt.title(r'$f(x,y)$')
# Contour plot - Interpolated Data
plt.subplot(223)
plt.contour(Xm, Ym, fIR(C,X,Xm,Ym), 20)
plt.axis('equal')
plt.colorbar()
plt.scatter(X[:,0], X[:,1], s=100, c="r", alpha=0.5, marker='.',
label="Random", edgecolors='None')
plt.title(r'$fIR(x,y)$')
# Surface - Interpolated Data
plt.subplot(224,projection='3d')
ax = fig.gca()
surf = ax.plot_surface(Xm, Ym, fIR(C,X,Xm,Ym), rstride=1, cstride=1, cmap=cm.coolwarm,
linewidth=0, antialiased=False)
fig.colorbar(surf)
ax.view_init(elev,azim)
ax.set_zlim(0,1)
plt.title(r'$fIR(x,y)$')
plt.show() | SC3/01_MC_theorem_Halton_distance_matrix_and_RBF_interpolation.ipynb | tclaudioe/Scientific-Computing | bsd-3-clause |
The interpolation with distance matrix itself | interact(showing_f_interpolated,n=(5,50,5),mH=(5,80,5),elev=elev_widget,azim=azim_widget) | SC3/01_MC_theorem_Halton_distance_matrix_and_RBF_interpolation.ipynb | tclaudioe/Scientific-Computing | bsd-3-clause |
RBF interpolation | # Some RBF's
linear_rbf = lambda r,eps: r
gaussian_rbf = lambda r,eps: np.exp(-(eps*r)**2)
MQ_rbf = lambda r,eps: np.sqrt(1+(eps*r)**2)
IMQ_rbf = lambda r,eps: 1./np.sqrt(1+(eps*r)**2)
# The chosen one! But please try all of them!
rbf = lambda r,eps: MQ_rbf(r,eps)
def eval_interp_rbf(C,X,x,y,eps):
A=rbf(distance_matrix(X, np.array([[x,y]])),eps)
return np.dot(C,A)
def showing_f_interpolated_rbf(n=10, mH=10, elev=40, azim=230, eps=1):
fig = plt.figure(figsize=(2*M,M))
# Creating regular mesh
Xr = np.linspace(0, 1, n)
Xm, Ym = np.meshgrid(Xr,Xr)
Z = f(Xm,Ym)
########################################################
## Pseudo-random
## Building distance matrix and solving linear system
np.random.seed(0)
X=np.random.rand(mH,2)
R=distance_matrix(X,X)
A=rbf(R,eps)
Zs=f(X[:,0],X[:,1])
C=np.linalg.solve(A,Zs)
# f interpolated with distance function
fIR=np.vectorize(eval_interp_rbf, excluded=[0,1,4])
# Contour plot - Original Data
plt.subplot(231)
plt.contour(Xm, Ym, fIR(C,X,Xm,Ym,eps), 20)
plt.colorbar()
plt.scatter(X[:,0], X[:,1], s=100, c="r", alpha=0.5, marker='.',
label="Random", edgecolors='None')
plt.title(r'$f(x,y)_{rbf}$ with Pseudo-random points')
# Surface - Original Data
plt.subplot(232,projection='3d')
ax = fig.gca()
surf = ax.plot_surface(Xm, Ym, fIR(C,X,Xm,Ym,eps), rstride=1, cstride=1, cmap=cm.coolwarm,
linewidth=0, antialiased=False)
fig.colorbar(surf)
ax.view_init(elev,azim)
ax.set_zlim(0,1)
plt.title(r'$f(x,y)_{rbf}$ with Pseudo-random points')
# Contour plot - Original Data
plt.subplot(233)
plt.contourf(Xm, Ym, np.abs(f(Xm,Ym)-fIR(C,X,Xm,Ym,eps)), 20)
#plt.imshow(np.abs(f(Xm,Ym)-fIR(C,X,Xm,Ym,eps)),interpolation='none', extent=[0, 1, 0, 1])
plt.axis('equal')
plt.xlim(0,1)
plt.colorbar()
plt.scatter(X[:,0], X[:,1], s=100, c="k", alpha=0.8, marker='.',
label="Random", edgecolors='None')
plt.title(r'Error with Pseudo-random points')
########################################################
## HALTON (Quasi-random)
## Building distance matrix and solving linear system
sequencer.reset()
X=np.array(sequencer.get(mH))
R=distance_matrix(X,X)
A=rbf(R,eps)
Zs=f(X[:,0],X[:,1])
C=np.linalg.solve(A,Zs)
# f interpolated with distance function
fIR=np.vectorize(eval_interp_rbf, excluded=[0,1,4])
# Contour plot - Interpolated Data
plt.subplot(234)
plt.contour(Xm, Ym, fIR(C,X,Xm,Ym,eps), 20)
plt.colorbar()
plt.scatter(X[:,0], X[:,1], s=100, c="r", alpha=0.5, marker='.',
label="Random", edgecolors='None')
plt.title(r'$f_{rbf}(x,y)$ with Halton points')
# Surface - Interpolated Data
plt.subplot(235,projection='3d')
ax = fig.gca()
surf = ax.plot_surface(Xm, Ym, fIR(C,X,Xm,Ym,eps), rstride=1, cstride=1, cmap=cm.coolwarm,
linewidth=0, antialiased=False)
fig.colorbar(surf)
ax.view_init(elev,azim)
ax.set_zlim(0,1)
plt.title(r'$f_{rbf}(x,y)$ with Halton points')
# Contour plot - Original Data
plt.subplot(236)
plt.contourf(Xm, Ym, np.abs(f(Xm,Ym)-fIR(C,X,Xm,Ym,eps)), 20)
#plt.imshow(np.abs(f(Xm,Ym)-fIR(C,X,Xm,Ym,eps)),interpolation='none', extent=[0, 1, 0, 1])
plt.axis('equal')
plt.xlim(0,1)
plt.colorbar()
plt.scatter(X[:,0], X[:,1], s=100, c="k", alpha=0.8, marker='.',
label="Random", edgecolors='None')
plt.title(r'Error with Halton points')
plt.show()
interact(showing_f_interpolated_rbf,n=(5,50,5),mH=(5,80,5),elev=elev_widget,azim=azim_widget,eps=(0.1,50,0.1)) | SC3/01_MC_theorem_Halton_distance_matrix_and_RBF_interpolation.ipynb | tclaudioe/Scientific-Computing | bsd-3-clause |
1. Cargamos el conjunto de entrenamiento
La manera en la que cargamos el conjunto de entrenamiento podemos observarlo en el Jupyter Notebook 1_Train_Set_Load.
2. Crear vocabulario
La manera en la que creamos el voacabulario podemos observarlo en el Jupyter Notebook 2A_Daisy_Features y 2B_Clustering. | path = '../rsc/obj/'
mini_kmeans_path = path + 'mini_kmeans.sav'
mini_kmeans = pickle.load(open(mini_kmeans_path, 'rb')) | code/notebooks/Prototypes/BoW/Bag_of_Words.ipynb | jasag/Phytoliths-recognition-system | bsd-3-clause |
3. ObtenciΓ³n de Bag of Words | trainInstances = []
for imgFeatures in train_features:
# extrae pertenencias a cluster
pertenencias = mini_kmeans.predict(imgFeatures)
# extrae histograma
bovw_representation, _ = np.histogram(pertenencias, bins=500, range=(0,499))
# aΓ±ade al conjunto de entrenamiento final
trainInstances.append(bovw_representation)
trainInstances = np.array(trainInstances) | code/notebooks/Prototypes/BoW/Bag_of_Words.ipynb | jasag/Phytoliths-recognition-system | bsd-3-clause |
Entrenamiento de un clasificador | from sklearn import svm
classifier = svm.SVC(kernel='linear', C=0.01)
y_pred = classifier.fit(trainInstances, y_train)
import pickle # MΓ³dulo para serializar
path = '../rsc/obj/'
svm_BoW_path = path + 'svm_BoW.sav'
pickle.dump(classifier, open(svm_BoW_path, 'wb')) | code/notebooks/Prototypes/BoW/Bag_of_Words.ipynb | jasag/Phytoliths-recognition-system | bsd-3-clause |
Functions, loops and branching
The following exercises let you practice Python syntax. Do not use any packages not in the standard library except for matplotlib.pyplot which has been imported for you.
If you have not done much programming, these exercises will be challenging. Don't give up! For this first exercise, solutions are provided, but try not to refer to them unless you are desperate.
1. Grading (20 points)
Write a function to assign grades to a student such that
A = [90 - 100]
B = [80 - 90)
C = [65 - 80)
D = [0, 65)
where square brackets indicate inclusive boundaries and parentheses indicate exclusive boundaries. However, studens whose attendance is 12 days or fewer get their grade reduced by one (A to B, B to C, C to D, and D stays D). The function should take a score and an attendance as an argument and return A, B, C or D as appropriate.(10 points)
- Count the number of students with each grade from the given scores. (10 points) | scores = [ 84, 76, 67, 23, 83, 23, 50, 100, 32, 84, 22, 41, 27,
29, 71, 85, 47, 77, 39, 25, 85, 69, 22, 66, 100, 92,
97, 46, 81, 88, 67, 20, 52, 62, 39, 36, 79, 54, 74,
64, 33, 68, 85, 69, 84, 30, 68, 100, 71, 33, 21, 95,
92, 72, 53, 50, 31, 82, 53, 68, 49, 37, 40, 21, 94,
30, 54, 58, 92, 95, 73, 80, 81, 56, 44, 22, 69, 70,
25, 50, 59, 32, 65, 79, 27, 62, 27, 31, 78, 88, 68,
53, 79, 69, 89, 38, 80, 55, 92, 55]
attendances = [17, 19, 21, 14, 10, 20, 14, 9, 6, 21, 5, 23, 21, 4, 5, 21, 20,
2, 14, 14, 21, 22, 3, 0, 11, 0, 0, 4, 20, 14, 23, 16, 24, 5,
12, 11, 22, 20, 15, 23, 0, 20, 20, 6, 4, 14, 6, 18, 17, 0, 18,
6, 3, 19, 24, 7, 9, 15, 18, 10, 2, 15, 21, 2, 9, 21, 20, 11,
24, 23, 14, 22, 4, 12, 7, 19, 6, 18, 23, 6, 14, 6, 1, 12, 7,
11, 22, 21, 7, 22, 24, 4, 10, 17, 21, 15, 0, 20, 3, 20]
# Your answer here
def grade(score, attendance):
"""Function that returns grade based on score and attendance."""
if attendance > 12:
if score >= 90:
return 'A'
elif score >= 80:
return 'B'
elif score >= 65:
return 'C'
else:
return 'D'
else:
if score >= 90:
return 'B'
elif score >= 80:
return 'C'
else:
return 'D'
counts = {}
for score, attendance in zip(scores, attendances):
g = grade(score, attendance)
counts[g] = counts.get(g, 0) + 1
for g in 'ABCD':
print(g, counts[g]) | homework/01_Functions_Loops_Branching_Solutions.ipynb | cliburn/sta-663-2017 | mit |
2. The Henon map and chaos. (25 points)
The Henon map takes a pont $(x_n, y_n)$ in the plane and maps it to
$$
x_{n+1} = 1 - a x_n^2 + y_n \
y_{n+1} = b x_n
$$
Write a function for the Henon map. It should take the current (x, y) value and return a new pair of coordinates. Set a=1.4 and b=0.3 as defatult arguments. What is the output for x=1 and y=1? (5 points)
Using a for loop that increments the value of $a$ from 1.1 to 1.4 in steps of 0.01, save the last 50 $x$-terms in the iterated Henon map stopping at $x_{1000}$ for each value of $a$. Use $x_0 = 1$ and $y_0 = 1$ for each value of $a$, leaveing fixed $b = 0.3$.(10 points)
Make a scatter plot of each $(a, x)$ value with $a$ on the horizontal axis and $x$ on the vertical axis. Use the plt.scatter function with s=1 to make the plot. (10 points) | # Your answer here
def henon(x, y, a=1.4, b=0.3):
"""Henon map."""
return (1 - a*x**2 + y, b*x)
henon(1, 1)
n = 1000
n_store = 50
aa = [i/100 for i in range(100, 141)]
xxs = []
for a in aa:
xs = []
x, y = 1, 1
for i in range(n - n_store):
x, y = henon(x, y, a=a)
for i in range(n_store):
x, y = henon(x, y, a=a)
xs.append(x)
xxs.append(xs)
%matplotlib inline
import matplotlib.pyplot as plt
for a, xs in zip(aa, xxs):
plt.scatter([a]*n_store, xs, s=1) | homework/01_Functions_Loops_Branching_Solutions.ipynb | cliburn/sta-663-2017 | mit |
3. Collatz numbers - Euler project problem 14. (25 points)
The following iterative sequence is defined for the set of positive integers:
n β n/2 (n is even)
n β 3n + 1 (n is odd)
Using the rule above and starting with 13, we generate the following sequence:
13 β 40 β 20 β 10 β 5 β 16 β 8 β 4 β 2 β 1
It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.
Write a function to generate the iterative sequence described (15 points)
Which starting number, under one million, produces the longest chain? (10 points)
NOTE: Once the chain starts the terms are allowed to go above one million. | # Your answer here
def collatz(n):
"""Returns Collatz sequence starting with n."""
seq = [n]
while n != 1:
if n % 2 == 0:
n = n // 2
else:
n = 3*n + 1
seq.append(n)
return seq | homework/01_Functions_Loops_Branching_Solutions.ipynb | cliburn/sta-663-2017 | mit |
Generator version | def collatz_count(n):
"""Returns Collatz sequence starting with n."""
count = 1
while n != 1:
if n % 2 == 0:
n = n // 2
else:
n = 3*n + 1
count += 1
return count
%%time
best_n = 1
best_length = 1
for n in range(2, 1000000):
length = len(collatz(n))
if length > best_length:
best_length = length
best_n = n
print(best_n, best_length) | homework/01_Functions_Loops_Branching_Solutions.ipynb | cliburn/sta-663-2017 | mit |
A simple optimization
Ignore starting numbers that have been previously generated since they cannot be longer than the generating sequence. | %%time
best_n = 1
best_length = 1
seen = set([])
for n in range(2, 1000000):
if n in seen:
continue
seq = collatz(n)
seen.update(seq)
length = len(seq)
if length > best_length:
best_length = length
best_n = n
print(best_n, best_length) | homework/01_Functions_Loops_Branching_Solutions.ipynb | cliburn/sta-663-2017 | mit |
4. Reading Ulysses. (30 points)
Write a program to download the text of Ulysses (5 points)
Open the downloaded file and read the entire sequence into a single string variable called text, discarding the header information (i.e. text should start with \n\n*** START OF THIS PROJECT GUTENBERG EBOOK ULYSSES ***\n\n\n\n\n). Also remove the footer information (i.e. text should not include anything from End of the Project Gutenberg EBook of Ulysses, by James Joyce). (10 points)
Find and report the starting index (counting from zero) and length of the longest word in text. For simplicity, a word is defined here to be any sequence of characters with no space between the characters (i.e. a word may include punctuation or numbers, just not spaces). If there are ties, report the starting index and length of the last word found. For example, in "the quick brow fox jumps over the lazy dog." the longest word is jumps which starts at index 19 and has length 5, and 'dog.' would be considered a 4-letter word (15 points). | # Your answer here
import urllib.request
response = urllib.request.urlopen('http://www.gutenberg.org/files/4300/4300-0.txt')
text = response.read().decode() | homework/01_Functions_Loops_Branching_Solutions.ipynb | cliburn/sta-663-2017 | mit |
```python
Alternative version using requests library
Although not officially part of the standard libaray,
it is so widely used that the standard docs point to it
"The Requests package is recommended for a higher-level HTTP client interface."
import requests
url = 'http://www.gutenberg.org/files/4300/4300-0.txt'
text = requests.get(url).text
``` | with open('ulysses.txt', 'w') as f:
f.write(text)
with open('ulysses.txt') as f:
text = f.read()
start_string = '\n\n*** START OF THIS PROJECT GUTENBERG EBOOK ULYSSES ***\n\n\n\n\n'
stop_string = 'End of the Project Gutenberg EBook of Ulysses, by James Joyce'
start_idx = text.find(start_string)
stop_idx = text.find(stop_string)
text = text[(start_idx + len(start_string)):stop_idx]
best_len = 0
best_word = ''
for word in set(text.split()):
if len(word) > best_len:
best_len = len(word)
best_word = word
best_word | homework/01_Functions_Loops_Branching_Solutions.ipynb | cliburn/sta-663-2017 | mit |
We are looking for the last word found, so search backwards from the end with rfind | idx = text.rfind(best_word,)
idx, best_len
text[idx:(idx+best_len)] | homework/01_Functions_Loops_Branching_Solutions.ipynb | cliburn/sta-663-2017 | mit |
Loading the Shapefile
This notebook uses the 1:110m Natural Earth countries shapefile.
After loading the shapefile, we also fetch the index of the "MAPCOLOR7" field so that we can paint different countries different colors.
You can also use your own shapefile - just copy it to the same folder as this notebook, and update the filename passed to shapefile.Reader. You may also need to update mapcolor_idx field to reference an attribute that exists in your shapefile. | import shapefile
sf = shapefile.Reader("ne_110m_admin_0_countries/ne_110m_admin_0_countries.shp")
mapcolor_idx = [field[0] for field in sf.fields].index("MAPCOLOR7")-1
mapcolor_map = [
"#000000",
"#fbb4ae",
"#b3cde3",
"#ccebc5",
"#decbe4",
"#fed9a6",
"#ffffcc",
"#e5d8bd",
] | jupyter-notebooks/vector/shapefile.ipynb | planetlabs/notebooks | apache-2.0 |
Reprojection
The countries shapefile is in the WGS 84 projetion (EPSG:4326). We will reproject to Web Mercator (EPSG:3857) to demonstrate how reprojection. To do this, we construct a Transformer using pyproj.
At the same time, set up the rendering bounds. For simplicity, define the bounds in lat/lon and reproject to meters. Note that pyplot expects bounds in minx,maxx,miny,maxy order, while pyproj transform works on in x,y pairs. | import pyproj
transformer = pyproj.Transformer.from_crs('EPSG:4326', 'EPSG:3857', always_xy=True)
BOUNDS = [-180, 180, -75, 80]
BOUNDS[0],BOUNDS[2] = transformer.transform(BOUNDS[0],BOUNDS[2])
BOUNDS[1],BOUNDS[3] = transformer.transform(BOUNDS[1],BOUNDS[3]) | jupyter-notebooks/vector/shapefile.ipynb | planetlabs/notebooks | apache-2.0 |
Plotting the Data
To display the shapefile, iterate through the shapes in the shapefile. Fetch the mapcolor attribute for each shape and use it to determine the fill color. Collect the points for each shape, and transform them to EPSG:3857 using the transformer constructed above. Plot each shape with pyplot using fill for the fill and plot for the outline.
Finaly, set the bounds on the plot. | %matplotlib notebook
import matplotlib.pyplot as plt
for shape in sf.shapeRecords():
for i in range(len(shape.shape.parts)):
fillcolor=mapcolor_map[shape.record[mapcolor_idx]]
i_start = shape.shape.parts[i]
if i==len(shape.shape.parts)-1:
i_end = len(shape.shape.points)
else:
i_end = shape.shape.parts[i+1]
points = list(transformer.itransform(shape.shape.points[i_start:i_end]))
x = [i[0] for i in points]
y = [i[1] for i in points]
#Poly Fill
plt.fill(x,y, facecolor=fillcolor, alpha=0.8)
#Poly line
plt.plot(x,y, color='#000000', alpha=1, linewidth=1)
ax = plt.axis(BOUNDS) | jupyter-notebooks/vector/shapefile.ipynb | planetlabs/notebooks | apache-2.0 |
Chebyshev differentiation matrix | def cheb(N):
if N==0:
D=0
x=1
return D,x
x = np.cos(np.pi*np.arange(N+1)/N)
c=np.hstack((2,np.ones(N-1),2))*((-1.)**np.arange(N+1))
X=np.tile(x,(N+1,1)).T
dX=X-X.T
D = np.outer(c,1./c)/(dX+np.eye(N+1))
D = D - np.diag(np.sum(D.T,axis=0))
return D,x | SC5/04 Numerical Example of Spectral Differentiation.ipynb | tclaudioe/Scientific-Computing | bsd-3-clause |
Understanding how the np.FFT does the FFT | def show_spectral_derivative_example(N):
x=np.linspace(2*np.pi/N,2*np.pi,N)
u = lambda x: np.sin(x)
up = lambda x: np.cos(x)
#u = lambda x: np.sin(x)*np.cos(x)
#up = lambda x: np.cos(x)*np.cos(x)-np.sin(x)*np.sin(x)
v=u(x)
K=np.fft.fftfreq(N)*N
iK=1j*K
vhat=np.fft.fft(v)
W=iK*vhat
W[int(N/2)]=0
vp=np.real(np.fft.ifft(W))
plt.figure(figsize=(10,10))
plt.plot(x,v,'ks-',markersize=12,markeredgewidth=3,label='$\sin(x)$',linewidth=3)
plt.plot(x,up(x),'b.-',markersize=24,markeredgewidth=3,label='Exact derivative: $\cos(x)$',linewidth=3)
plt.plot(x,np.real(vp),'rx-',markersize=10,markeredgewidth=3,label='spectral derivative',linewidth=3)
plt.grid(True)
plt.legend(loc='best')
plt.xlabel('$x$')
plt.show()
print('v :',v)
print('vhat :',vhat)
print('K :',K)
print('W :',W)
print('vprime: ',vp)
widgets.interact(show_spectral_derivative_example,N=(2,40,2))
def spectralDerivativeByFFT(v,nu=1):
if not np.all(np.isreal(v)):
raise ValueError('The input vector must be real')
N=v.shape[0]
K=np.fft.fftfreq(N)*N
iK=(1j*K)**nu
v_hat=np.fft.fft(v)
w_hat=iK*v_hat
if np.mod(nu,2)!=0:
w_hat[int(N/2)]=0
return np.real(np.fft.ifft(w_hat))
def my_D2_spec_2pi(N):
h=(2*np.pi/N)
c=np.zeros(N)
j=np.arange(1,N)
c[0]=-np.pi**2/(3.*h**2)-1./6.
c[1:]=-0.5*((-1)**j)/(np.sin(j*h/2.)**2)
D2=toeplitz(c)
return D2 | SC5/04 Numerical Example of Spectral Differentiation.ipynb | tclaudioe/Scientific-Computing | bsd-3-clause |
Fractional derivative application | def fractional_derivative(N=10,nu=1):
x=np.linspace(2*np.pi/N,2*np.pi,N)
u = lambda x: np.sin(x)
up = lambda x: np.cos(x)
v = u(x)
vp=spectralDerivativeByFFT(v,nu)
plt.figure(figsize=(10,10))
plt.plot(x,v,'ks-',markersize=12,markeredgewidth=3,label='$\sin(x)$',linewidth=3)
plt.plot(x,up(x),'b.-',markersize=24,markeredgewidth=3,label='Exact derivative: $\cos(x)$',linewidth=3)
plt.plot(x,np.real(vp),'rx-',markersize=10,markeredgewidth=3,label=r'$\frac{d^{\nu}u}{dx^{\nu}}$',linewidth=3)
plt.grid(True)
plt.legend(loc='best')
plt.xlabel('$x$')
plt.show()
d_nu=0.1
widgets.interact(fractional_derivative,N=(4,100),nu=(d_nu,1,d_nu)) | SC5/04 Numerical Example of Spectral Differentiation.ipynb | tclaudioe/Scientific-Computing | bsd-3-clause |
Example 1: Computing Eigenvalues
We are solving: $-u''(x)+x^2\,u(x)=\lambda\, u(x)$ on $\mathbb{R}$ | L=8.0
def show_example_1(N=6):
h=2*np.pi/N
x=np.linspace(h,2*np.pi,N)
x=L*(x-np.pi)/np.pi
D2=(np.pi/L)**2*my_D2_spec_2pi(N)
w, v = np.linalg.eig(-D2+np.diag(x**2))
# eigenvalues = np.sort(np.linalg.eigvals(-D2+np.diag(x**2)))
ii = np.argsort(w)
w=w[ii]
v=v[:,ii]
plt.figure(figsize=(2*M,2*M))
for i in np.arange(1,5):
plt.subplot(2,2,i)
plt.title(r'$u_{:d}(x),\, \lambda_{:d}={:f}$'.format(i,i,w[i-1]))
plt.plot(x,v[:,i],'kx',markersize=16,markeredgewidth=3)
plt.grid(True)
plt.show()
widgets.interact(show_example_1,N=(6,100,1)) | SC5/04 Numerical Example of Spectral Differentiation.ipynb | tclaudioe/Scientific-Computing | bsd-3-clause |
Example 2: Solving ODE
Solving the following BVP $u_{xx}=\exp(4\,x)$ with $u(-1)=u(1)=0$ | def example_2(N=16):
D,x = cheb(N)
D2 = np.dot(D,D)
D2 = D2[1:-1,1:-1]
f = np.exp(4*x[1:-1])
u = np.linalg.solve(D2,f)
u = np.concatenate(([0],u,[0]),axis=0)
plt.figure(figsize=(M,M))
plt.plot(x,u,'k.')
xx = np.linspace(-1,1,1000)
P = np.polyfit(x, u, N)
uu = np.polyval(P, xx)
plt.plot(xx,uu,'b-')
plt.grid(True)
exact = (np.exp(4*xx)-np.sinh(4.)*xx-np.cosh(4.))/16.
plt.title('max error= '+str(np.linalg.norm(exact-uu,np.inf)))
plt.ylim([-2.5,0.5])
plt.show()
interact(example_2,N=(2,35)) | SC5/04 Numerical Example of Spectral Differentiation.ipynb | tclaudioe/Scientific-Computing | bsd-3-clause |
Example 3: Solving ODE
Solving the following BVP $u_{xx}=\exp(u)$ with $u(-1)=u(1)=0$ | def example_3(N=16,IT=20):
D,x = cheb(N)
D2 = np.dot(D,D)
D2 = D2[1:-1,1:-1]
u = np.zeros(N-1)
for i in np.arange(IT):
u_new = np.linalg.solve(D2,np.exp(u))
change = np.linalg.norm(u_new-u,np.inf)
u = u_new
u = np.concatenate(([0],u,[0]),axis=0)
plt.figure(figsize=(M,M))
plt.plot(x,u,'k.')
xx = np.linspace(-1,1,1000)
P = np.polyfit(x, u, N)
uu = np.polyval(P, xx)
plt.plot(xx,uu,'b-')
plt.grid(True)
plt.title('IT= '+str(IT)+' u(0)= '+str(u[int(N/2)]))
plt.ylim([-0.5,0.])
plt.show()
interact(example_3,N=(2,30),IT=(0,100)) | SC5/04 Numerical Example of Spectral Differentiation.ipynb | tclaudioe/Scientific-Computing | bsd-3-clause |
Example 4: Eigenvalue BVP
Solve $u_{xx}=\lambda\,u$ with $u(-1)=u(1)=0$ | N_widget = IntSlider(min=2, max=50, step=1, value=10)
j_widget = IntSlider(min=1, max=49, step=1, value=5)
def update_j_range(*args):
j_widget.max = N_widget.value-1
j_widget.observe(update_j_range, 'value')
def example_4(N=36,j=5):
D,x = cheb(N)
D2 = np.dot(D,D)
D2 = D2[1:-1,1:-1]
lam, V = np.linalg.eig(D2)
ii=np.argsort(-np.real(lam))
lam=lam[ii]
V=V[:,ii]
u = np.concatenate(([0],V[:,j-1],[0]),axis=0)
plt.figure(figsize=(2*M,M))
plt.plot(x,u,'k.')
xx = np.linspace(-1,1,1000)
P = np.polyfit(x, u, N)
uu = np.polyval(P, xx)
plt.plot(xx,uu,'b-')
plt.grid(True)
plt.title('eig '+str(j)+' = '+str(lam[j-1]*4./(np.pi**2))+' pi**2/4'+' ppw '+str(4*N/(np.pi*j)))
plt.show()
interact(example_4,N=N_widget,j=j_widget) | SC5/04 Numerical Example of Spectral Differentiation.ipynb | tclaudioe/Scientific-Computing | bsd-3-clause |
Example 5: (2D) Poisson equation $u_{xx}+u_{yy}=f$ with u=0 on $\partial\Gamma$ | elev_widget = IntSlider(min=0, max=180, step=10, value=40)
azim_widget = IntSlider(min=0, max=360, step=10, value=230)
def example_5(N=10,elev=40,azim=230):
D,x = cheb(N)
y=x
D2 = np.dot(D,D)
D2 = D2[1:-1,1:-1]
xx,yy=np.meshgrid(x[1:-1],y[1:-1])
xx = xx.flatten()
yy = yy.flatten()
f = 10*np.sin(8*xx*(yy-1))
I = np.eye(N-1)
# The Laplacian
L = np.kron(I,D2)+np.kron(D2,I)
u = np.linalg.solve(L,f)
fig = plt.figure(figsize=(2*M,2*M))
# The spy of the Laplacian
plt.subplot(221)
plt.spy(L)
# Plotting the approximation and its interpolation
# The numerical approximation
uu = np.zeros((N+1,N+1))
uu[1:-1,1:-1]=np.reshape(u,(N-1,N-1))
xx,yy=np.meshgrid(x,y)
value = uu[int(N/4),int(N/4)]
plt.subplot(222,projection='3d')
ax = fig.gca()
#surf = ax.plot_surface(xxx, yyy, uuu_n, rstride=1, cstride=1, cmap=cm.coolwarm,
# linewidth=0, antialiased=False)
ax.plot_wireframe(xx, yy, uu)
ax.view_init(elev,azim)
# The INTERPOLATED approximation
N_fine=4*N
finer_mesh=np.linspace(-1,1,N_fine)
xxx,yyy=np.meshgrid(finer_mesh,finer_mesh)
uuu = spf.interpolate.interp2d(xx, yy, uu, kind='linear')
uuu_n=np.reshape(uuu(finer_mesh,finer_mesh),(N_fine,N_fine))
plt.subplot(224,projection='3d')
ax = fig.gca()
surf = ax.plot_surface(xxx, yyy, uuu_n, rstride=1, cstride=1, cmap=cm.coolwarm,
linewidth=0, antialiased=False)
#ax.plot_wireframe(xxx, yyy, uuu_n)
fig.colorbar(surf)
ax.view_init(elev,azim)
plt.subplot(223)
ax = fig.gca()
#surf = ax.plot_surface(xxx, yyy, uuu_n, rstride=1, cstride=1, cmap=cm.coolwarm,
# linewidth=0, antialiased=False)
extent = [x[0], x[-1], y[0], y[-1]]
plt.imshow(uu, extent=extent)
plt.ylabel('$y$')
plt.xlabel('$x$')
plt.colorbar()
plt.show()
interact(example_5,N=(3,20),elev=elev_widget,azim=azim_widget) | SC5/04 Numerical Example of Spectral Differentiation.ipynb | tclaudioe/Scientific-Computing | bsd-3-clause |
Example 6: (2D) Helmholtz equation $u_{xx}+u_{yy}+k^2\,u=f$ with u=0 on $\partial\Gamma$ | elev_widget = IntSlider(min=0, max=180, step=10, value=40)
azim_widget = IntSlider(min=0, max=360, step=10, value=230)
def example_6(N=10,elev=40,azim=230,k=9,n_contours=8):
D,x = cheb(N)
y=x
D2 = np.dot(D,D)
D2 = D2[1:-1,1:-1]
xx,yy=np.meshgrid(x[1:-1],y[1:-1])
xx = xx.flatten()
yy = yy.flatten()
f = np.exp(-10.*((yy-1.)**2+(xx-.5)**2))
I = np.eye(N-1)
# The Laplacian
L = np.kron(I,D2)+np.kron(D2,I)+k**2*np.eye((N-1)**2)
u = np.linalg.solve(L,f)
fig = plt.figure(figsize=(2*M,2*M))
# Plotting the approximation and its interpolation
# The numerical approximation
uu = np.zeros((N+1,N+1))
uu[1:-1,1:-1]=np.reshape(u,(N-1,N-1))
xx,yy=np.meshgrid(x,y)
value = uu[int(N/4),int(N/4)]
plt.subplot(221,projection='3d')
ax = fig.gca()
#surf = ax.plot_surface(xxx, yyy, uuu_n, rstride=1, cstride=1, cmap=cm.coolwarm,
# linewidth=0, antialiased=False)
ax.plot_wireframe(xx, yy, uu)
ax.view_init(elev,azim)
plt.subplot(222)
plt.contour(xx, yy, uu, n_contours,
colors='k', # negative contours will be dashed by default
)
# The INTERPOLATED approximation
N_fine=4*N
finer_mesh=np.linspace(-1,1,N_fine)
xxx,yyy=np.meshgrid(finer_mesh,finer_mesh)
uuu = spf.interpolate.interp2d(xx, yy, uu, kind='linear')
uuu_n=np.reshape(uuu(finer_mesh,finer_mesh),(N_fine,N_fine))
plt.subplot(223,projection='3d')
ax = fig.gca()
#surf = ax.plot_surface(xxx, yyy, uuu_n, rstride=1, cstride=1, cmap=cm.coolwarm,
# linewidth=0, antialiased=False)
ax.plot_wireframe(xxx, yyy, uuu_n)
ax.view_init(elev,azim)
plt.subplot(224)
plt.contour(xxx, yyy, uuu_n, n_contours,
colors='k', # negative contours will be dashed by default
)
plt.show()
interact(example_6,N=(3,30),elev=elev_widget,azim=azim_widget,k=(1,20),n_contours=(5,12)) | SC5/04 Numerical Example of Spectral Differentiation.ipynb | tclaudioe/Scientific-Computing | bsd-3-clause |
Example 7: (2D) $-(u_{xx}+u_{yy})=\lambda\,u$ with u=0 on $\partial\Gamma$ | elev_widget = IntSlider(min=0, max=180, step=10, value=40)
azim_widget = IntSlider(min=0, max=360, step=10, value=230)
N_widget = IntSlider(min=2, max=30, step=1, value=10)
j_widget = IntSlider(min=1, max=20, step=1, value=1)
def update_j_range(*args):
j_widget.max = (N_widget.value-1)**2
j_widget.observe(update_j_range, 'value')
def example_7(N=10,elev=40,azim=230,n_contours=8,j=1):
D,x = cheb(N)
y=x
D2 = np.dot(D,D)
D2 = D2[1:-1,1:-1]
xx,yy=np.meshgrid(x[1:-1],y[1:-1])
xx = xx.flatten()
yy = yy.flatten()
I = np.eye(N-1)
# The Laplacian
L = (np.kron(I,-D2)+np.kron(-D2,I))
lam, V = np.linalg.eig(L)
ii=np.argsort(np.real(lam))
lam=lam[ii]
V=V[:,ii]
fig = plt.figure(figsize=(2*M,M))
# Plotting the approximation and its interpolation
# The numerical approximation
vv = np.zeros((N+1,N+1))
vv[1:-1,1:-1]=np.reshape(np.real(V[:,j-1]),(N-1,N-1))
xx,yy=np.meshgrid(x,y)
plt.subplot(221,projection='3d')
ax = fig.gca()
#surf = ax.plot_surface(xxx, yyy, uuu_n, rstride=1, cstride=1, cmap=cm.coolwarm,
# linewidth=0, antialiased=False)
ax.plot_wireframe(xx, yy, vv)
plt.title('eig '+str(j)+'/ (pi/2)**2= '+str(lam[j-1]/((np.pi/2)**2)))
ax.view_init(elev,azim)
plt.subplot(222)
plt.contour(xx, yy, vv, n_contours,
colors='k', # negative contours will be dashed by default
)
# The INTERPOLATED approximation
N_fine=4*N
finer_mesh=np.linspace(-1,1,N_fine)
xxx,yyy=np.meshgrid(finer_mesh,finer_mesh)
vvv = spf.interpolate.interp2d(xx, yy, vv, kind='linear')
vvv_n=np.reshape(vvv(finer_mesh,finer_mesh),(N_fine,N_fine))
plt.subplot(223,projection='3d')
ax = fig.gca()
#surf = ax.plot_surface(xxx, yyy, uuu_n, rstride=1, cstride=1, cmap=cm.coolwarm,
# linewidth=0, antialiased=False)
ax.plot_wireframe(xxx, yyy, vvv_n)
ax.view_init(elev,azim)
plt.subplot(224)
plt.contour(xxx, yyy, vvv_n, n_contours,
colors='k', # negative contours will be dashed by default
)
plt.show()
interact(example_7,N=N_widget,elev=elev_widget,azim=azim_widget,n_contours=(5,12),j=j_widget) | SC5/04 Numerical Example of Spectral Differentiation.ipynb | tclaudioe/Scientific-Computing | bsd-3-clause |
A good basic unit of computation for comparing the summation algorithms might be to count the number of assignment statements performed. | def findmin(X):
start=time.time()
minval= X[0]
for ele in X:
if minval > ele:
minval = ele
end=time.time()
return minval, end-start
def findmin2(X):
start=time.time()
L = len(X)
overallmin = X[0]
for i in range(L):
minval_i = X[i]
for j in range(L):
if minval_i > X[j]:
minval_i = X[j]
if overallmin > minval_i:
overallmin = minval_i
end=time.time()
return overallmin, end-start
import random
for i in range(5):
print("findmin is %d required %10.7f seconds" % findmin( [random.randrange(1000000) for _ in range(10000*10**i)] ) )
for i in range(5):
print("findmin2 is %d required %10.7f seconds" % findmin2( [random.randrange(1000000) for _ in range(10000*10**i)] ) ) | crack/BigO.ipynb | ernestyalumni/CompPhys | apache-2.0 |
cf. 2.4. An Anagram Detection Example | def anagramSolution(s1,s2):
""" @fn anagramSolution
@details 1 string is an anagram of another if the 2nd is simply a rearrangement of the 1st
'heart' and 'earth' are anagrams
'python' and 'typhon' are anagrams
"""
A = list(s2) # Python strings are immutable, so make a list
pos1 = 0
stillOK = True
while pos1 < len(s1) and stillOK:
pos2 = 0
found = False
while pos2 < len(A) and not found:
if s1[pos1] == A[pos2]: # given s1[pos1], try to find it in A, changing pos2
found = True
else:
pos2 = pos2+1
if found:
A[pos2] = None
else:
stillOK = False
pos1 = pos1 + 1
return stillOK
anagramSolution("heart","earth")
anagramSolution("python","typhon")
anagramSolution("anagram","example") | crack/BigO.ipynb | ernestyalumni/CompPhys | apache-2.0 |
2.4.2. Sort and Compare Solution 2 | def anagramSolution2(s1,s2):
| crack/BigO.ipynb | ernestyalumni/CompPhys | apache-2.0 |
For the record, we should mention that there exist many other libraries in Python to parse XML, such as minidom or BeautifulSoup which is an interesting library, when you intend to scrape data from the web. While these might come with more advanced bells and whistles than lxml, they can also be more complex to use, which is why we stick to lxml in this course. Let us now import our sonnet in Python, which has been saved in the file sonnet18.xml: | tree = etree.parse("data/TEI/sonnet18.xml")
print(tree) | Chapter 8 - Parsing XML.ipynb | mikekestemont/ghent1516 | mit |
Now let us start processing the contents of our file. Suppose that we are not really interested in the full hierarchical structure of our file, but just in the rhyme words occuring in it. The high-level function interfind() allows us to easily select all rhyme-element in our tree, regardless of where exactly they occur. Because this functions returns a list of nodes, we can simply loop over them: | for node in tree.iterfind("//rhyme"):
print(node) | Chapter 8 - Parsing XML.ipynb | mikekestemont/ghent1516 | mit |
Note that the search expression ("//rhyme") has two forward slashes before our actual search term. This is in fact XPath syntax, and the two slashes indicate that the search term can occur anywhere (e.g. not necessarily among a node's direct children). Unfortunately, printing the nodes themselves again isn't really insightful: in this way, we only get rather prosaic information of the Python objects holding our rhyme nodes. We can use the .tag property to print the tag's name: | for node in tree.iterfind("//rhyme"):
print(node.tag) | Chapter 8 - Parsing XML.ipynb | mikekestemont/ghent1516 | mit |
To extract the actual rhyme word contained in the element, we can use the .text property of the nodes: | for node in tree.iterfind("//rhyme"):
print(node.text) | Chapter 8 - Parsing XML.ipynb | mikekestemont/ghent1516 | mit |
OK: under this directory, we appear to have a bunch of XML-files, but their titles are just numbers, which doesn't tell us a lot. Let's have a look at what's the title and author tags in these files: | for filename in os.listdir(dirname):
if filename.endswith(".xml"):
print("*****")
print("\t-", filename)
tree = etree.parse(dirname+filename)
author_element = tree.find("//author") # find vs iterfind!
print("\t-", author_element.text)
title_element = tree.find("//title")
print("\t-", title_element.text) | Chapter 8 - Parsing XML.ipynb | mikekestemont/ghent1516 | mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.