Class: ActiveRecord::Associations::BelongsToPolymorphicAssociation
| Relationships & Source Files | |
| Super Chains via Extension / Inclusion / Inheritance | |
|
Class Chain:
|
|
|
Instance Chain:
|
|
| Inherits: |
ActiveRecord::Associations::BelongsToAssociation
|
| Defined in: | activerecord/lib/active_record/associations/belongs_to_polymorphic_association.rb |
Overview
Active Record Belongs To Polymorphic Association
Class Method Summary
Association
- Inherited
Instance Attribute Summary
- #saved_change_to_target? ⇒ Boolean readonly
- #target_changed? ⇒ Boolean readonly
- #target_previously_changed? ⇒ Boolean readonly
BelongsToAssociation
- Inherited
| #saved_change_to_target?, #target_changed?, #target_previously_changed?, #updated?, #find_target?, #foreign_key_present?, #require_counter_update? |
Association
- Inherited
| #disable_joins, | |
| #loaded? | Has the target been already loaded? |
| #options, #owner, #reflection, | |
| #stale_target? | The target is stale if the target no longer points to the record(s) that the relevant foreign_key(s) refers to. |
| #target, | |
| #target= | Sets the target of this association to |
| #find_target, #find_target?, | |
| #foreign_key_present? | Returns true if there is a foreign key present on the owner which references the target. |
| #violates_strict_loading? |
Instance Method Summary
- #klass
- #inverse_reflection_for(record) private
- #raise_on_type_mismatch!(record) private
- #replace_keys(record, force: false) private
- #stale_state private
BelongsToAssociation
- Inherited
SingularAssociation
- Inherited
| #build, | |
| #force_reload_reader | Implements the reload reader method, e.g. |
| #reader | Implements the reader method, e.g. |
| #writer | Implements the writer method, e.g. |
| #_create_record, #find_target, #replace, #scope_for_create, #set_new_record |
Association
- Inherited
| #create, #create!, #extensions, #initialize_attributes, #inversed_from, #inversed_from_queries, | |
| #klass | Returns the class of the target. |
| #load_target | Loads the target if needed and returns it. |
| #loaded! | Asserts the target has been loaded setting the loaded flag to |
| #marshal_dump | We can’t dump @reflection and @through_reflection since it contains the scope proc. |
| #marshal_load, | |
| #reload | Reloads the target and returns |
| #remove_inverse_instance | Remove the inverse association, if possible. |
| #reset | Resets the loaded flag to |
| #reset_negative_cache, #reset_scope, #scope, | |
| #set_inverse_instance | Set the inverse association, if possible. |
| #set_inverse_instance_from_queries, | |
| #association_scope | The scope for this association. |
| #build_record, #enqueue_destroy_association, | |
| #ensure_klass_exists! | Reader and writer methods call this so that consistent errors are presented when the association target class does not exist. |
| #foreign_key_for? | Returns true if record contains the foreign_key. |
| #inversable?, #inverse_association_for, | |
| #inverse_reflection_for | Can be redefined by subclasses, notably polymorphic belongs_to The record parameter is necessary to support polymorphic inverses as we must check for the association in the specific class of the record. |
| #invertible_for? | Returns true if inverse association on the given record needs to be set. |
| #matches_foreign_key?, | |
| #raise_on_type_mismatch! | Raises |
| #scope_for_create, | |
| #skip_statement_cache? | Returns true if statement cache should be skipped on the association reader. |
| #skip_strict_loading, | |
| #stale_state | This should be implemented to return the values of the relevant key(s) on the owner, so that when stale_state is different from the value stored on the last find_target, the target is stale. |
| #target_scope | Can be overridden (i.e. in |
Constructor Details
This class inherits a constructor from ActiveRecord::Associations::Association
Instance Attribute Details
#saved_change_to_target? ⇒ Boolean
(readonly)
[ GitHub ]
# File 'activerecord/lib/active_record/associations/belongs_to_polymorphic_association.rb', line 20
def saved_change_to_target? super || owner.saved_change_to_attribute?(reflection.foreign_type) end
#target_changed? ⇒ Boolean
(readonly)
[ GitHub ]
# File 'activerecord/lib/active_record/associations/belongs_to_polymorphic_association.rb', line 12
def target_changed? super || owner.attribute_changed?(reflection.foreign_type) end
#target_previously_changed? ⇒ Boolean
(readonly)
[ GitHub ]
# File 'activerecord/lib/active_record/associations/belongs_to_polymorphic_association.rb', line 16
def target_previously_changed? super || owner.attribute_previously_changed?(reflection.foreign_type) end
Instance Method Details
#inverse_reflection_for(record) (private)
[ GitHub ]# File 'activerecord/lib/active_record/associations/belongs_to_polymorphic_association.rb', line 35
def inverse_reflection_for(record) reflection.polymorphic_inverse_of(record.class) end
#klass
[ GitHub ]# File 'activerecord/lib/active_record/associations/belongs_to_polymorphic_association.rb', line 7
def klass type = owner[reflection.foreign_type] type.presence && owner.class.polymorphic_class_for(type) end
#raise_on_type_mismatch!(record) (private)
[ GitHub ]# File 'activerecord/lib/active_record/associations/belongs_to_polymorphic_association.rb', line 39
def raise_on_type_mismatch!(record) # A polymorphic association cannot have a type mismatch, by definition end
#replace_keys(record, force: false) (private)
[ GitHub ]# File 'activerecord/lib/active_record/associations/belongs_to_polymorphic_association.rb', line 25
def replace_keys(record, force: false) super target_type = record ? record.class.polymorphic_name : nil if force || owner._read_attribute(reflection.foreign_type) != target_type owner[reflection.foreign_type] = target_type end end
#stale_state (private)
[ GitHub ]# File 'activerecord/lib/active_record/associations/belongs_to_polymorphic_association.rb', line 43
def stale_state foreign_key = super foreign_key && [foreign_key.to_s, owner[reflection.foreign_type].to_s] end


Set or Modify a mark depending of the student's array. - Set : If no
marks is in the specified index, we add the new mark in the array. -
Modify : If a mark does exist in a index of the student's array, we
modify it with the new value.
Set or Modify a mark depending of the student's array. - Set : If no
marks is in the specified index, we add the new mark in the array. -
Modify : If a mark does exist in a index of the student's array, we
modify it with the new value.
Set or Modify a mark depending of the student's array. - Set : If no
marks is in the specified index, we add the new mark in the array. -
Modify : If a mark does exist in a index of the student's array, we
modify it with the new value.


|
Skyblock AI is a bot that tries to make your Skyblock experience as good as possible. You can check the auction and bazaar prices or view the bazaar price history to maximize your profit. You can check your progress, have your networth calculated or get a hint of what you might do if you are new to the game. Skyblock AI also has a timer command so you know when the next events are coming up.
Skyblock AI is constantly being improved and has a steadily growing community.
|


Summer is fast approaching, and with it, music festival season! Large scale dance music events take place all over the world from Tomorrowland in Boom, Belgium to the Full Moon Parties of Thailand- but many of these festivals happen right here in the western portion of the United States! Today we are going to take a tour of some of the amazing events coming up this year that are scheduled to take place right in our backyard!
In 2012, United States of Conciousness and Live Nation hosted the very first Paradios Music Festival at the George Ampitheater in George, Washingtion. Now in its 5th year, the two day festival features three diverse stages hosting a wide variety of dance music artists, live art, and much more! This year's lineup is still yet to be relased but past years have featured headliners such as Skrillex, Bassnectar, Armin Van Buren, Zedd, Above & Beyond and Zedd!
Paradiso Music Festival is widely regarded as the largest electronic music event in the Pacific Northwest, attracting more than 20,000 fans from all over the world in 2016! The Gorge Ampitheater offers a picturesque backdrop for what many ravers in the northwest as the best weekend of the year
This years festival takes place on Friday, June 23rd and Saturday, June 24th. Those wishing to attend Paradiso Music Festival can find tickets and camping passes avalible at http//:paradisofestival.com.
What The Festival is an immersive art and music festival experience taking place each summer in Wolf Run Ranch, Oregon at the edge of the Mount Hood National Forest. The festival website describes its mission statement as "Our mission is simple: We want to move your bodies, senses, and souls. We want you to leave feeling connected and to be inspired from your full immersion into art, music, and community." This years headliners include Zhu, Cut Copy, and Gramatik
Feeling the Pacific Northwest’s growing desire for a transformational festival with an electronic music and visual art component, the founders of What The Festival were inspired by their years of involvement at Burning Man and music production. What started as a vision, quickly became a tangible reality in 2012. In its first year, What The Festival was hosted at White River Canyon, Oregon, then graduated the following year to the now-permanent-home of Wolf Run Ranch where it has remained ever since. Five years later, What The Festival has grown but the boutique experience has not disappeared. As our pack grows larger, so do our hearts, and we invite you to participate to the fullest.
What the Festival takes place this Summer from June 16th-19th at Wolf Run Ranch, OR. Tickets are still avalible at http://whatthefestival.com/weekend-passes/
What The Festival 2016 | (OFFICIAL) After Movie from What The Festival on Vimeo.
Symbiosis Presents: Oregon Eclipse 2017 is by far and away the most unique event on this tour as the festival serves to mark the upcoming total solar eclipse that will be visible in the area durring the festival durratoin. This event is a collaboration between festival throwing companies the world over working to bring a powerful experience to patrons in attendance. Oregon Eclipse is only going to happen once, and will feature eight stages hosting performaces of all types from heavy bass music to live theatrical performances. Families are encouraged to attend with ample opportunites for fun and personal growth for people of all ages!
This experience will see a coming together of peoples that will happen one time only in alignment with one of the most spectacular phenomena one can ever witness.
Experience Passes are still avalible at http://oregoneclipse2017.com/trailblazer-pass/
Total Solar Eclipse Explainer from Symbiosis Gathering on Vimeo.
Lightning in a Bottle (LIB) is a transformational festival in the Central Coast region of California presented by The Do LaB. The Do LaB seeks to promote sustainability, social cohesion, personal health, and creative expression. They have also contributed art installations to the Coachella Valley Music and Arts Festival in Indio, California.
The festival returning to its home in San Antonio Reservoir Recreation Area in Bradley, CA for its 17th iteration. Headliners this year include Bassnectar, Rufus Del Sol, Troyboi, and Kaytranata
Small numbers of tier three tickets are still avalible at https://www.eventbrite.com/e/lightning-in-a-bottle-arts-music-festival-2017-tickets-30281032383
Electric Daisy Carnival, commonly known as EDC, is one of the biggest electronic dance music festivals in the world, with its flagship held annually in Las Vegas, Nevada. Big name electronic dance producers and DJ's such as Diplo, Jauz, the Chainsmokers, and Tiësto perform at the many locations held yearly for EDC. The festival incorporates various styles of dance music including trap, bounce, trance, techno, bass, house, and more.
Insomnica Events has grown up to host EDC events all over the world, with the second largest next to the Vegas festival taking place in Mexico City this year. Additionally, 2016 saw the launch of EDC Week taking place at nightclubs and pool parties all up and down the Las Vegas strip durring the week leading up to the festival. This year's lineup is still to be announced, however dance music fans can be assured that the festival will always bring about the absolute best of the best.
This year's event is taking place from June 16th-June 18th. Tickets and shuttle passes for this year's EDC are avalible at http://lasvegas.electricdaisycarnival.com/2016/11/28/edc-las-vegas-2017-tickets-sale-now/
Whether one is looking to venture far from home to experience this summer's festival season, or simply take a jaunt in one's own backyard, those looking to party hard this summer have many many options open to them. Whether or not one is looking for a spiritually empowereing time spent taking in art in its many forms, or looking to be transported into a technicolor pipedream of sounds and lights, there is a festival out here in the west for you!
No matter where you end up this festival season, please remember that the law is the law, and all choices have consequences. Please party safe, drink lots of water, take care of your friends, drink even more water, and remember to keep the PLUR spirit alive!


Deadline: November 19, 2017
Submit: by web form
General rules: Read them carefully
Implement two versions of Fibonacci heaps, the one presented during the lecture and a naive version that ignores the flags of nodes, i.e. it will not perform any cascading cuts:
Examine the behaviour of these two data structures on test data generated by the program described below. The test data contains sets of varying sizes with three kinds of operations:
Your task is to determine the average number of steps that an ExtractMin operation takes. The number of steps of one such operation is the number of children of the deleted node that are appended to the list of trees, plus the number of times some tree is linked to another tree during the subsequent consolidation procedure.
Download the generator and run it with the following parameters:
-s XX
, where XX are the last two digits of your student ID;
-r
, to generate the random test;
-b
, to generate the biased test;
-x
, to generate the special test. (Beware: the output has some 68GB,
so you probably don't want to store it to a file; instead, pipe it directly to your program.)
The output of the generator is a text file. Each line specifies a single operation on the tree:
# N
: start a test in which N elements need to be stored in a heap – discard the previous heap and create a new one (the set size can be useful for plotting);
INS E K
: insert the element E with key K to the heap;
DEL
: delete the element with minimum key (if several elements have the same key, only delete one of them);
DEC E K
: decrease the key of element E to key K (if the element E does not exist, or its key is smaller than K already, ignore this operation).
A single call of the generator creates a sequence of tests with at most 2.000.000 elements each. The element identifiers E are integers from 0 to N-1. Each identifier is unique, i.e., you can assume that at any time there is at most one element with identifier E stored in the heap. However after an element was deleted, it may be inserted again at a later time. The keys K are not unique, i.e. at any time there may be several elements with the same key stored in the heap. Make sure you have pointers to elements so you have direct access to them during a Decrease operation.
Draw plots showing the dependence of the average number of steps of a ExtractMin operation on the size N.
#4
INS 0 3
DEC 0 0
DEL
INS 1 2
DEC 1 0
DEL
INS 2 1
DEC 2 0
INS 3 3
# 5
INS 0 3
DEL
DEC 0 0
INS 1 1
DEC 1 0
DEL
INS 2 4
INS 3 4
DEC 3 0
DEC 2 0
DEL
DEL
INS 2 2


The first list is a list of marked boards and boards containing marked or bookmarked threads.
The following list is a list of marked and bookmarked threads.
Click a board name to list threads on the board, then click a thread name to jump the thread.
Icons are links to following pages:
∷ - To the list of boards,
≋ - To a list of threads on a board,
All. - To a thread view of all posts,
l50 - To a thread view of latest 50 posts,
⥸ - To a thread view of posts after bookmark.
Thread name is a link as same as All. or l50 that is not displayed.
Setting of 'Link to all posts' in 'List of threads' determines whether a link to each posts becomes an icon or a title.
To reflect some settings to tabs, you need to reload.
To reflect language setting to this popup, you need to reopen.
Storage data handling
Unlock to initialize
When you click 'export', storage data - favorites, blocking IDs, and settings - are downloaded from local storage.
When you click 'import' and select a file, storage data are cleared, then the file data are imported.
When you unlock and click 'Initialize', storage data are cleared and initialized.
So exporting before importing or initializing are recommended.


A cyber defense competition is comprised of
A cyber defense competition can educate its participants by training them to work as a team on securing their servers. In today's cyber-based world, demand for cybersecurity experts is higher than ever, and PGCDC provides a realistic environment to learn and have fun.
Teamwork is one of the most valuable skills to have. Developing the ability to work and coordinate with a group of people during earlier years undoubtably helps with a professional life later on.
Participating in a CTF requires self-exploration and constructive problem solving. Learning to find answers to problems without dependence on an educator is crucial for many modern career paths.
Throughout a CTF, the participants learn new tactics on approaching complex concepts like creating algorithms, performing cyber-forensics on various media, and penetration testing websites professionally.
Creating a professional network is an important factor in success. Having people to ask questions, get resources, and collaborate with can be incredibly beneficial when looking ahead.


| Class | Description |
|---|---|
| AbsoluteValue |
AbsoluteValue represents the function "abs" which denotes the distance from 0 to the value in question.
|
| ExpressionGeneratorParallel |
ExpressionGeneratorParallel is essentially a wrapper around ExpressionParallel in that it represents a whole expression along with associated methods that help create it and evaluate it.
|
| ExpressionParallel |
ExpressionParallel represents a mathematical "expression," by which is meant either a representation of a variable, a mathematical operator, or a mathematical function (such
as those of trigonometry). |
| ExpressionParallel.Average |
Average represents the operation of averaging (i.e. the mean).
|
| ExpressionParallel.Cos |
Cos represents the trigonometric operation cosine.
|
| ExpressionParallel.Multiply |
Multiply represents the operator *.
|
| ExpressionParallel.Sin |
Sin represents the trigonometric operator sine.
|
| ExpressionParallel.Variable |
Variable represents a mathematical variable - to be replaced with actual values when evaluated as part of a larger expression.
|
| Power |
Power represents the exponentiation symbol, generally seen as "^".
|
| Enum | Description |
|---|---|
| ExpressionGeneratorParallel.ExpressionType |
A list of all expressions known to ExpressionGeneratorParallel.
|


Camel, cow, donkey found roaming together along Kansas road
by The Associated PressGODDARD, Kan. (AP) — Authorities have found the owners of a camel, cow and donkey that were spotted roaming together along a Kansas road in a grouping reminiscent of a Christmas Nativity scene.
Police in Goddard had asked for help over the weekend in a Facebook post locating the owners of the “three friends traveling together (towards a Northern star).” The post said that if police couldn’t find the owners, they would be “halfway toward a live nativity this Christmas season.”
No details were provided about the owners. And no one was immediately available at the police department to answer questions. Amid the search, one poster inquired, “Are there 3 wise looking men near?” Another said, “who knows, they may lead you to the second coming.”
Goddard is about 15 miles (24 kilometers) west of Wichita.


April 2020
Setting up Matterport Mask RCNN
14/04/2020
In this short article, we will set up Matterport's Mask RCNN repository.


im1.jpg | im2.jpg |
thresh = 10; % Harris corner threshold nonmaxrad = 3; % Non-maximal suppression radius im1 = imread('im1.jpg'); im2 = imread('im2.jpg'); % Find Harris corners in image1 and image2 [cim1, r1, c1] = harris(im1, 1, thresh, 3); show(im1,1), hold on, plot(c1,r1,'r+'); [cim2, r2, c2] = harris(im2, 1, thresh, 3); show(im2,2), hold on, plot(c2,r2,'r+');
w = 7; % Window size for correlation matching [m1,m2] = matchbycorrelation(im1, [r1';c1'], im2, [r2';c2'], w); % Display putative matches show(im1,3), set(3,'name','Putative matches'), hold on for n = 1:length(m1); line([m1(2,n) m2(2,n)], [m1(1,n) m2(1,n)]) end
% Assemble homogeneous feature coordinates for fitting of the % fundamental matrix, note that [x,y] corresponds to [col, row] x1 = [m1(2,:); m1(1,:); ones(1,length(m1))]; x2 = [m2(2,:); m2(1,:); ones(1,length(m1))]; t = .001; % Distance threshold for deciding outliers [F, inliers] = ransacfitfundmatrix(x1, x2, t); % Display both images overlayed with inlying matched feature points show(double(im1)+double(im2),4), set(4,'name','Inlying matches'), hold on plot(m1(2,inliers),m1(1,inliers),'r+'); plot(m2(2,inliers),m2(1,inliers),'g+'); for n = inliers line([m1(2,n) m2(2,n)], [m1(1,n) m2(1,n)],'color',[0 0 1]) end
% Step through each matched pair of points and display the % corresponding epipolar lines on the two images. l2 = F*x1; % Epipolar lines in image2 l1 = F'*x2; % Epipolar lines in image1 for n = inliers figure(1), clf, show(im1,1), hold on, plot(x1(1,n),x1(2,n),'r+'); hline(l1(:,n)); figure(2), clf, show(im2,2), hold on, plot(x2(1,n),x2(2,n),'r+'); hline(l2(:,n)); fprintf('hit any key to see next point\r'); pause end
Here's another way to visualize the matches suggested by José L. Crespo which works rather nicely. It displays each image with the putative matches marked as circles with different colors. Using the colorcube map produces different colors for nearby points allowing them to be distinguished from each other.
col=colormap(colorcube(size(m2,2))); figure(1), imshow(im1,[]), hold on scatter(m1(2,:),m1(1,:),[],col); hold off figure(2), imshow(im2,[]), hold on scatter(m2(2,:),m2(1,:),[],col); hold off


Arsenal target £43m-rated star to fix struggling defence in January
by Jaikuran RandhawaAccording to the Sun, Arsenal are considering a move for Villarreal star Pau Torres in the January transfer window in a bid to solve their defensive issues.
The 22-year-old scored on his debut for Spain last night and he’s quickly emerging as one of the best young centre-backs in Europe.
The Sun add that the defender has a £43m release clause in his contract, it will be interesting to see if the Gunners decide to splash the cash after their splurge this past summer.
The report reiterates that the north London outfit would hope to structure a potential deal for the defender in a similar manner to the way in which they secured Nicolas Pepe from Lille this summer.
Arsenal only paid £20m of the total £72m deal up front, as per the Sun.
Unfortunately, the Gunners may have to battle Manchester City for the defender’s signature.
Unai Emery has so far failed to address Arsenal’s key shortcoming since being appointed – the team’s defence.
The Gunners are sitting sixth in the Premier League, yet they have the joint-worst goal difference (-1) of sides in the top ten. This isn’t good enough for a team that hope to get themselves back in to the Champions League spots.
Torres could prove to be an excellent signing for the Gunners, the ace would add to an already young defensive line that are yet to fully take shape.
Hector Bellerin, Kieran Tierney, Rob Holding and even Calum Chambers have the potential to lead the team in the future.
Perhaps the best way to ensure Arsenal solve their defensive problems is to install a young foundation of talent at the back.


Toggle navigation
Quizrr-Viz
member
question
Add Graph!
Lesson Id
Graph
Change Defaults
History
Change Defaults
K-Factor:
Streak Factor:
Member Rating:
Easy Question:
Normal Question:
Difficult Question:
History


Metadata is provides using the classes BeanDomain, BeanClass and BeanProperty.
It is recommended to derive a class from BeanDomain and provide a description for every contained class
using a nested class derived from BeanClass. Then in each BeanClass' constructor define the list of properties
by using the add() Method, which will return a BeanProperty object. This may be stored in a final field for static
metadata access.
The class BeanRecordProxy allows accessing JavaBean to DTO data though the Record interface defined in the org.apache.empire.data namespace.


{% extends 'base.html' %} {% block content %}
This project is aimed to help Pytorch machine learning developers to quickly build a Flask
web app
in a Docker container ready to be deployed.
View on GitHub
Models hacked by Ross Wrightman were used to train datasets
View on GitHub .


VSL // Going Underground
* In this video, Craig Thornton, the head chef and creator of LA-based underground dining concept, Wolvesmouth, talks about the art of underground dining
today’s Very Short List:
food 24 Apr 2014
Jenny Nguyen is a lifestyle and food writer based in NYC. She runs the curated hotspots & travel website Melting Butter
Subscribe
* Boiler Room is an underground music project from London that travels the world holding intimate live DJ performances, which are streamed to their website. Here’s one on a Melbourne rooftop with Australia’s Chet Faker
* Who gives better recommendations for restaurants and bars than chefs and sommeliers? Err, no one? That’s why I use Find. Eat. Drink.
http://link.nyobserver.com/516ca68465217dc6e1b9a3a61jr04.bi7/TvnrKi0WTdwTHwxwCf759
delightful e-mail that shares
cultural gems from a
different curator every day.
If you have any problems reading this e-mail, click here
http://link.nyobserver.com/516ca68465217dc6e1b9a3a61jr04.bi7/U0ILYuYQM8j0qcEEC5671
Subscribe
Forward
My Account
Unsubscribe
tech 23 Apr 2014
William Pearce on discovery technology.
culture 21 Apr 2014
Alexa Jaccarino on non-profit organizations with the future in mind.
food 18 Apr 2014
Pastry Chef Claire Livia Lassam on the food blogs that get her electric mixers stirring.
Editorial Policy
Privacy Policy
Contact Us
Press
Terms + Conditions
very fine print: ©2014
Observer VSL LLC.
321 West 44th Street, 6th Floor
New York, NY 10036 USA
All rights reserved.
Questions?<PHONE_NUMBER>.
This message was intended for<EMAIL_ADDRESS>If you believe this has been sent to you in error, please safely unsubscribe


6 study tips science has proven to help you ace your next test
02 Apr 2016Get plenty of sleep
Why:
Lack of sleep can cause memory-less and can leave you feeling sluggish. So get plenty of rest to maintain an alert state, that way you have more energy to study and concentrate.
Create a study schedule and stick to it
Why:
By creating a study schedule you can organize your methodology before starting, giving you clear goals in order to achieve success. In addition by maintaining a schedule, you are less likely to procrastinate.

Study in a group
Why:
By forming study groups not only can you make studying more fun but you can can have other insure that you are kept on track.
Create songs and stories about your studies
Why:
The brain is far more likely to recall a song or story than it is to recall pure information from a text book. If the thing your studying about is important, give it a memorable story to embed it in to your brain.
Teach the material to someone else
Why:
It’s one thing to memorize some facts, but once you are able to teach it you can truly say you understand the material. Find a room mate who is willing to listen, set up a power point and teach him your ways sensei.
Study before bed
Why:
When your sleeping the brain is actually moving around information and sorting facts in to categories. By studying just before bed, you solidify the facts in to your memory, therefore allowing you to recall much more than if you were studying in the morning.


@import helper._
@import uk.gov.hmrc.examplefrontend.model.User
@this(layout: Layout)
@(result:User,isUpdate:Boolean)(implicit request: Request[_], messages: Messages)
@layout(pageTitle = Some("Summary")) {
Back
Summary
Below are the details you have entered. If these are correct press Submit to complete the process or you
can alter details.
Please ensure these are correct, as some details cannot be changed after submission.
You are able to cancel your application using the Cancel button.
Cancel
}


Conversion¶
There are three sensible targets for conversion.
- GPX
- KML
- CSV
Output Formats¶
We’ll focus on GPX.
GPX¶
See http://www.topografix.com/gpx.asp
We’ll bypass formal processing of the XSD definitions. The data collected is simple. The GPWPL sentence only has lat, lon, ID The GPRTE sentences only have ID, number/total, and a list of waypoint names.
Template output for the GPX document as a whole:
<gpx
version="1.1"
creator="xsd:string [1]">
<metadata>
<name> xsd:string </name>
<desc> xsd:string </desc>
</metadata>
<wpt> wptType </wpt>
<rte> rteType </rte>
</gpx>
A waypoint (wptType):
<wpt
lat="latitudeType [1] ?"
lon="longitudeType [1] ?">
<name> xsd:string </name>
</wpt>
A route (rteType):
<rte>
<name> xsd:string </name>
<number> xsd:nonNegativeInteger </number>
<desc> xsd:string </desc>
<rtept> wptType </rtept>
</rte>
KML¶
Here’s another XML data structure we could emit.
https://developers.google.com/kml/documentation/kmlreference
CSV¶
There’s no formal schema for the CSV representation of points and routes. In order to work with these, concrete examples from GPSNavX and the new Zeus2 chart plotter are required.
Conversion Processing¶
The conversion process involves two steps.
- Load the JSON version of the saved sentences.
- Create an XML document using GPX tags.
There are two variations.
- Convert a saved route.
- Convert the saved waypoint list.
Each route contains duplicate copies of relevant waypoints. It looks like GPSNavX handles this by appending a suffix to the waypoint to distinguish duplicate copies.
Note that the legacy chartplotter names are highly abbreviated, upper-case only.
After conversion, it’s helpful to manually edit the GPX documents to write more informative waypoint and route names.
Example¶
MacBookPro-SLott:NMEA-Tools slott$ python3 -m nmeatools.waypoint_to_gpx /Users/slott/Documents/Sailing/Cruise\ History/routes/rt1.json --desc '2017 Waypoints from Red Ranger chartplotter.' --force
INFO:__main__:Read route from /Users/slott/Documents/Sailing/Cruise History/routes/rt1.json
INFO:__main__:GPWPL 37°50.45′N 76°16.406′W REEDVILLE
INFO:__main__:GPWPL 37°50.356′N 76°16.521′W WPT017
INFO:__main__:GPWPL 37°50.21′N 76°16.701′W WPT018
INFO:__main__:GPWPL 37°50.081′N 76°16.764′W WPT016
INFO:__main__:GPWPL 37°49.939′N 76°16.986′W WPT015
INFO:__main__:GPWPL 37°49.875′N 76°16.911′W COCK CR ST
INFO:__main__:GPWPL 37°49.35′N 76°16.858′W COCK CR RU
INFO:__main__:GPWPL 37°49.122′N 76°17.017′W COCK CR 1
INFO:__main__:GPWPL 37°48.492′N 76°17.557′W GWICO 6
INFO:__main__:GPWPL 37°48.326′N 76°16.915′W GWICO 4
INFO:__main__:GPWPL 37°48.007′N 76°15.793′W GWICO 2
INFO:__main__:GPWPL 37°46.894′N 76°12.375′W GWICO 1
INFO:__main__:GPWPL 37°40.722′N 76°11.616′W CHES 59A
INFO:__main__:GPWPL 37°34.341′N 76°11.882′W RAP 2R
INFO:__main__:GPWPL 37°33.28′N 76°15.51′W PIANK2
INFO:__main__:GPWPL 37°31.99′N 76°19.02′W PIANK6
INFO:__main__:GPWPL 37°32.585′N 76°19.172′W JACKSON
INFO:__main__:GPRTE 'DLTVL RDVL' 1 c ['WPT017', 'WPT018']
INFO:__main__:GPRTE 'DLTVL RDVL' 2 c ['WPT015', 'COCK CR ST']
INFO:__main__:GPRTE 'DLTVL RDVL' 3 c ['COCK CR 1', 'GWICO 6']
INFO:__main__:GPRTE 'DLTVL RDVL' 4 c ['GWICO 2', 'GWICO 1']
INFO:__main__:GPRTE 'DLTVL RDVL' 5 c ['RAP 2R', 'PIANK2']
INFO:__main__:GPRTE 'DLTVL RDVL' 6 c ['JACKSON']
INFO:__main__:23 sentences read
INFO:__main__:Writing /Users/slott/Documents/Sailing/Cruise History/routes/rt1.gpx
Why are there extra waypoints in the waypoint list that are not referenced in the route?
Your guess is as good as mine.
The names like "DLTVL RDVL"
need to be manually changed in the resulting
GPX file to something like "Deltaville to Reedville"
.


Next: gentemp, Previous: gensym, Up: Symbols Dictionary
a non-negative integer.
implementation-dependent.
A number which will be used in constructing the name of the next symbol generated by the function gensym.
*gensym-counter* can be either assigned or bound at any time, but its value must always be a non-negative integer.
The ability to pass a numeric argument to gensym has been deprecated; explicitly binding *gensym-counter* is now stylistically preferred.


@import models.user.User @(user: Option[User] = None, isMobile: Boolean, timeSpent: Float)(implicit lang: Lang) @main("Sidewalk - Time Check") { @if(!isMobile) { @navbar(user, Some("/timeCheck")) }
This page simply shows you how long our system has logged you working on Project Sidewalk. Crunching the numbers can take a while, so please be patient if the page take a long time to load!
If you see a large discrepancy between the time below and how long you estimate that you've worked on the website, you can email volunteer.sidewalk@@gmail.com to try and sort out the issue. The most common reason is that you forgot to log in while working. Try to include as much info you can about when you worked on Project Sidewalk and which pages you were using on the website at those times.
You've worked for @{"%.2f".format(timeSpent)} hours!


Posted by HouJK on January 4, 2019
Posted by HouJK on January 1, 2019
Posted by HouJK on May 10, 2018
Posted by HouJK on April 30, 2018
Posted by HouJK on April 26, 2018
Posted by HouJK on April 6, 2018
Posted by HouJK on April 5, 2018


▐ Welcome
Home
About
Log In
Register
Upload
Profile
button text
placeholdername.com is a photo sharing website where you can create an account to store images.
Login
Create an Account


Learning in deep artificial and biological neuronal networks¶
Documentation for the coding exercise from Tutorial 2¶
- API
- Controller for simulations
- Adding custom functions to PyTorch’s autograd
- Adding custom functions for feedback alignment to PyTorch’s autograd
- A linear layer module that maintains its own parameters
- A linear layer module for FA that maintains its own parameters
- Implementation of a Multi-layer Perceptron (MLP)
- A collection of helper functions
- Testing
In tutorial 2.1, you will be implementing parts of the backpropagation algorithm by completing missing parts in the module lib.backprop_functions
. Tutorial 2.2 is similar in spirit, but you will modify your implementations of the backward pass in lib.feedback_alignment_functions
to implement the Feedback-Alignment (FA) algorithm. Please scroll down for extra information on tutorial 2.1 and 2.2.
Tutorial 2.1 – 30.09.2020¶
In the tutorial session on Sep. 30th, 2020 you have seen how to derive the backpropagation update rules. In this exercise, you are going to implement the forward and backward pass for core blocks that are often used in Artificial Neural Networks.
Please refer to the API to get an overview of the coding structure.
You can test your implementations by following the instructions from the testing page.
In addition, you can see your code in action by learning a simple regression task via the script main
. Please study the command-line arguments on how to use the script.
$ python3 main.py --help
To visually certify the quality of the obtained predictions, you can visualize the results of a 1D regression task via
$ python3 main.py --polynomial_regression --show_plot --epochs=1000 --lr=1e-2
We recommend playing around with command-line options such as learning rate --lr
, momentum --momentum
, the number of epochs --epochs
or the batch size --batchsize
as well as the architectural options of the neural network to get a feeling for how optimization with backpropagation in neural networks behaves.
Tutorial 2.2 – Oct. 7th, 2020¶
In the tutorial session on Oct. 7th, 2020 we explained why Feedback-Alignment works and why it can be seen as a more biologically plausible variant of error-backpropagation. In this exercise, you are going to implement feedback alignment and investigate some simple toy examples to get more insight in the inner workings of Feedback-Alignment.
Please refer to the API to get an overview of the coding structure.
Below, we give you the needed commandline code for running the experiments of tutorial 2.2.
Linear student-teacher regression with feedback alignment:
$ python3 main.py --size_hidden 20 --size_input 30 --size_output 10 --num_hidden 1 --lr 1.e-1 --epochs 200 --feedback_alignment --plot_matrix_angles --linear
Nonlinear student-teacher regression with feedback alignment:
$ python3 main.py --size_hidden 20 --size_input 30 --size_output 10 --num_hidden 1 --lr 3e-1 --epochs 300 --feedback_alignment --plot_matrix_angles
Nonlinear student-teacher regression with backpropagation:
$ python3 main.py --size_input 30 --size_hidden 20 --size_output 10 --num_hidden 1 --lr 3e-1 --epochs 300
Polynomial regression with feedback alignment:
$ python3 main.py --polynomial_regression --show_plot --epochs=20000 --lr=2e-1 --feedback_alignment
Polynomial regression with backpropagation:
$ python3 main.py --polynomial_regression --show_plot --epochs=20000 --lr=2e-2
Please refer to the assignment sheet to obtain further information on how exercises have to be handed in and how they are graded. Note that you need to submit three files in total: backprop_functions.py, feedback_alignment_functions.py and a pdf file with the answers on the questions of tutorial 2.2.


‘$access/2’
’$access’/2 – determine accessability of a file
FORMS
’$access’(FileName,AccessMode)
DESCRIPTION
FileName can be a symbol, a UIA, or a list of ASCII characters. ’$access’/2 checks whether or not the given file is accessible with the given mode, where AccessMode should be one of the following:
4 : write
2 : read
0 : existence
These access modes are used as indicated on Unix systems and the Macintosh.
However, they are ignored on DOS systems. On DOS systems, the file is only
checked as to whether or not it is read accessible.
EXAMPLES
?- ’$access’(’../foo/foobar.pl’,2).
yes.


HTML Fragment Example When it is loaded, its script tag is executed by the plastic-bag, changing the message box color to green and setting a event in this button to change its own color too.


Embedded JavaScript templates
$ npm install ejs
<% %>
<%= %>
(escape function configurable)<%- %>
-%>
ending tag<%_ _%>
<? ?>
instead of <% %>
)<% if (user) { %>

<%= user.name %>

<% } %>
Try EJS online at: https://ionicabizau.github.io/ejs-playground/.
var template = ejs.compile(str, options);
template(data);
// => Rendered HTML string
ejs.render(str, data, options);
// => Rendered HTML string
ejs.renderFile(filename, data, options, function(err, str){
// str => Rendered HTML string
});
It is also possible to use ejs.render(dataAndOptions);
where you pass
everything in a single object. In that case, you'll end up with local variables
for all the passed options. However, be aware that your code could break if we
add an option with the same name as one of your data object's properties.
Therefore, we do not recommend using this shortcut.
cache
Compiled functions are cached, requires filename
filename
The name of the file being rendered. Not required if you
are using renderFile()
. Used by cache
to key caches, and for includes.root
Set project root for includes with an absolute path (/file.ejs).context
Function execution contextcompileDebug
When false
no debug instrumentation is compiledclient
When true
, compiles a function that can be rendered
in the browser without needing to load the EJS Runtime
(ejs.min.js).delimiter
Character to use with angle brackets for open/closedebug
Output generated function bodystrict
When set to true
, generated function is in strict mode_with
Whether or not to use with() {}
constructs. If false
then the locals will be stored in the locals
object. Set to false
in strict mode.localsName
Name to use for the object storing local variables when not using with
Defaults to locals
rmWhitespace
Remove all safe-to-remove whitespace, including leading
and trailing whitespace. It also enables a safer version of -%>
line
slurping for all scriptlet tags (it does not strip new lines of tags in
the middle of a line).escape
The escaping function used with <%=
construct. It is
used in rendering and is .toString()
ed in the generation of client functions. (By default escapes XML).This project uses JSDoc. For the full public API
documentation, clone the repository and run npm run doc
. This will run JSDoc
with the proper options and output the documentation to out/
. If you want
the both the public & private API docs, run npm run devdoc
instead.
<%
'Scriptlet' tag, for control-flow, no output<%_
'Whitespace Slurping' Scriptlet tag, strips all whitespace before it<%=
Outputs the value into the template (escaped)<%-
Outputs the unescaped value into the template<%#
Comment tag, no execution, no output<%%
Outputs a literal '<%'%%>
Outputs a literal '%>'%>
Plain ending tag-%>
Trim-mode ('newline slurp') tag, trims following newline_%>
'Whitespace Slurping' ending tag, removes all whitespace after itFor the full syntax documentation, please see docs/syntax.md.
Includes either have to be an absolute path, or, if not, are assumed as
relative to the template with the include
call. For example if you are
including ./views/user/show.ejs
from ./views/users.ejs
you would
use <%- include('user/show') %>
.
You must specify the filename
option for the template with the include
call unless you are using renderFile()
.
You'll likely want to use the raw output tag (<%-
) with your include to avoid
double-escaping the HTML output.

<% users.forEach(function(user){ %>
<%- include('user/show', {user: user}) %>
<% }); %>

Includes are inserted at runtime, so you can use variables for the path in the
include
call (for example <%- include(somePath) %>
). Variables in your
top-level data object are available to all your includes, but local variables
need to be passed down.
NOTE: Include preprocessor directives (<% include user/show %>
) are
still supported.
Custom delimiters can be applied on a per-template basis, or globally:
var ejs = require('ejs'),
users = ['geddy', 'neil', 'alex'];
// Just one template
ejs.render('<?= users.join(" | "); ?>', {users: users}, {delimiter: '?'});
// => 'geddy | neil | alex'
// Or globally
ejs.delimiter = '$';
ejs.render('<$= users.join(" | "); $>', {users: users});
// => 'geddy | neil | alex'
EJS ships with a basic in-process cache for caching the intermediate JavaScript
functions used to render templates. It's easy to plug in LRU caching using
Node's lru-cache
library:
var ejs = require('ejs')
, LRU = require('lru-cache');
ejs.cache = LRU(100); // LRU cache with 100-item limit
If you want to clear the EJS cache, call ejs.clearCache
. If you're using the
LRU cache and need a different limit, simple reset ejs.cache
to a new instance
of the LRU.
The default file loader is fs.readFileSync
, if you want to customize it, you can set ejs.fileLoader.
var ejs = require('ejs');
var myFileLoad = function (filePath) {
return 'myFileLoad: ' + fs.readFileSync(filePath);
};
ejs.fileLoader = myFileLoad;
With this feature, you can preprocess the template before reading it.
EJS does not specifically support blocks, but layouts can be implemented by including headers and footers, like so:
<%- include('header') -%>

Title

My page

<%- include('footer') -%>
Go to the Latest Release, download
./ejs.js
or ./ejs.min.js
. Alternately, you can compile it yourself by cloning
the repository and running jake build
(or $(npm bin)/jake build
if jake is
not installed globally).
Include one of these files on your page, and ejs
should be available globally.

Most of EJS will work as expected; however, there are a few things to note:
ejs.renderFile()
won't work.include
s do not work unless you use an IncludeCallback
. Here is an example:var str = "Hello <%= include('file', {person: 'John'}); %>",
fn = ejs.compile(str, {client: true});
fn(data, null, function(path, d){ // IncludeCallback
// path -> 'file'
// d -> {person: 'John'}
// Put your code here
// Return the contents of file as a string
}); // returns rendered string
There are a number of implementations of EJS:
Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
EJS Embedded JavaScript templates copyright 2112 mde@fleegix.org.


TMS
Timetable Management System
Make Time Slot
Timetable Management
Teacher Management
Rooms Management
Add Teacher
Male:
Female:
Add Teacher


--- layout: post date: 2009-07-17 time: "09:00:00" authors: ["Greg Wilson"] title: Day 4 tags: ["University of Alberta", "University of Toronto"] ---
Today was all about the Unix shell: Karen Reid covered a wide range of topics, often using live examples. Some of the students had never used a command-line prompt before, so all of the material was new; others already knew their way around pretty well, but Karen's explanations filled in some gaps and made sense out of what had, for some of them, seemed like arbitrary magic.
Tomorrow morning, Paul Lu is going to introduce them to Make. We're going to spend the afternoon working on the students' own problems, which range from automating workflows to visualization with VTK to manipulating geographical data with GRASS. There may also be some ice cream...


Sets the ratio of the tabs to the horizontal scrollbar.
Syntax
WORKBOOK.TAB.SPLIT(ratio_num)
Ratio_num is the ratio of tabs to horizontal scroll, as a decimal value between 0 and 1. If omitted defaults to 6.
Remarks
If the structure of the workbook is protected, you cannot use this function.
Use GET.WINDOW(28) to find out what the current ratio is.
Related Function
GET.WINDOW Returns information about a workbook window
Return to index


Provides an interface to manipulate all kind of data.
Inheritance:
Public Fields
-
int* selected_examples
- The indices of all selected examples.
-
int n_inputs
- Frame size of inputs.
-
int n_targets
- Frame size of targets.
-
int real_current_example_index
- Index of the current example.
-
Sequence* inputs
- Pointer on the inputs of the current example
-
Sequence* targets
- Pointer to the targets of the current example
-
int n_examples
- Number of examples in the dataset.
-
int n_real_examples
- Real number of examples in the dataset.
Public Methods
-
DataSet()
-
void init(int n_examples_, int n_inputs_, int n_targets_)
- Method which initializes some fields of the datasets.
-
void setExample(int t, bool set_inputs=true, bool set_targets=true)
- Set targets and inputs to the targets and inputs of the example with the index selected_examples[t].
-
virtual void setRealExample(int t, bool set_inputs=true, bool set_targets=true) = 0
- Set targets and inputs to the targets and inputs of the example with the index t.
-
virtual void pushSubset(int* subset_, int n_examples_)
- Set a new subset.
-
virtual void popSubset()
- Remove the last subset.
-
virtual void pushExample() = 0
- Tells that the current example must be kept in memory after next calls of setExample().
-
virtual void popExample() = 0
- Tells that the last pushed example will be now the current example, and therefore, will be forgeted after the next call of setExample().
-
virtual void getNumberOfFrames(int t, int* n_input_frames, int* n_target_frames) = 0
- Put in n_input_frames and n_target_frames the number of input frames and target frames for example t.
-
virtual void preProcess(PreProcessing* pre_processing) = 0
- Perform some pre-processing on data
Inherited from Object:
Public Fields
-
Allocator* allocator
Public Methods
-
void addOption(const char* name, int size, void* ptr, const char* help="")
-
void addIOption(const char* name, int* ptr, int init_value, const char* help="")
-
void addROption(const char* name, real* ptr, real init_value, const char* help="")
-
void addBOption(const char* name, bool* ptr, bool init_value, const char* help="")
-
void addOOption(const char* name, Object** ptr, Object* init_value, const char* help="")
-
void setOption(const char* name, void* ptr)
-
void setIOption(const char* name, int option)
-
void setROption(const char* name, real option)
-
void setBOption(const char* name, bool option)
-
void setOOption(const char* name, Object* option)
-
virtual void loadXFile(XFile* file)
-
virtual void saveXFile(XFile* file)
-
void load(const char* filename)
-
void save(const char* filename)
-
void* operator new(size_t size, Allocator* allocator_=NULL)
-
void* operator new(size_t size, Allocator* allocator_, void* ptr_)
-
void operator delete(void* ptr)
Documentation
Provides an interface to manipulate all kind of data.
A dataset contains two kind of things: inputs sequences
and targets sequences.
- int* selected_examples
- The indices of all selected examples.
When select_examples is false, it contains
the indices of all examples.
- int n_inputs
- Frame size of inputs.
- int n_targets
- Frame size of targets.
- int real_current_example_index
- Index of the current example.
Warning: it's the real index and not the index
in the selected_examples table.
- Sequence* inputs
- Pointer on the inputs of the current example
- Sequence* targets
- Pointer to the targets of the current example
- int n_examples
- Number of examples in the dataset.
If you're using select_examples, it's
the number of selected examples.
- int n_real_examples
- Real number of examples in the dataset.
It's the number of examples in memory.
(= n_examples if select_examples is false)
- DataSet()
- void init(int n_examples_, int n_inputs_, int n_targets_)
- Method which initializes some fields of the datasets.
It has to be called only in the constructor of your subclasses.
Just for developpers of new datasets.
- void setExample(int t, bool set_inputs=true, bool set_targets=true)
- Set targets and inputs to the targets and inputs
of the example with the index selected_examples[t].
Warning: after a setExample() the previous selected example
is not supposed to exist... for that, use pushExample().
- virtual void setRealExample(int t, bool set_inputs=true, bool set_targets=true) = 0
- Set targets and inputs to the targets and inputs
of the example with the index t. If you create a new
dataset, you must update inside current_example_index.
Warning: after a setExample() the previous selected example
is not supposed to exist... for that, use pushExample().
- virtual void pushSubset(int* subset_, int n_examples_)
- Set a new subset.
- subset_ (of size n_examples_) is a set
of indices which define a subset of data.
- if a pushSubset() has been already called,
the next pushSubset() defines a subset of the
previous subset, and so on...
- this function set select_examples to true
and set the read indices of the examples in
selected_examples.
- virtual void popSubset()
- Remove the last subset.
- recomputes "selected_examples".
- if it was the last subset, set select_examples
to false.
- virtual void pushExample() = 0
- Tells that the current example must be kept in memory
after next calls of setExample().
- virtual void popExample() = 0
- Tells that the last pushed example will be now the current
example, and therefore, will be forgeted after the next
call of setExample().
- virtual void getNumberOfFrames(int t, int* n_input_frames, int* n_target_frames) = 0
- Put in n_input_frames and n_target_frames the number
of input frames and target frames for example t.
This take subsets in account.
If one field is NULL, it will not be returned.
- virtual void preProcess(PreProcessing* pre_processing) = 0
- Perform some pre-processing on data
- Direct child classes:
- MemoryDataSet
FrameSelectorDataSet
ExampleFrameSelectorDataSet
DiskDataSet
ClassFormatDataSet
- Author:
- Ronan Collobert<EMAIL_ADDRESS>Alphabetic index HTML hierarchy of classes or Java
This page was generated with the help of DOC++.


Awesome that you got to this page. A journey starts with a step, and you have started a step. Applaud yourself!


This Video was shot in chitlang road.We were four boys riding to chitlang.Along me Rajkumar Bishwokarma, Pawan Thapa, Dibesh Babu Shrestha were there. Unfortunately,We didn't make our trip to upper side of chitlang but we enjoy alot with the views and shoot that we did.


My First jQuery
Meet the DEV Clubbers
Current list of computer-box heroes:
Overview
Does javascript magic
Bakes great cookies
Has been voted most likely to change the world in some meaningful way someday
Overview
Is currently two people
Is one of the smartest people you know
Needs to convince Luke to host a D&D session
Overview
Has a fantastic birth date
Rocks his BCGs
Seemingly reads coding books for fun
Overview
Has lovely locks
Has or is a doppelganger
Is a Git ninja
Overview
Is the only one of us actually emplyed as a programmer
Is setting up what will almost certainly be an awesome birthday trip in Savannah
May very well be radioactive
Overview
Sucks at javascript
Is trying to get better at javascript
Still really sucks at javascript
Overview
Freshly pressed and best dressed
Is absolutely crushing Ironyard
Is Zach's knight in html armor
*apologies to anyone I might have missed. This is purely a training exercise


//
about: Interests: Lycanthropy, linguistics, true crime, pop culture & flipibits /// Essay ideas
Japanese culture - body language, and cold shoulder, and passive aggression in a new level. it was hard to read social cues when they’re not being assholes. but even on a normal level, a little distress would give an idea of why something is wrong.
–
sound symbolism in branding
–
debugging through the iron curtain. the mysteries of flip bits.
–
the infuriating response of women to appease their perprator; aka chicken soup not for the soul
///
I watched Mamma Mia for the first time and wow was I missing out on a masterpiece.
It wasn’t necessarily something I usually indulge in but it made me feel so happy. weirdly so.
I read an article on it on how https://www.theguardian.com/film/2008/nov/27/women and it explained so much on how mamma mia was engineered to be a feel good movie.
for one thing, it didn’t over sexualize the female characters.
It was very interesting to see the film get totally panned by male critics, but they just didn't understand it. In any other film, the 20-year-old female character would have been Pierce Brosnan's love interest, but in Mamma Mia! there's no hint of sexual tension between them. And when you know that's not going to happen, you relax.
it’s something so subconcious that i didn’t know it bothered me before, but having the cast presented in a way that was so young and wild and free. and meryl streep worked wonderously as someone embracing her youth embodied in a body her age. it felt so fresh. to see these three middle aged women just owning their bodies and freedom and being dancing queens prancing around chaing guys and being promiscuous with no judgement, but purely from their frivolity and not for the male gaze.
meryl streep was a 50 year old who wasn’t trying to be a 20 year old but emracing such unadulterated joy and youth in her age that it felt so refreshening.
it was wonderful.
I know this can be tricky and more verbose than uploading your Jekyll site directly to your repository. However GitHub Pages support static HTML pages, a workaround solution for using Almace Scaffolding on GitHub Pages is treating your Jekyll site as static pages:
- Build your site locally (
grunt build
). - Upload Jekyll generated static files to your
username.github.io
repository.
If you’d like to keep all things under Git control, you can try the following file structure:
├── _amsf/ (Almace Scaffolding source code)
├── *.html (Jekyll-generated static pages)
└── README.md (your own readme)
the little debbie murders has an interesting ring to it


SIR-B is a SAR that flew on the Space Shuttle in 1984. It acquired data at many sites around the world.


@(username: Option[String])(implicit request: RequestHeader, lang: Lang, env: securesocial.core.RuntimeEnvironment[_]) @scripts = { } @main("User Profile", scripts, username) {
Followers
Following
Likes


India resumes Malaysian palm oil imports as Kuala Lumpur offers discount
Malaysian palm oil is available at a $5 discount amid congestion at Indonesian ports
by ReutersIndian refiners have resumed buying Malaysian palm oil after a gap of nearly a month and contracted around 70,000 tonnes of shipments in December as Kuala Lumpur has been offering a $5 per tonne discount over supplies from rival Indonesia, five traders told Reuters on Thursday.
The resumption in purchases by India, the biggest buyer of Malaysian palm oil this year, could support Malaysian palm oil prices, which are trading near their highest level in two years.
Indian refiners stopped purchases from Malaysia last month fearing New Delhi could raise import taxes or enforce other measures to curb imports after Kuala Lumpur criticised New Delhi for its actions in Kashmir.
Malaysian palm oil is available at a $5 discount amid congestion at Indonesian ports, said a Mumbai-based dealer with a global trading firm. "This is giving a few buyers a reason to start buying Malaysian oil in small quantities to run their refineries."


imgur Chrome Extension v1 written by William Parry (@williamparry)
Uses imgur.com API (imgur.com)
Required Chrome Permissions Explained
© 2013 William Parry | Terms of Use


TF - IDF is short for term frequency - inverse document frequency. The wiki page can be found here: tf - idf.
Term frequency means the raw frequency of a term t in occurs in a document d, which can be represented as tf(f, d) = f(t, d).
Inverse document frequency measures whether the term is common or rare across all documents. It is the logarithmically scaled fraction of the documents that contain the word, obtained by dividing the total number of documents by the number of documents containing the term, and then taking the logarithm of that quotient, which can be represented as idf(t, D) = log(N / {d in D: t in d}).
Finally tfidf(t, d, D) = tf(t, d) x idf(t, D).
Apparently, if a term t has a very high tf in one document, it means that this term appears lots of times in that document. Then we can believe that this term can help us classify this document.
If the number of documents containing term t is very small, the idf will be larger. Then we can also believe that the term t can help us classify this kind of documents. And idf can help us find some common words like “a”, “the”, “is”. These words can be appeared many times in a document, so the tf value will be very large. But they are also existed in every document, so the idf value will be very small, even 0. Then the tf-idf can help us filter these words.
A basic assumption of tf-idf is that the most meaningful word that help us classify the document should appear most times. However, it is not always correct. A better way is to introduce semantic analysis. A recent way is to use LDA (Latent Dirichlet Allocation). I haven’t use this in my experiment, but I will try to talk a little about that in the next section.
LDA is short for Latent Dirichlet Allocation. Here is a very good explanation about LDA on Quora if you don’t want to read the boring wiki page:
http://www.quora.com/What-is-a-good-explanation-of-Latent-Dirichlet-Allocation
Basically, LDA is an unsupervised learning algorithm. It can provide the topics that each document contains. If given 3 documents and 2 topics, LDA can return something like “document A is 100% topic 1, document B is 100% topic 2, document C is 80% topic 1 and 20% topic 2”.
LDA assumes that documents are mixtures of topics. In this model, LDA assumes that documents are created in the following steps:
After that, LDA will try to backtrack from the document to find a set of topics that is most likely to generate this document.
This is just a simple example about how LDA works. I will explain it after I try it in my experiment and read more documents.
Yisha Wu 08 October 2014


{% extends "base.html" %} {% block pagecss %} {% endblock %} {% block pagehead %} Alsea Loop 200k Permanent {% endblock %} {% block subhead %}Based on the Alsea Loop brevet, March 11, 2017{% endblock %} {% block content %}
Unofficial map and downloadable track:
https://ridewithgps.com/routes/1810086
Cue sheet as PDF or
as Excel sheet
RUSA database
record
Permanent owner / Contact for more information: Michal Young
<EMAIL_ADDRESS>This 204k Randonneurs USA permanent brevet, #1726, is a loop primarily north and west of Eugene with a fair amount of climbing (you cross the coast range twice) and some lovely views. The highlight is South Fork road from near Alsea past Alsea Falls to Alpine, which will be familiar to many local riders from the Alpine Century, but there are plenty of other nice views along the way. The last 25 miles are flat.
Note: Logging trucks use some of these roads (Territorial Road in particular) on weekdays. I have not encountered them on a Saturday, but I cannot rule that out. The route is safest and most pleasant on a Sunday.
There is no fee to ride this permanent for RUSA credit, but you must be a current RUSA member. To register, print out the registration form (pdf or MS Word), fill it out, and scan or take a picture of the signed form. Email the scan or picture to<EMAIL_ADDRESS>If everything is in order, I will reply with a PDF of your brevet card for you to print. Please allow a few days for a response.
Google photo album by Chris Archibald
Google photo album by Jeff Reynolds
The Alsea loop begins in south-west Eugene (the shopping center at 29th and Willamette) and pops over the valley rim on Lorane Highway, on the way west/south-west way to the tiny town of Crow.
Just beyond John-Boy's Market, at the Post Office, you'll turn left on Alsea-Deadwood highway, and just a mile south you'll turn left again onto South Fork Road, toward Alsea Falls. One of the first sights on South Fork is the Alsea Acres goat farm, which makes wonderful chevre (goat cheese), available at the Eugene Farmers' Market on Saturdays in summer. Then you'll start climbing back over the coast range, but it's not as steep as the climb from east to west. Alsea Falls is worth a short stop. When you summit, the road turns steeply downward. This is a screaming descent ... do be careful in the curves. When you level out again, you're almost to Alpine, and soon on you're way back to Monroe (not a control on the return). The climbing is almost over. Monroe is your last chance for restrooms with running water for quite a while, so use them if you can.
From Monroe you retrace your route a few miles back on Territorial, but this time you'll turn left on Ferguson. Answer the question on your brevet card when you reach Washburn, then take Washburn right (south) to High Pass.
Now it's flat and pretty straight and, frankly, pretty boring compared to what you've been through ... sorry, can't be helped. Washburn takes you to High Pass road, where you turn left (east) toward Junction City. High Pass is a fairly busy road, but you'll only be on it for a mile. Before Junction City you'll turn right on Dorsey Lane, which looks too small to possibly be on the way to anywhere, but it really is on the way to Alvadore. And maybe Alvadore isn't anywhere, but there are a couple convenience stores catering to visitors to Fern Ridge Reservoir, and you should stop at one of them to get a receipt.
More flat ... I've tried to avoid routing you much along the busy Clear Lake road, but you'll have to endure half a mile of that shoulder before you turn right again onto Fir Butte, which takes you to Royal, which takes you to the beginning of the Fern Ridge Bicycle Path, at the intersection of Royal with Greenhill Road (just several yards south on Greenhill). Now this is more like it ... a nice separated multi-use path all the way back into Eugene.  Watch for pedestrians and runners, and keep an eye out for heron and cranes along the canal.
You come off the Fern Ridge path just past Chambers street, across the canal on a little bridge, and then across a larger bridge that crosses 18th Ave and through the disc golf course, ending in a school parking lot. Work your way left through the parking lot to a path that takes you out to Polk Street, then follow cues to work your way back to the starting point at 29th and Willamette. In addition to the food establishments in the shopping center, there are food and restrooms in Market of Choice, the large grocery store.
{% endblock %}


In this notebook, some template code has already been provided for you, and you will need to implement additional functionality to successfully complete this project. You will not need to modify the included code beyond what is requested. Sections that begin with '(IMPLEMENTATION)' in the header indicate that the following block of code will require additional functionality which you must provide. Instructions will be provided for each section, and the specifics of the implementation are marked in the code block with a 'TODO' statement. Please be sure to read the instructions carefully!
Note: Once you have completed all of the code implementations, you need to finalize your work by exporting the iPython Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.
In addition to implementing code, there will be questions that you must answer which relate to the project and your implementation. Each section where you will answer a question is preceded by a 'Question X' header. Carefully read each question and provide thorough answers in the following text boxes that begin with 'Answer:'. Your project submission will be evaluated based on your answers to each of the questions and the implementation you provide.
Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. Markdown cells can be edited by double-clicking the cell to enter edit mode.
The rubric contains optional "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. If you decide to pursue the "Stand Out Suggestions", you should include the code in this IPython notebook.
In this notebook, you will make the first steps towards developing an algorithm that could be used as part of a mobile or web app. At the end of this project, your code will accept any user-supplied image as input. If a dog is detected in the image, it will provide an estimate of the dog's breed. If a human is detected, it will provide an estimate of the dog breed that is most resembling. The image below displays potential sample output of your finished project (... but we expect that each student's algorithm will behave differently!).
In this real-world setting, you will need to piece together a series of models to perform different tasks; for instance, the algorithm that detects humans in an image will be different from the CNN that infers dog breed. There are many points of possible failure, and no perfect algorithm exists. Your imperfect solution will nonetheless create a fun user experience!
We break the notebook into separate steps. Feel free to use the links below to navigate the notebook.
In the code cell below, we import a dataset of dog images. We populate a few variables through the use of the load_files
function from the scikit-learn library:
train_files
, valid_files
, test_files
- numpy arrays containing file paths to imagestrain_targets
, valid_targets
, test_targets
- numpy arrays containing onehot-encoded classification labels dog_names
- list of string-valued dog breed names for translating labelsfrom sklearn.datasets import load_files
from keras.utils import np_utils
import numpy as np
from glob import glob
# define function to load train, test, and validation datasets
def load_dataset(path):
data = load_files(path)
dog_files = np.array(data['filenames'])
dog_targets = np_utils.to_categorical(np.array(data['target']), 133)
return dog_files, dog_targets
# load train, test, and validation datasets
train_files, train_targets = load_dataset('dogImages/train')
valid_files, valid_targets = load_dataset('dogImages/valid')
test_files, test_targets = load_dataset('dogImages/test')
# load list of dog names
dog_names = [item[20:-1] for item in sorted(glob("dogImages/train/*/"))]
# print statistics about the dataset
print('There are %d total dog categories.' % len(dog_names))
print('There are %s total dog images.\n' % len(np.hstack([train_files, valid_files, test_files])))
print('There are %d training dog images.' % len(train_files))
print('There are %d validation dog images.' % len(valid_files))
print('There are %d test dog images.'% len(test_files))
In the code cell below, we import a dataset of human images, where the file paths are stored in the numpy array human_files
.
import random
random.seed(8675309)
# load filenames in shuffled human dataset
human_files = np.array(glob("lfw/*/*"))
random.shuffle(human_files)
# print statistics about the dataset
print('There are %d total human images.' % len(human_files))
We use OpenCV's implementation of Haar feature-based cascade classifiers to detect human faces in images. OpenCV provides many pre-trained face detectors, stored as XML files on github. We have downloaded one of these detectors and stored it in the haarcascades
directory.
In the next code cell, we demonstrate how to use this detector to find human faces in a sample image.
import cv2
import matplotlib.pyplot as plt
%matplotlib inline
# extract pre-trained face detector
face_cascade = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_alt.xml')
# load color (BGR) image
img = cv2.imread(human_files[3])
# convert BGR image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# find faces in image
faces = face_cascade.detectMultiScale(gray)
# print number of faces detected in the image
print('Number of faces detected:', len(faces))
# get bounding box for each detected face
for (x,y,w,h) in faces:
# add bounding box to color image
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
# convert BGR image to RGB for plotting
cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# display the image, along with bounding box
plt.imshow(cv_rgb)
plt.show()
Before using any of the face detectors, it is standard procedure to convert the images to grayscale. The detectMultiScale
function executes the classifier stored in face_cascade
and takes the grayscale image as a parameter.
In the above code, faces
is a numpy array of detected faces, where each row corresponds to a detected face. Each detected face is a 1D array with four entries that specifies the bounding box of the detected face. The first two entries in the array (extracted in the above code as x
and y
) specify the horizontal and vertical positions of the top left corner of the bounding box. The last two entries in the array (extracted here as w
and h
) specify the width and height of the box.
We can use this procedure to write a function that returns True
if a human face is detected in an image and False
otherwise. This function, aptly named face_detector
, takes a string-valued file path to an image as input and appears in the code block below.
# returns "True" if face is detected in image stored at img_path
def face_detector(img_path):
img = cv2.imread(img_path)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray)
return len(faces) > 0
Question 1: Use the code cell below to test the performance of the face_detector
function.
human_files
have a detected human face? dog_files
have a detected human face?  You will see that our algorithm falls short of this goal, but still gives acceptable performance. We extract the file paths for the first 100 images from each of the datasets and store them in the numpy arrays human_files_short
and dog_files_short
.
Answer:
Human subset: 98.0%
Dog subset: 11.0%
human_files_short = human_files[:100]
dog_files_short = train_files[:100]
# Do NOT modify the code above this line.
## TODO: Test the performance of the face_detector algorithm
## on the images in human_files_short and dog_files_short.
def face_detector_performance(faces_array,detector=face_detector):
"""
Consumes an array of file locations
Uses the face_detector method to see if the image has faces
Returns a float representing the number of images present in the dataset that had faces
according to the face_detector method
"""
results = []
for face in faces_array:
results.append(detector(face))
size = len(faces_array)
trues = sum(results)
return trues / size
print("Calculating percentage of images containing faces using the face_detector method...")
print("Human subset: {}%".format(face_detector_performance(human_files_short) * 100))
print("Dog subset: {}%".format(face_detector_performance(dog_files_short) * 100))
Question 2: This algorithmic choice necessitates that we communicate to the user that we accept human images only when they provide a clear view of a face (otherwise, we risk having unneccessarily frustrated users!). In your opinion, is this a reasonable expectation to pose on the user? If not, can you think of a way to detect humans in images that does not necessitate an image with a clearly presented face?
Answer:
As the description of this project reads, its used to detect dog breeds or when a human is present, suggest a dog breed the human most looks like. That being said, I think it is a reasonable thing to ask of a consumer, unless they are interested in what dog breed their chin looks like...
We suggest the face detector from OpenCV as a potential way to detect human images in your algorithm, but you are free to explore other approaches, especially approaches that make use of deep learning :). Please use the code cell below to design and test your own face detection algorithm. If you decide to pursue this optional task, report performance on each of the datasets.
## (Optional) TODO: Report the performance of another
## face detection algorithm on the LFW dataset
### Feel free to use as many code cells as needed.
In this section, we use a pre-trained ResNet-50 model to detect dogs in images. Our first line of code downloads the ResNet-50 model, along with weights that have been trained on ImageNet, a very large, very popular dataset used for image classification and other vision tasks. ImageNet contains over 10 million URLs, each linking to an image containing an object from one of 1000 categories. Given an image, this pre-trained ResNet-50 model returns a prediction (derived from the available categories in ImageNet) for the object that is contained in the image.
from keras.applications.resnet50 import ResNet50
# define ResNet50 model
ResNet50_model = ResNet50(weights='imagenet')
When using TensorFlow as backend, Keras CNNs require a 4D array (which we'll also refer to as a 4D tensor) as input, with shape
$$ (\text{nb_samples}, \text{rows}, \text{columns}, \text{channels}), $$
where nb_samples
corresponds to the total number of images (or samples), and rows
, columns
, and channels
correspond to the number of rows, columns, and channels for each image, respectively.
The path_to_tensor
function below takes a string-valued file path to a color image as input and returns a 4D tensor suitable for supplying to a Keras CNN. The function first loads the image and resizes it to a square image that is $224 \times 224$ pixels. Next, the image is converted to an array, which is then resized to a 4D tensor. In this case, since we are working with color images, each image has three channels. Likewise, since we are processing a single image (or sample), the returned tensor will always have shape
$$ (1, 224, 224, 3). $$
The paths_to_tensor
function takes a numpy array of string-valued image paths as input and returns a 4D tensor with shape
$$ (\text{nb_samples}, 224, 224, 3). $$
Here, nb_samples
is the number of samples, or number of images, in the supplied array of image paths. It is best to think of nb_samples
as the number of 3D tensors (where each 3D tensor corresponds to a different image) in your dataset!
from keras.preprocessing import image
from tqdm import tqdm
def path_to_tensor(img_path):
# loads RGB image as PIL.Image.Image type
img = image.load_img(img_path, target_size=(224, 224))
# convert PIL.Image.Image type to 3D tensor with shape (224, 224, 3)
x = image.img_to_array(img)
# convert 3D tensor to 4D tensor with shape (1, 224, 224, 3) and return 4D tensor
return np.expand_dims(x, axis=0)
def paths_to_tensor(img_paths):
list_of_tensors = [path_to_tensor(img_path) for img_path in tqdm(img_paths)]
return np.vstack(list_of_tensors)
Getting the 4D tensor ready for ResNet-50, and for any other pre-trained model in Keras, requires some additional processing. First, the RGB image is converted to BGR by reordering the channels. All pre-trained models have the additional normalization step that the mean pixel (expressed in RGB as $[103.939, 116.779, 123.68]$ and calculated from all pixels in all images in ImageNet) must be subtracted from every pixel in each image. This is implemented in the imported function preprocess_input
. If you're curious, you can check the code for preprocess_input
here.
Now that we have a way to format our image for supplying to ResNet-50, we are now ready to use the model to extract the predictions. This is accomplished with the predict
method, which returns an array whose $i$-th entry is the model's predicted probability that the image belongs to the $i$-th ImageNet category. This is implemented in the ResNet50_predict_labels
function below.
By taking the argmax of the predicted probability vector, we obtain an integer corresponding to the model's predicted object class, which we can identify with an object category through the use of this dictionary.
from keras.applications.resnet50 import preprocess_input, decode_predictions
def ResNet50_predict_labels(img_path):
# returns prediction vector for image located at img_path
img = preprocess_input(path_to_tensor(img_path))
return np.argmax(ResNet50_model.predict(img))
While looking at the dictionary, you will notice that the categories corresponding to dogs appear in an uninterrupted sequence and correspond to dictionary keys 151-268, inclusive, to include all categories from 'Chihuahua'
to 'Mexican hairless'
. Thus, in order to check to see if an image is predicted to contain a dog by the pre-trained ResNet-50 model, we need only check if the ResNet50_predict_labels
function above returns a value between 151 and 268 (inclusive).
We use these ideas to complete the dog_detector
function below, which returns True
if a dog is detected in an image (and False
if not).
### returns "True" if a dog is detected in the image stored at img_path
def dog_detector(img_path):
prediction = ResNet50_predict_labels(img_path)
return ((prediction <= 268) & (prediction >= 151))
Question 3: Use the code cell below to test the performance of your dog_detector
function.
human_files_short
have a detected dog? dog_files_short
have a detected dog?Answer:
Human subset: 2.0%
Dog subset: 100.0%
### TODO: Test the performance of the dog_detector function
### on the images in human_files_short and dog_files_short.
print("Calculating percentage of images containing faces using the dog_detector method...")
print("Human subset: {}%".format(face_detector_performance(human_files_short,detector=dog_detector) * 100))
print("Dog subset: {}%".format(face_detector_performance(dog_files_short,detector=dog_detector) * 100))
Now that we have functions for detecting humans and dogs in images, we need a way to predict breed from images. In this step, you will create a CNN that classifies dog breeds. You must create your CNN from scratch (so, you can't use transfer learning yet!), and you must attain a test accuracy of at least 1%. In Step 5 of this notebook, you will have the opportunity to use transfer learning to create a CNN that attains greatly improved accuracy.
Be careful with adding too many trainable layers! More parameters means longer training, which means you are more likely to need a GPU to accelerate the training process. Thankfully, Keras provides a handy estimate of the time that each epoch is likely to take; you can extrapolate this estimate to figure out how long it will take for your algorithm to train.
We mention that the task of assigning breed to dogs from images is considered exceptionally challenging. To see why, consider that even a human would have great difficulty in distinguishing between a Brittany and a Welsh Springer Spaniel.
| Brittany | Welsh Springer Spaniel |
|---|---|
It is not difficult to find other dog breed pairs with minimal inter-class variation (for instance, Curly-Coated Retrievers and American Water Spaniels).
| Curly-Coated Retriever | American Water Spaniel |
|---|---|
Likewise, recall that labradors come in yellow, chocolate, and black. Your vision-based algorithm will have to conquer this high intra-class variation to determine how to classify all of these different shades as the same breed.
| Yellow Labrador | Chocolate Labrador | Black Labrador |
|---|---|---|
We also mention that random chance presents an exceptionally low bar: setting aside the fact that the classes are slightly imabalanced, a random guess will provide a correct answer roughly 1 in 133 times, which corresponds to an accuracy of less than 1%.
Remember that the practice is far ahead of the theory in deep learning. Experiment with many different architectures, and trust your intuition. And, of course, have fun!
We rescale the images by dividing every pixel in every image by 255.
from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
# pre-process the data for Keras
train_tensors = paths_to_tensor(train_files).astype('float32')/255
valid_tensors = paths_to_tensor(valid_files).astype('float32')/255
test_tensors = paths_to_tensor(test_files).astype('float32')/255
Create a CNN to classify dog breed. At the end of your code cell block, summarize the layers of your model by executing the line:
model.summary()
We have imported some Python modules to get you started, but feel free to import as many modules as you need. If you end up getting stuck, here's a hint that specifies a model that trains relatively fast on CPU and attains >1% test accuracy in 5 epochs:
Question 4: Outline the steps you took to get to your final CNN architecture and your reasoning at each step. If you chose to use the hinted architecture above, describe why you think that CNN architecture should work well for the image classification task.
Answer:
from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D, AveragePooling2D
from keras.layers import Dropout, Flatten, Dense
from keras.models import Sequential
model = Sequential()
#Conv2D
#'input_shape' to define input shape... (first Conv layer only)
#'kernel_size' to set the size of the convolutional window
#'filters' to spocify the amount of filters in the layer
#'padding' set to same as to not lose nodes
#'activation' layer set to ReLU to counter the vanishing gradient problem
#Pooling
#Pooling for dimensionality reduction
#Max pooling taking the largest of each feature map for a sliding window of (n,m) --> Default (2,2) window
#Global pooling for taking single value for each feature map (no sliding window, dramatically reduces dimensionality)
#Dense
#Softmax for multi-class classification --> Different dog breeds (133)
### TODO: Define your architecture.
# Architecture from above
# model.add(Conv2D(filters=16, kernel_size=2, padding='same', activation='relu', input_shape=(224,224, 3)))
# model.add(MaxPooling2D())
# model.add(Conv2D(filters=32, kernel_size=2, padding='same', activation='relu'))
# model.add(MaxPooling2D())
# model.add(Conv2D(filters=64, kernel_size=2, padding='same', activation='relu'))
# model.add(MaxPooling2D())
# model.add(GlobalAveragePooling2D())
# model.add(Dense(133, activation='softmax'))
# Attempt at own architecture.
# epoch == 10
# Added dropout to avoid overfitting
# Adding dropout layers increased accuracy to 4.7% (+1%)
# Set kernel size to 3 based on VGG architecture (according to learning material)
# Setting kernel size to 3 increased accuracy to 4.9% (+0.2%)
# Set kernel size to 11 based on AlexNet architecture (according to learning material)
# Setting kernel size to 11 increased/decreased accuracy to 4.66% (-0.3%)
# Set kernel size to back to 3
# Changed pooling from MaxPooling2D to AveragePooling2D
# Changing MaxPooling2D to AveragePooling2D decreased accuracy to 4.18% (- 0.48%)
# Changed pooling back to MaxPooling2D
#
# increasing epochs from 10 to 50 based on current configuration
#
# epoch == 50
# Test accuracy: 25.5981%
model.add(Conv2D(filters=16, kernel_size=11, padding='same', activation='relu', input_shape=(224,224, 3)))
model.add(Dropout(0.2))
model.add(MaxPooling2D())
model.add(Dropout(0.2))
model.add(Conv2D(filters=32, kernel_size=11, padding='same', activation='relu'))
model.add(Dropout(0.2))
model.add(MaxPooling2D())
model.add(Dropout(0.2))
model.add(Conv2D(filters=64, kernel_size=11, padding='same', activation='relu'))
model.add(Dropout(0.2))
model.add(MaxPooling2D())
model.add(Dropout(0.2))
model.add(GlobalAveragePooling2D())
model.add(Dense(133, activation='softmax'))
# define optimizers --> RMS propr does not have default dropout, add as Visible Layer
# rmsprop = keras.optimizers.RMSprop(lr=0.001, rho=0.9, epsilon=None, decay=0.0)
model.summary()
# Default compile
model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])
Train your model in the code cell below. Use model checkpointing to save the model that attains the best validation loss.
You are welcome to augment the training data, but this is not a requirement.
from keras.callbacks import ModelCheckpoint
### TODO: specify the number of epochs that you would like to use to train the model.
epochs = 50
### Do NOT modify the code below this line.
checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.from_scratch.hdf5',
verbose=1, save_best_only=True)
model.fit(train_tensors, train_targets,
validation_data=(valid_tensors, valid_targets),
epochs=epochs, batch_size=20, callbacks=[checkpointer], verbose=1)
model.load_weights('saved_models/weights.best.from_scratch.hdf5')
Try out your model on the test dataset of dog images. Ensure that your test accuracy is greater than 1%.
# get index of predicted dog breed for each image in test set
dog_breed_predictions = [np.argmax(model.predict(np.expand_dims(tensor, axis=0))) for tensor in test_tensors]
# report test accuracy
test_accuracy = 100*np.sum(np.array(dog_breed_predictions)==np.argmax(test_targets, axis=1))/len(dog_breed_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
bottleneck_features = np.load('bottleneck_features/DogVGG16Data.npz')
train_VGG16 = bottleneck_features['train']
valid_VGG16 = bottleneck_features['valid']
test_VGG16 = bottleneck_features['test']
The model uses the the pre-trained VGG-16 model as a fixed feature extractor, where the last convolutional output of VGG-16 is fed as input to our model. We only add a global average pooling layer and a fully connected layer, where the latter contains one node for each dog category and is equipped with a softmax.
VGG16_model = Sequential()
VGG16_model.add(GlobalAveragePooling2D(input_shape=train_VGG16.shape[1:]))
VGG16_model.add(Dense(133, activation='softmax'))
VGG16_model.summary()
VGG16_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])
from keras.callbacks import ModelCheckpoint
checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.VGG16.hdf5',
verbose=1, save_best_only=True)
VGG16_model.fit(train_VGG16, train_targets,
validation_data=(valid_VGG16, valid_targets),
epochs=20, batch_size=20, callbacks=[checkpointer], verbose=1)
VGG16_model.load_weights('saved_models/weights.best.VGG16.hdf5')
Now, we can use the CNN to test how well it identifies breed within our test dataset of dog images. We print the test accuracy below.
# get index of predicted dog breed for each image in test set
VGG16_predictions = [np.argmax(VGG16_model.predict(np.expand_dims(feature, axis=0))) for feature in test_VGG16]
# report test accuracy
test_accuracy = 100*np.sum(np.array(VGG16_predictions)==np.argmax(test_targets, axis=1))/len(VGG16_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
from extract_bottleneck_features import *
def VGG16_predict_breed(img_path):
# extract bottleneck features
bottleneck_feature = extract_VGG16(path_to_tensor(img_path))
# obtain predicted vector
predicted_vector = VGG16_model.predict(bottleneck_feature)
# return dog breed that is predicted by the model
return dog_names[np.argmax(predicted_vector)]
You will now use transfer learning to create a CNN that can identify dog breed from images. Your CNN must attain at least 60% accuracy on the test set.
In Step 4, we used transfer learning to create a CNN using VGG-16 bottleneck features. In this section, you must use the bottleneck features from a different pre-trained model. To make things easier for you, we have pre-computed the features for all of the networks that are currently available in Keras:
The files are encoded as such:
Dog{network}Data.npz
where {network}
, in the above filename, can be one of VGG19
, Resnet50
, InceptionV3
, or Xception
. Pick one of the above architectures, download the corresponding bottleneck features, and store the downloaded file in the bottleneck_features/
folder in the repository.
In the code block below, extract the bottleneck features corresponding to the train, test, and validation sets by running the following:
bottleneck_features = np.load('bottleneck_features/Dog{network}Data.npz')
train_{network} = bottleneck_features['train']
valid_{network} = bottleneck_features['valid']
test_{network} = bottleneck_features['test']
### TODO: Obtain bottleneck features from another pre-trained CNN.
bottleneck_features = np.load('bottleneck_features/DogResnet50Data.npz')
train_Resnet50 = bottleneck_features['train']
valid_Resnet50 = bottleneck_features['valid']
test_Resnet50 = bottleneck_features['test']
Create a CNN to classify dog breed. At the end of your code cell block, summarize the layers of your model by executing the line:
<your model's name>.summary()
Question 5: Outline the steps you took to get to your final CNN architecture and your reasoning at each step. Describe why you think the architecture is suitable for the current problem.
Answer:
As we're dealing with a dataset which is similar to the original one, and it is rather small (in my opinion), this would reference to a transfer learning case where we:
(from CNN's lesson 4 part 25)
### TODO: Define your architecture.
Resnet50_model = Sequential()
Resnet50_model.add(GlobalAveragePooling2D(input_shape=train_Resnet50.shape[1:]))
Resnet50_model.add(Dense(133, activation='softmax'))
Resnet50_model.summary()
### TODO: Compile the model.
Resnet50_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])
Train your model in the code cell below. Use model checkpointing to save the model that attains the best validation loss.
You are welcome to augment the training data, but this is not a requirement.
### TODO: Train the model.
from keras.callbacks import ModelCheckpoint
epochs = 10
checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.Resnet50.hdf5',
verbose=1, save_best_only=True)
Resnet50_model.fit(train_Resnet50, train_targets,
validation_data=(valid_Resnet50, valid_targets),
epochs=epochs, batch_size=20, callbacks=[checkpointer], verbose=1)
### TODO: Load the model weights with the best validation loss.
Resnet50_model.load_weights('saved_models/weights.best.Resnet50.hdf5')
Try out your model on the test dataset of dog images. Ensure that your test accuracy is greater than 60%.
### TODO: Calculate classification accuracy on the test dataset.
# get index of predicted dog breed for each image in test set
Resnet50_predictions = [np.argmax(Resnet50_model.predict(np.expand_dims(feature, axis=0))) for feature in test_Resnet50]
# report test accuracy
test_accuracy = 100*np.sum(np.array(Resnet50_predictions)==np.argmax(test_targets, axis=1))/len(Resnet50_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Write a function that takes an image path as input and returns the dog breed (Affenpinscher
, Afghan_hound
, etc) that is predicted by your model.
Similar to the analogous function in Step 5, your function should have three steps:
dog_names
array defined in Step 0 of this notebook to return the corresponding breed.The functions to extract the bottleneck features can be found in extract_bottleneck_features.py
, and they have been imported in an earlier code cell. To obtain the bottleneck features corresponding to your chosen CNN architecture, you need to use the function
extract_{network}
where {network}
, in the above filename, should be one of VGG19
, Resnet50
, InceptionV3
, or Xception
.
### TODO: Write a function that takes a path to an image as input
### and returns the dog breed that is predicted by the model.
from extract_bottleneck_features import *
def predict_breed(img_path, model_type):
if model_type == "Resnet50":
return Resnet50_predict_breed(img_path)
return "Error: Unknown model type"
def Resnet50_predict_breed(img_path):
# extract bottleneck features
bottleneck_feature = extract_Resnet50(path_to_tensor(img_path))
# obtain predicted vector
predicted_vector = Resnet50_model.predict(bottleneck_feature)
# return dog breed that is predicted by the model
return dog_names[np.argmax(predicted_vector)]
Write an algorithm that accepts a file path to an image and first determines whether the image contains a human, dog, or neither. Then,
You are welcome to write your own functions for detecting humans and dogs in images, but feel free to use the face_detector
and dog_detector
functions developed above. You are required to use your CNN from Step 5 to predict dog breed.
Some sample output for our algorithm is provided below, but feel free to design your own user experience!
### TODO: Write your algorithm.
### Feel free to use as many code cells as needed.
model_type = "Resnet50"
def get_species(img_path):
"""
Checks if image is either a dog, human or something else!
Uses following coding scheme:
dog = 0
human = 1
other = -1
"""
# check for dog
tp = dog_detector(img_path)
# dog
if tp >= 1:
# print('a dog was found!')
return 'dog'
# return predict_breed(img_path, model_type)
# not a dog
# check for human
tp = face_detector(img_path)
if tp >= 1:
# print('a human was found!')
return 'human'
# return predict_breed(img_path, model_type)
# not a human
return 'unknown'
In this section, you will take your new algorithm for a spin! What kind of dog does the algorithm think that you look like? If you have a dog, does it predict your dog's breed accurately? If you have a cat, does it mistakenly think that your cat is a dog?
Test your algorithm at least six images on your computer. Feel free to use any images you like. Use at least two human and two dog images.
Question 6: Is the output better than you expected :) ? Or worse :( ? Provide at least three possible points of improvement for your algorithm.
Answer: : The output is pretty good! Better then I expected for sure. It makes up for some fun laughs with friends. Due to privacy concerns, I ended up using only images from wikipedia.
Some improvements:
## TODO: Execute your algorithm from Step 6 on
## at least 6 images on your computer.
## Feel free to use as many code cells as needed.
# Collect all image paths in a directory for evaluation
import os
def collect_images(directory):
"""
directory: string representing directory to collect images from based on the current working directory
returns: array of paths for the given directory
Does not check if files in directory are actually images
"""
imgs = []
filelist = os.listdir(directory)
for file in filelist:
imgs.append(directory + "/" + file)
return imgs
# The code snippit below is copied from github
# Full credit to
# User: soply
# url: https://gist.github.com/soply/f3eec2e79c165e39c9d540e916142ae1
def show_images(images, cols = 1, titles = None):
"""Display a list of images in a single figure with matplotlib.
Parameters
---------
images: List of np.arrays compatible with plt.imshow.
cols (Default = 1): Number of columns in figure (number of rows is
set to np.ceil(n_images/float(cols))).
titles: List of titles corresponding to each image. Must have
the same length as titles.
"""
assert((titles is None)or (len(images) == len(titles)))
n_images = len(images)
if titles is None: titles = ['Image (%d)' % i for i in range(1,n_images + 1)]
fig = plt.figure()
for n, (image, title) in enumerate(zip(images, titles)):
a = fig.add_subplot(cols, np.ceil(n_images/float(cols)), n + 1)
if image.ndim == 2:
plt.gray()
plt.imshow(image)
a.set_title(title)
fig.set_size_inches(np.array(fig.get_size_inches()) * n_images)
plt.show()
from skimage import io
def project_images(image_paths, cols = 1, titles = None):
"""
Wrapper method to take an array of string paths and convert them into a numpy array of images
Internally uses show_images method
"""
images_arr = []
for image_path in image_paths:
i = io.imread(image_path)
images_arr.append(i)
show_images(images_arr, cols, titles)
# Get dog breeds for all images in directory
image_paths = collect_images('images/samples')
species = [get_species(i) for i in image_paths]
titles = [predict_breed(i,model_type) for i in image_paths]
# Improve titles by combining predicted species with predicted breed to annotate top of over image
final_titles = []
for ix,val in enumerate(species):
final_titles.append(species[ix] + ' - ' + titles[ix])
print(final_titles)
# Visualize predictions
project_images(image_paths, cols=3,titles=final_titles)
#print breed detected by algorithm, by image path
for idx, im_p in enumerate(image_paths):
print(im_p + ' - ' + species[idx] + ' - ' + titles[idx])