markdown
stringlengths 0
37k
| code
stringlengths 1
33.3k
| path
stringlengths 8
215
| repo_name
stringlengths 6
77
| license
stringclasses 15
values |
---|---|---|---|---|
However, in order to implement this, we need a list of bonds. We will do this by taking a system minimized under our original harmonic_morse potential:
|
R_temp, max_force_component = run_minimization(harmonic_morse_pair(displacement,D0=5.0,alpha=10.0,r0=1.0,k=500.0), R, shift)
print('largest component of force after minimization = {}'.format(max_force_component))
plot_system( R_temp, box_size )
|
notebooks/customizing_potentials_cookbook.ipynb
|
google/jax-md
|
apache-2.0
|
We now place a bond between all particle pairs that are separated by less than 1.3. calculate_bond_data returns a list of such bonds, as well as a list of the corresponding current length of each bond.
|
bonds, lengths = calculate_bond_data(displacement, R_temp, 1.3)
print(bonds[:5]) # list of particle index pairs that form bonds
print(lengths[:5]) # list of the current length of each bond
|
notebooks/customizing_potentials_cookbook.ipynb
|
google/jax-md
|
apache-2.0
|
We use this length as the r0 parameter, meaning that initially each bond is at the unstable local maximum $r=r_0$.
|
bond_energy_fn = bistable_spring_bond(displacement, bonds, r0=lengths)
|
notebooks/customizing_potentials_cookbook.ipynb
|
google/jax-md
|
apache-2.0
|
We now use our new bond_energy_fn to minimize the energy of the system. The expectation is that nearby particles should either move closer together or further apart, and the choice of which to do should be made collectively due to the constraint of constant volume. This is exactly what we see.
|
Rfinal, max_force_component = run_minimization(bond_energy_fn, R_temp, shift)
print('largest component of force after minimization = {}'.format(max_force_component))
plot_system( Rfinal, box_size )
|
notebooks/customizing_potentials_cookbook.ipynb
|
google/jax-md
|
apache-2.0
|
Specifying bonds dynamically
As with species or parameters, bonds can be specified dynamically, i.e. when the energy function is called. Importantly, note that this does NOT override bonds that were specified statically in smap.bond.
|
# Specifying the bonds dynamically ADDS additional bonds.
# Here, we dynamically pass the same bonds that were passed statically, which
# has the effect of doubling the energy
print(bond_energy_fn(R))
print(bond_energy_fn(R,bonds=bonds, r0=lengths))
|
notebooks/customizing_potentials_cookbook.ipynb
|
google/jax-md
|
apache-2.0
|
We won't go thorugh a further example as the implementation is exactly the same as specifying species or parameters dynamically, but the ability to employ bonds both statically and dynamically is a very powerful and general framework.
Combining potentials
Most JAX MD functionality (e.g. simulations, energy minimizations) relies on a function that calculates energy for a set of positions. Importantly, while this cookbook focus on simple and robust ways of defining such functions, JAX MD is not limited to these methods; users can implement energy functions however they like.
As an important example, here we consider the case where the energy includes both a pair potential and a bond potential. Specifically, we combine harmonic_morse_pair with bistable_spring_bond.
|
# Note, the code in the "Bonds" section must be run prior to this.
energy_fn = harmonic_morse_pair(displacement,D0=0.,alpha=10.0,r0=1.0,k=1.0)
bond_energy_fn = bistable_spring_bond(displacement, bonds, r0=lengths)
def combined_energy_fn(R):
return energy_fn(R) + bond_energy_fn(R)
|
notebooks/customizing_potentials_cookbook.ipynb
|
google/jax-md
|
apache-2.0
|
Here, we have set $D_0=0$, so the pair potential is just a one-sided repulsive harmonic potential. For particles connected with a bond, this raises the energy of the "contracted" minimum relative to the "extended" minimum.
|
drs = np.arange(0,2,0.01)
U = harmonic_morse(drs,D0=0.,alpha=10.0,r0=1.0,k=1.0)+bistable_spring(drs)
plt.plot(drs,U)
format_plot(r'$r$', r'$V(r)$')
finalize_plot()
|
notebooks/customizing_potentials_cookbook.ipynb
|
google/jax-md
|
apache-2.0
|
This new energy function can be passed to the minimization routine (or any other JAX MD simulation routine) in the usual way.
|
Rfinal, max_force_component = run_minimization(combined_energy_fn, R_temp, shift)
print('largest component of force after minimization = {}'.format(max_force_component))
plot_system( Rfinal, box_size )
|
notebooks/customizing_potentials_cookbook.ipynb
|
google/jax-md
|
apache-2.0
|
Specifying forces instead of energies
So far, we have defined functions that calculate the energy of the system, which we then pass to JAX MD. Internally, JAX MD uses automatic differentiation to convert these into functions that calculate forces, which are necessary to evolve a system under a given dynamics. However, JAX MD has the option to pass force functions directly, rather than energy functions. This creates additional flexibility because some forces cannot be represented as the gradient of a potential.
As a simple example, we create a custom force function that zeros out the force of some particles. During energy minimization, where there is no stochastic noise, this has the effect of fixing the position of these particles.
First, we break the system up into two species, as before.
|
N_0 = N // 2 # Half the particles in species 0
N_1 = N - N_0 # The rest in species 1
species = np.array([0]*N_0 + [1]*N_1, dtype=np.int32)
print(species)
|
notebooks/customizing_potentials_cookbook.ipynb
|
google/jax-md
|
apache-2.0
|
Next, we we creat our custom force function. Starting with our harmonic_morse pair potential, we calculate the force manually (i.e. using built-in automatic differentiation), and then multiply the force by the species id, which has the desired effect.
|
energy_fn = harmonic_morse_pair(displacement,D0=5.0,alpha=10.0,r0=1.0,k=500.0)
force_fn = quantity.force(energy_fn)
def custom_force_fn(R, **kwargs):
return vmap(lambda a,b: a*b)(force_fn(R),species)
|
notebooks/customizing_potentials_cookbook.ipynb
|
google/jax-md
|
apache-2.0
|
Running simulations with custom forces is as easy as passing this force function to the simulation.
|
def run_minimization_general(energy_or_force, R_init, shift, num_steps=5000):
dt_start = 0.001
dt_max = 0.004
init,apply=minimize.fire_descent(jit(energy_or_force),shift,dt_start=dt_start,dt_max=dt_max)
apply = jit(apply)
@jit
def scan_fn(state, i):
return apply(state), 0.
state = init(R_init)
state, _ = lax.scan(scan_fn,state,np.arange(num_steps))
return state.position, np.amax(np.abs(quantity.canonicalize_force(energy_or_force)(state.position)))
|
notebooks/customizing_potentials_cookbook.ipynb
|
google/jax-md
|
apache-2.0
|
We run this as usual,
|
key, split = random.split(key)
Rfinal, _ = run_minimization_general(custom_force_fn, R, shift)
plot_system( Rfinal, box_size, species )
|
notebooks/customizing_potentials_cookbook.ipynb
|
google/jax-md
|
apache-2.0
|
After the above minimization, the blue particles have the same positions as they did initially:
|
plot_system( R, box_size, species )
|
notebooks/customizing_potentials_cookbook.ipynb
|
google/jax-md
|
apache-2.0
|
Note, this method for fixing particles only works when there is no stochastic noise (e.g. in Langevin or Brownian dynamics) because such noise affects partices whether or not they have a net force. A safer way to fix particles is to create a custom shift function.
Coupled ensembles
For a final example that demonstrates the flexibility within JAX MD, lets do something that is particularly difficult in most standard MD packages. We will create a "coupled ensemble" -- i.e. a set of two identical systems that are connected via a $Nd$ dimensional spring. An extension of this idea is used, for example, in the Doubly Nudged Elastic Band method for finding transition states.
If the "normal" energy of each system is
\begin{equation}
U(R) = \sum_{i,j} V( r_{ij} ),
\end{equation}
where $r_{ij}$ is the distance between the $i$th and $j$th particles in $R$ and the $V(r)$ is a standard pair potential, and if the two sets of positions, $R_0$ and $R_1$, are coupled via the potential
\begin{equation}
U_\mathrm{spr}(R_0,R_1) = \frac 12 k_\mathrm{spr} \left| R_1 - R_0 \right|^2,
\end{equation}
so that the total energy of the system is
\begin{equation}
U_\mathrm{total} = U(R_0) + U(R_1) + U_\mathrm{spr}(R_0,R_1).
\end{equation}
|
energy_fn = harmonic_morse_pair(displacement,D0=5.0,alpha=10.0,r0=0.5,k=500.0)
def spring_energy_fn(Rall, k_spr=50.0, **kwargs):
metric = vmap(space.canonicalize_displacement_or_metric(displacement), (0, 0), 0)
dr = metric(Rall[0],Rall[1])
return 0.5*k_spr*np.sum((dr)**2)
def total_energy_fn(Rall, **kwargs):
return np.sum(vmap(energy_fn)(Rall)) + spring_energy_fn(Rall)
|
notebooks/customizing_potentials_cookbook.ipynb
|
google/jax-md
|
apache-2.0
|
We now have to define a new shift function that can handle arrays of shape $(2,N,d)$. In addition, we make two copies of our initial positions R, one for each system.
|
def shift_all(Rall, dRall, **kwargs):
return vmap(shift)(Rall, dRall)
Rall = np.array([R,R])
|
notebooks/customizing_potentials_cookbook.ipynb
|
google/jax-md
|
apache-2.0
|
Now, all we have to do is pass our custom energy and shift functions, as well as the $(2,N,d)$ dimensional initial position, to JAX MD, and proceed as normal.
As a demonstration, we define a simple and general Brownian Dynamics simulation function, similar to the simulation routines above except without the special cases (e.g. chaning r0 or species).
|
def run_brownian_simple(energy_or_force, R_init, shift, key, num_steps):
init, apply = simulate.brownian(energy_or_force, shift, dt=0.00001, kT=1.0, gamma=0.1)
apply = jit(apply)
@jit
def scan_fn(state, t):
return apply(state), 0
key, split = random.split(key)
state = init(split, R_init)
state, _ = lax.scan(scan_fn, state, np.arange(num_steps))
return state.position
|
notebooks/customizing_potentials_cookbook.ipynb
|
google/jax-md
|
apache-2.0
|
Note that nowhere in this function is there any indication that we are simulating an ensemble of systems. This comes entirely form the inputs: i.e. the energy function, the shift function, and the set of initial positions.
|
key, split = random.split(key)
Rall_final = run_brownian_simple(total_energy_fn, Rall, shift_all, split, num_steps=10000)
|
notebooks/customizing_potentials_cookbook.ipynb
|
google/jax-md
|
apache-2.0
|
The output also has shape $(2,N,d)$. If we display the results, we see that the two systems are in similar, but not identical, positions, showing that we have succeeded in simulating a coupled ensemble.
|
for Ri in Rall_final:
plot_system( Ri, box_size )
finalize_plot((0.5,0.5))
|
notebooks/customizing_potentials_cookbook.ipynb
|
google/jax-md
|
apache-2.0
|
<p style="text-align: right; direction: rtl; float: right; clear: both;">
תוכלו ליצור בעצמכם פונקציה שיוצרת משתמש חדש?<br>
זה לא מסובך מדי:
</p>
|
def create_user(first_name, last_name, nickname, current_age):
return {
'first_name': first_name,
'last_name': last_name,
'nickname': nickname,
'age': current_age,
}
# נקרא לפונקציה כדי לראות שהכל עובד כמצופה
new_user = create_user('Bayta', 'Darell', 'Bay', 24)
print(new_user)
|
week07/1_Classes.ipynb
|
PythonFreeCourse/Notebooks
|
mit
|
<p style="text-align: right; direction: rtl; float: right; clear: both;">
<mark>נוכל גם לממש פונקציות שיעזרו לנו לבצע פעולות על כל אחד מהמשתמשים.</mark><br>
לדוגמה: הפונקציה <var>describe_as_a_string</var> תקבל משתמש ותחזיר לנו מחרוזת שמתארת אותו,<br>
והפונקציה <var>celeberate_birthday</var> תקבל משתמש ותגדיל את גילו ב־1:
</p>
|
def describe_as_a_string(user):
first_name = user['first_name']
last_name = user['last_name']
full_name = f'{first_name} {last_name}'
nickname = user['nickname']
age = user['age']
return f'{nickname} ({full_name}) is {age} years old.'
def celebrate_birthday(user):
user['age'] = user['age'] + 1
print(describe_as_a_string(new_user))
celebrate_birthday(new_user)
print("--- After birthday")
print(describe_as_a_string(new_user))
|
week07/1_Classes.ipynb
|
PythonFreeCourse/Notebooks
|
mit
|
<div class="align-center" style="display: flex; text-align: right; direction: rtl;">
<div style="display: flex; width: 10%; float: right; ">
<img src="images/recall.svg" style="height: 50px !important;" alt="תזכורת" title="תזכורת">
</div>
<div style="width: 90%">
<p style="text-align: right; direction: rtl;">
הצלחנו לערוך את ערכו של <code>user['age']</code> מבלי להחזיר ערך, כיוון שמילונים הם mutable.<br>
אם זה נראה לכם מוזר, חזרו למחברת על mutability ו־immutability.
</p>
</div>
</div>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
בשלב הזה בתוכניתנו קיימות קבוצת פונקציות שמטרתן היא ניהול של משתמשים ושל תכונותיהם.<br>
</p>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
נוכל להוסיף למשתמש תכונות נוספות, כמו דוא"ל ומשקל, לדוגמה,<br>
או להוסיף לו פעולות שיהיה אפשר לבצע עליו, כמו הפעולה <var>eat_bourekas</var>, שמוסיפה לתכונת המשקל של המשתמש חצי קילו.<br>
</p>
<span style="text-align: right; direction: rtl; float: right; clear: both;">חסרונות</span>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
אף על פי שהרעיון נחמד, ככל שנרבה להוסיף פעולות ותכונות, תגבר תחושת האי־סדר שאופפת את הקוד הזה.<br>
קל לראות שהקוד שכתבנו מפוזר על פני פונקציות רבות בצורה לא מאורגנת.<br>
במילים אחרות – אין אף מבנה בקוד שתחתיו מאוגדות כל הפונקציות והתכונות ששייכות לטיפול במשתמש.
</p>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
הבעיה תצוף כשנרצה להוסיף לתוכנה שלנו עוד מבנים שכאלו.<br>
לדוגמה, כשנרצה להוסיף לצ'יקצ'וק יכולת לניהול סרטונים – שתכונותיהם אורך סרטון ומספר לייקים, והפעולה עליהם היא היכולת לעשות Like לסרטון.<br>
הקוד לניהול המשתמש והקוד לניהול הסרטונים עלולים להתערבב, יווצרו תלויות ביניהם וחוויית ההתמצאות בקוד תהפוך ללא נעימה בעליל.<br>
</p>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
החוסר באיגוד התכונות והפונקציות אף מקשה על הקורא להבין לאן שייכות כל אחת מהתכונות והפונקציות, ומה תפקידן בקוד.<br>
מי שמסתכל על הקוד שלנו לא יכול להבין מייד ש־<var>describe_as_a_string</var> מיועדת לפעול רק על מבנים שנוצרו מ־<var>create_user</var>.<br>
הוא עלול לנסות להכניס מבנים אחרים ולהקריס את התוכנית, או גרוע מכך – להיתקל בבאגים בעתיד, בעקבות שימוש לא נכון בפונקציה.
</p>
<span style="text-align: right; direction: rtl; float: right; clear: both;">הגדרה</span>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
במהלך המחברת ראינו דוגמאות למבנים שהגדרנו <mark>כאוספים של תכונות ושל פעולות</mark>.<br>
משתמש באפליקציית צ'יקצ'וק, לדוגמה, מורכב מהתכונות שם פרטי, שם משפחה, כינוי וגיל, ומהפעולות "חגוג יום הולדת" ו"תאר כמחרוזת".<br>
נורה עשויה להיות מורכבת מהתכונות צבע ומצב (דולקת או לא), ומהפעולות "הדלק נורה" ו"כבה נורה".<br>
</p>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
<dfn>מחלקה</dfn> היא דרך לתאר לפייתון אוסף כזה של תכונות ושל פעולות, ולאגד אותן תחת מבנה אחד.<br>
אחרי שתיארנו בעזרת מחלקה אילו תכונות ופעולות מאפיינות עצם מסוים, נוכל להשתמש בה כדי לייצר כמה עצמים כאלו שנרצה.<br>
</p>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
נדמיין מחלקה כמו שבלונה – <mark>תבנית</mark> שמתארת אילו תכונות ופעולות מאפיינות סוג עצם מסוים.<br>
מחלקה שעוסקת במשתמשים, לדוגמה, תתאר עבור פייתון מאילו תכונות ופעולות מורכב כל משתמש.<br>
</p>
<figure>
<img src="images/user_class.svg?v=1" style="max-width: 650px; margin-right: auto; margin-left: auto; text-align: center;" alt="במרכז התמונה ניצבת צללית של אדם (משתמש). בצד ימין שלו יש תיבה עם הכותרת 'תכונות', ובתוכה המילים 'שם פרטי', 'שם משפחה', 'כינוי' ו'גיל'. בצד שמאל שלו יש תיבה נוספת הנושאת את הכותרת 'פעולות', ובתוכה המילים 'חגוג יום הולדת' ו'תאר משתמש'."/>
<figcaption style="margin-top: 2rem; text-align: center; direction: rtl;">איור המתאר את התכונות ואת הפעולות השייכות למחלקה "משתמש".</figcaption>
</figure>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
בעזרת אותה מחלקת משתמשים (או שבלונת משתמשים, אם תרצו), נוכל ליצור משתמשים רבים.<br>
כל משתמש שניצור באמצעות השבלונה ייקרא "<dfn>מופע</dfn>" (או <dfn>Instance</dfn>) – יחידה אחת, עצמאית, שמכילה את התכונות והפעולות שתיארנו.<br>
אנחנו נשתמש במחלקה שוב ושוב כדי ליצור כמה משתמשים שנרצה, בדיוק כמו שנשתמש בשבלונה.
</p>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
יש עוד הרבה מה להגיד והרבה מה להגדיר, אבל נשמע שמתחתי אתכם מספיק.<br>
בואו ניגש לקוד!
</p>
<span style="text-align: right; direction: rtl; float: right; clear: both;">יצירת מחלקות</span>
<span style="text-align: right; direction: rtl; float: right; clear: both;">מחלקה בסיסית</span>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
ראשית, ניצור את המחלקה הפשוטה ביותר שאנחנו יכולים לבנות, ונקרא לה <var>User</var>.<br>
בהמשך המחברת נרחיב את המחלקה, והיא תהיה זו שמטפלת בכל הקשור במשתמשים של צ'יקצ'וק:
</p>
|
class User:
pass
|
week07/1_Classes.ipynb
|
PythonFreeCourse/Notebooks
|
mit
|
<div class="align-center" style="display: flex; text-align: right; direction: rtl;">
<div style="display: flex; width: 10%; float: right; ">
<img src="images/recall.svg" style="height: 50px !important;" alt="תזכורת" title="תזכורת">
</div>
<div style="width: 90%">
<p style="text-align: right; direction: rtl;">
ניסינו ליצור את המבנה הכי קצר שאפשר, אבל <code>class</code> חייב להכיל קוד.<br>
כדי לעקוף את המגבלה הזו, השתמשנו במילת המפתח <code>pass</code>, שאומרת לפייתון "אל תעשי כלום".
</p>
</div>
</div>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
בקוד שלמעלה השתמשנו במילת המפתח <code>class</code> כדי להצהיר על מחלקה חדשה.<br>
מייד לאחר מכן ציינו את שם המחלקה שאנחנו רוצים ליצור – <var>User</var> במקרה שלנו.<br>
שם המחלקה נתון לחלוטין לבחירתנו, והמילה <var>User</var> לא אומרת לפייתון שום דבר מיוחד. באותה המידה יכולנו לבחור כל שם אחר.
</p>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
הדבר שחשוב לזכור הוא שהמחלקה היא <em>לא</em> המשתמש עצמו, אלא רק השבלונה שלפיה פייתון תבנה את המשתמש.<br>
אמנם כרגע המחלקה <var>User</var> ריקה ולא מתארת כלום, אבל פייתון עדיין תדע ליצור משתמש חדש אם נבקש ממנה לעשות זאת.<br>
נבקש מהמחלקה ליצור עבורנו משתמש חדש. נקרא לה בשמה ונוסיף סוגריים, בדומה לקריאה לפונקציה:
</p>
|
user1 = User()
|
week07/1_Classes.ipynb
|
PythonFreeCourse/Notebooks
|
mit
|
<p style="text-align: right; direction: rtl; float: right; clear: both;">
כעת יצרנו משתמש, ואנחנו יכולים לשנות את התכונות שלו.<br>
מבחינה מילולית, נהוג להגיד שיצרנו <dfn>מופע</dfn> (<dfn>Instance</dfn>) או <dfn>עצם</dfn> (אובייקט, <dfn>Object</dfn>) מסוג <var>User</var>, ששמו <var>user1</var>.<br>
השתמשנו לשם כך ב<dfn>מחלקה</dfn> בשם <var>User</var>.
</p>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
נשנה את תכונות המשתמש.<br>
כדי להתייחס לתכונה של מופע כלשהו בפייתון, נכתוב את שם המשתנה שמצביע למופע, נקודה, ואז שם התכונה.<br>
אם נרצה לשנות את התכונה – נבצע אליה השמה:
</p>
|
user1.first_name = "Miles"
user1.last_name = "Prower"
user1.age = 8
user1.nickname = "Tails"
|
week07/1_Classes.ipynb
|
PythonFreeCourse/Notebooks
|
mit
|
<p style="text-align: right; direction: rtl; float: right; clear: both;">
נוכל לאחזר את התכונות הללו בקלות, באותה הצורה:
</p>
|
print(user1.age)
|
week07/1_Classes.ipynb
|
PythonFreeCourse/Notebooks
|
mit
|
<p style="text-align: right; direction: rtl; float: right; clear: both;">
ואם נבדוק מה הסוג של המשתנה <var>user1</var>, מצפה לנו הפתעה נחמדה:
</p>
|
type(user1)
|
week07/1_Classes.ipynb
|
PythonFreeCourse/Notebooks
|
mit
|
<p style="text-align: right; direction: rtl; float: right; clear: both;">
איזה יופי! המחלקה גרמה לכך ש־<var>User</var> הוא ממש סוג משתנה בפייתון עכשיו.<br>
קחו לעצמכם רגע להתפעל – יצרנו סוג משתנה חדש בפייתון!<br>
אם כך, המשתנה <var>user1</var> מצביע על מופע של משתמש, שסוגו <var>User</var>.
</p>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
ננסה ליצור מופע נוסף, הפעם של משתמש אחר:
</p>
|
user2 = User()
user2.first_name = "Harry"
user2.last_name = "Potter"
user2.age = 39
user2.nickname = "BoyWhoLived1980"
|
week07/1_Classes.ipynb
|
PythonFreeCourse/Notebooks
|
mit
|
<p style="text-align: right; direction: rtl; float: right; clear: both;">
ונשים לב ששני המופעים מתקיימים זה לצד זה, ולא דורסים את הערכים זה של זה:
</p>
|
print(f"{user1.first_name} {user1.last_name} is {user1.age} years old.")
print(f"{user2.first_name} {user2.last_name} is {user2.age} years old.")
|
week07/1_Classes.ipynb
|
PythonFreeCourse/Notebooks
|
mit
|
<p style="text-align: right; direction: rtl; float: right; clear: both;">
המצב הזה מתקיים כיוון שכל קריאה למחלקה <var>User</var> יוצרת מופע חדש של משתמש.<br>
כל אחד מהמופעים הוא ישות נפרדת שמתקיימת בזכות עצמה.
</p>
<div class="align-center" style="display: flex; text-align: right; direction: rtl; clear: both;">
<div style="display: flex; width: 10%; float: right; clear: both;">
<img src="images/exercise.svg" style="height: 50px !important;" alt="תרגול">
</div>
<div style="width: 70%">
<p style="text-align: right; direction: rtl; float: right; clear: both;">
צרו מחלקה בשם <var>Point</var> שמייצגת נקודה.<br>
צרו 2 מופעים של נקודות: אחת בעלת <var>x</var> שערכו 3 ו־<var>y</var> שערכו 1, והשנייה בעלת <var>x</var> שערכו 4 ו־<var>y</var> שערכו 1.
</p>
</div>
<div style="display: flex; width: 20%; border-right: 0.1rem solid #A5A5A5; padding: 1rem 2rem;">
<p style="text-align: center; direction: rtl; justify-content: center; align-items: center; clear: both;">
<strong>חשוב!</strong><br>
פתרו לפני שתמשיכו!
</p>
</div>
</div>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
שמות מחלקה ייכתבו באות גדולה בתחילתם, כדי להבדילם מפונקציות וממשתנים רגילים.<br>
אם שם המחלקה מורכב מכמה מילים, האות הראשונה בכל מילה תהא אות גדולה. בשם לא יופיעו קווים תחתונים.<br>
לדוגמה, מחלקת <var>PopSong</var>.
</p>
<span style="text-align: right; direction: rtl; float: right; clear: both;">מחלקה עם פעולות</span>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
יצירת מחלקה ריקה זה נחמד, אבל זה לא מרגיש שעשינו צעד מספיק משמעותי כדי לשפר את איכות הקוד מתחילת המחברת.<br>
לדוגמה, אם אנחנו רוצים להדפיס את הפרטים של משתמש מסוים, עדיין נצטרך לכתוב פונקציה כזו:
</p>
|
def describe_as_a_string(user):
full_name = f'{user.first_name} {user.last_name}'
return f'{user.nickname} ({full_name}) is {user.age} years old.'
print(describe_as_a_string(user2))
|
week07/1_Classes.ipynb
|
PythonFreeCourse/Notebooks
|
mit
|
<p style="text-align: right; direction: rtl; float: right; clear: both;">
הפונקציה עדיין מסתובבת לה חופשייה ולא מאוגדת תחת אף מבנה – וזה בדיוק המצב שניסינו למנוע.<br>
למזלנו הפתרון לבעיית איגוד הקוד הוא פשוט. נוכל להדביק את קוד הפונקציה תחת המחלקה <code>User</code>:
</p>
|
class User:
def describe_as_a_string(user):
full_name = f'{user.first_name} {user.last_name}'
return f'{user.nickname} ({full_name}) is {user.age} years old.'
user3 = User()
user3.first_name = "Anthony John"
user3.last_name = "Soprano"
user3.age = 61
user3.nickname = "Tony"
|
week07/1_Classes.ipynb
|
PythonFreeCourse/Notebooks
|
mit
|
<p style="text-align: right; direction: rtl; float: right; clear: both;">
בתא שלמעלה הגדרנו את הפונקציה <var>describe_as_a_string</var> בתוך המחלקה <var>User</var>.<br>
פונקציה שמוגדרת בתוך מחלקה נקראת <dfn>פעולה</dfn> (<dfn>Method</dfn>), שם שניתן לה כדי לבדל אותה מילולית מפונקציה רגילה.
</p>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
למעשה, בתא שלמעלה הוספנו את הפעולה <var>describe_as_a_string</var> לשבלונה של המשתמש.<br>
מעכשיו, כל מופע חדש של משתמש יוכל לקרוא לפעולה <var>describe_as_a_string</var> בצורה הבאה:
</p>
|
user3.describe_as_a_string()
|
week07/1_Classes.ipynb
|
PythonFreeCourse/Notebooks
|
mit
|
<p style="text-align: right; direction: rtl; float: right; clear: both;">
חדי העין שמו ודאי לב למשהו מעט משונה בקריאה לפעולה <var>describe_as_a_string</var>.<br>
הפעולה מצפה לקבל פרמטר (קראנו לו <var>user</var>), אבל כשקראנו לה בתא האחרון לא העברנו לה אף ארגומנט!<br>
</p>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
זהו קסם ידוע ונחמד של מחלקות: כשמופע קורא לפעולה כלשהי – אותו מופע עצמו מועבר אוטומטית כארגומנט הראשון לפעולה.<br>
לדוגמה, בקריאה <code dir="ltr">user3.describe_as_a_string()</code>, המופע <var>user3</var> הועבר לתוך הפרמטר <var>user</var> של <var>describe_as_a_string</var>.<br>
</p>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
המוסכמה היא לקרוא תמיד לפרמטר הקסום הזה, זה שהולך לקבל את המופע, בשם <var>self</var>.<br>
נשנה את ההגדרה שלנו בהתאם למוסכמה:
</p>
|
class User:
def describe_as_a_string(self):
full_name = f'{self.first_name} {self.last_name}'
return f'{self.nickname} ({full_name}) is {self.age} years old.'
user3 = User()
user3.first_name = "Anthony John"
user3.last_name = "Soprano"
user3.age = 61
user3.nickname = "Tony"
user3.describe_as_a_string()
|
week07/1_Classes.ipynb
|
PythonFreeCourse/Notebooks
|
mit
|
<div class="align-center" style="display: flex; text-align: right; direction: rtl;">
<div style="display: flex; width: 10%; float: right; ">
<img src="images/warning.png" style="height: 50px !important;" alt="אזהרה!">
</div>
<div style="width: 90%">
<p style="text-align: right; direction: rtl;">
טעות נפוצה היא לשכוח לשים <var>self</var> כפרמטר הראשון בפעולות שנגדיר.
</p>
</div>
</div>
<div class="align-center" style="display: flex; text-align: right; direction: rtl; clear: both;">
<div style="display: flex; width: 10%; float: right; clear: both;">
<img src="images/exercise.svg" style="height: 50px !important;" alt="תרגול">
</div>
<div style="width: 70%">
<p style="text-align: right; direction: rtl; float: right; clear: both;">
צרו פעולה בשם <var>describe_as_a_string</var> עבור מחלקת <var>Point</var> שיצרתם.<br>
הפעולה תחזיר מחרוזת בצורת <samp dir="ltr">(x, y)</samp>.
</p>
</div>
<div style="display: flex; width: 20%; border-right: 0.1rem solid #A5A5A5; padding: 1rem 2rem;">
<p style="text-align: center; direction: rtl; justify-content: center; align-items: center; clear: both;">
<strong>חשוב!</strong><br>
פתרו לפני שתמשיכו!
</p>
</div>
</div>
<span style="text-align: right; direction: rtl; float: right; clear: both;">יצירת מופע</span>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
הפיסה החסרה בפאזל היא יצירת המופע.<br>
אם נרצה ליצור משתמש חדש, עדיין נצטרך להציב בו תכונות אחת־אחת – וזה לא כזה כיף.<br>
נשדרג את עצמנו ונכתוב פונקציה שקוראת ל־<var>User</var> ויוצרת מופע עם כל התכונות שלו:<br>
</p>
|
def create_user(first_name, last_name, nickname, current_age):
user = User()
user.first_name = first_name
user.last_name = last_name
user.nickname = nickname
user.age = current_age
return user
user4 = create_user('Daenerys', 'Targaryen', 'Mhysa', 23)
print(f"{user4.first_name} {user4.last_name} is {user4.age} years old.")
|
week07/1_Classes.ipynb
|
PythonFreeCourse/Notebooks
|
mit
|
<p style="text-align: right; direction: rtl; float: right; clear: both;">
אבל הגדרה שכזו, כמו שכבר אמרנו, סותרת את כל הרעיון של מחלקות.<br>
הרי המטרה של מחלקות היא קיבוץ כל מה שקשור בניהול התכונות והפעולות תחת המחלקה.
</p>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
נעתיק את <var>create_user</var> לתוך מחלקת <var>User</var>, בשינויים קלים:
</p>
<ol style="text-align: right; direction: rtl; float: right; clear: both;">
<li>לא נשכח לשים את <var>self</var> כפרמטר ראשון בחתימת הפעולה.</li>
<li>כפי שראינו, פעולות במחלקה מקבלות מופע ועובדות ישירות עליו, ולכן נשמיט את השורות <code dir="ltr">user = User()</code> ו־<code dir="ltr">return user</code>.</li>
</ol>
|
class User:
def describe_as_a_string(self):
full_name = f'{self.first_name} {self.last_name}'
return f'{self.nickname} ({full_name}) is {self.age} years old.'
def create_user(self, first_name, last_name, nickname, current_age):
self.first_name = first_name
self.last_name = last_name
self.nickname = nickname
self.age = current_age
|
week07/1_Classes.ipynb
|
PythonFreeCourse/Notebooks
|
mit
|
<p style="text-align: right; direction: rtl; float: right; clear: both;">
עכשיו נוכל ליצור משתמש חדש, בצורה החביבה והמקוצרת הבאה:
</p>
|
user4 = User()
user4.create_user('Daenerys', 'Targaryen', 'Mhysa', 23)
user4.describe_as_a_string()
|
week07/1_Classes.ipynb
|
PythonFreeCourse/Notebooks
|
mit
|
<span style="text-align: right; direction: rtl; float: right; clear: both;">תרגיל ביניים: מחלקת נקודות</span>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
מינרווה מקגונגל יצאה לבילוי לילי בסמטת דיאגון,<br>
ואחרי לילה עמוס בשתיית שיכר בקלחת הרותחת, היא מעט מתקשה לחזור להוגוורטס.
</p>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
הוסיפו את הפעולות <var>create_point</var> ו־<var>distance</var> למחלקת הנקודה שיצרתם.<br>
הפעולה <var>create_point</var> תקבל כפרמטרים <var>x</var> ו־<var>y</var>, ותיצוק תוכן למופע שיצרתם.<br>
הפעולה <var>distance</var> תחזיר את המרחק של מקגונגל מהוגוורטס, הממוקם בנקודה <span dir="ltr">(0, 0)</span>.
</p>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
נוסחת המרחק היא חיבור בין הערכים המוחלטים של נקודות ה־<var>x</var> וה־<var>y</var>.<br>
לדוגמה:
</p>
<ul style="text-align: right; direction: rtl; float: right; clear: both;">
<li>המרחק מהנקודה <pre dir="ltr" style="display: inline; margin: 0 0.5em;">x = 5, y = 3</pre> הוא <samp>8</samp>.</li>
<li>המרחק מהנקודה <pre dir="ltr" style="display: inline; margin: 0 0.5em;">x = 0, y = 3</pre> הוא <samp>3</samp>.</li>
<li>המרחק מהנקודה <pre dir="ltr" style="display: inline; margin: 0 0.5em;">x = -3, y = 3</pre> הוא <samp>6</samp>.</li>
<li>המרחק מהנקודה <pre dir="ltr" style="display: inline; margin: 0 0.5em;">x = -5, y = 0</pre> הוא <samp>5</samp>.</li>
<li>המרחק מהנקודה <pre dir="ltr" style="display: inline; margin: 0 0.5em;">x = 0, y = 0</pre> הוא <samp>0</samp>.</li>
</ul>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
ודאו שהתוכנית שלכם מחזירה <samp dir="ltr">Success!</samp> עבור הקוד הבא:
</p>
|
current_location = Point()
current_location.create_point(5, 3)
if current_location.distance() == 8:
print("Success!")
|
week07/1_Classes.ipynb
|
PythonFreeCourse/Notebooks
|
mit
|
<span style="text-align: right; direction: rtl; float: right; clear: both;">פעולות קסם</span>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
כדי להקל אפילו עוד יותר על המלאכה, בפייתון יש <dfn>פעולות קסם</dfn> (<dfn>Magic Methods</dfn>).<br>
אלו פעולות עם שם מיוחד, שאם נגדיר אותן במחלקה, הן ישנו את ההתנהגות שלה או של המופעים הנוצרים בעזרתה.
</p>
<h4 style="text-align: right; direction: rtl; float: right; clear: both;">הפעולה <code>__str__</code></h4>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
נתחיל, לדוגמה, מהיכרות קצרה עם פעולת הקסם <code>__str__</code> (עם קו תחתון כפול, מימין ומשמאל לשם הפעולה).<br>
אם ננסה סתם ככה להמיר למחרוזת את <var>user4</var> שיצרנו קודם לכן, נקבל בהלה והיסטריה:
|
user4 = User()
user4.create_user('Daenerys', 'Targaryen', 'Mhysa', 23)
str(user4)
|
week07/1_Classes.ipynb
|
PythonFreeCourse/Notebooks
|
mit
|
<p style="text-align: right; direction: rtl; float: right; clear: both;">
פייתון אמנם אומרת דברים נכונים, כמו שמדובר באובייקט (מופע) מהמחלקה <var>User</var> ואת הכתובת שלו בזיכרון, אבל זה לא באמת מועיל.<br>
</p>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
כיוון שפונקציית ההדפסה <var>print</var>, מאחורי הקלעים, מבקשת את צורת המחרוזת של הארגומנט שמועבר אליה,<br>
גם קריאה ל־<var>print</var> ישירות על <var>user4</var> תיצור את אותה תוצאה לא ססגונית:
</p>
|
print(user4)
|
week07/1_Classes.ipynb
|
PythonFreeCourse/Notebooks
|
mit
|
<p style="text-align: right; direction: rtl; float: right; clear: both;">
המחלקה שלנו, כמובן, כבר ערוכה להתמודד עם המצב.<br>
בזכות הפעולה <var>describe_as_a_string</var> שהגדרנו קודם לכן נוכל להדפיס את פרטי המשתמש בקלות יחסית:
</p>
|
print(user4.describe_as_a_string())
|
week07/1_Classes.ipynb
|
PythonFreeCourse/Notebooks
|
mit
|
<p style="text-align: right; direction: rtl; float: right; clear: both;">
אבל יש דרך קלה עוד יותר!<br>
ניחשתם נכון – פעולת הקסם <code>__str__</code>.<br>
נחליף את השם של הפעולה <var>describe_as_a_string</var>, ל־<code>__str__</code>:
</p>
|
class User:
def __str__(self):
full_name = f'{self.first_name} {self.last_name}'
return f'{self.nickname} ({full_name}) is {self.age} years old.'
def create_user(self, first_name, last_name, nickname, current_age):
self.first_name = first_name
self.last_name = last_name
self.nickname = nickname
self.age = current_age
user5 = User()
user5.create_user('James', 'McNulty', 'Jimmy', 49)
print(user5)
|
week07/1_Classes.ipynb
|
PythonFreeCourse/Notebooks
|
mit
|
<p style="text-align: right; direction: rtl; float: right; clear: both;">
ראו איזה קסם! עכשיו המרה של כל מופע מסוג <var>User</var> למחרוזת היא פעולה ממש פשוטה!<br>
</p>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
בתא שלמעלה, הגדרנו את פעולת הקסם <code>__str__</code>.<br>
הפעולה מקבלת כפרמטר את <var>self</var>, המופע שביקשנו להמיר למחרוזת,<br>
ומחזירה לנו מחרוזת שאנחנו הגדרנו כמחרוזת שמתארת את המופע.
</p>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
הגדרת פעולת הקסם <code>__str__</code> עבור מחלקה מסוימת מאפשרת לנו להמיר מופעים למחרוזות בצורה טבעית.
</p>
<h4 style="text-align: right; direction: rtl; float: right; clear: both;">הפעולה <code>__init__</code></h4>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
פעולת קסם חשובה אף יותר, ואולי המפורסמת ביותר, נקראת <code>__init__</code>.<br>
היא מאפשרת לנו להגדיר מה יקרה ברגע שניצור מופע חדש:
</p>
|
class User:
def __init__(self):
print("New user has been created!")
def __str__(self):
full_name = f'{self.first_name} {self.last_name}'
return f'{self.nickname} ({full_name}) is {self.age} years old.'
def create_user(self, first_name, last_name, nickname, current_age):
self.first_name = first_name
self.last_name = last_name
self.nickname = nickname
self.age = current_age
user5 = User()
user5.create_user('Lorne', 'Malvo', 'Mick', 23)
print(user5)
|
week07/1_Classes.ipynb
|
PythonFreeCourse/Notebooks
|
mit
|
<p style="text-align: right; direction: rtl; float: right; clear: both;">
בדוגמת הקוד שלמעלה הגדרנו את פעולת הקסם <code>__init__</code>, שתרוץ מייד כשנוצר מופע חדש.<br>
החלטנו שברגע שייווצר מופע של משתמש, תודפס ההודעה <samp dir="ltr">New user has been created!</samp>.
</p>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
הכיף הגדול ב־<code>__init__</code> הוא היכולת שלה לקבל פרמטרים.<br>
נוכל להעביר אליה את הארגומנטים בקריאה לשם המחלקה, בעת יצירת המופע 🤯
</p>
|
class User:
def __init__(self, message):
self.creation_message = message
print(self.creation_message)
def __str__(self):
full_name = f'{self.first_name} {self.last_name}'
return f'{self.nickname} ({full_name}) is {self.age} years old.'
def create_user(self, first_name, last_name, nickname, current_age):
self.first_name = first_name
self.last_name = last_name
self.nickname = nickname
self.age = current_age
user5 = User("New user has been created!") # תראו איזה מגניב
user5.create_user('Lorne', 'Malvo', 'Mick', 58)
print(user5)
print(f"We still have the message: {user5.creation_message}")
|
week07/1_Classes.ipynb
|
PythonFreeCourse/Notebooks
|
mit
|
<p style="text-align: right; direction: rtl; float: right; clear: both;">
בתא שלמעלה הגדרנו שפעולת הקסם <code>__init__</code> תקבל כפרמטר הודעה להדפסה.<br>
ההודעה תישמר בתכונה <var>creation_message</var> השייכת למופע, ותודפס מייד לאחר מכן.<br>
את ההודעה העברנו כארגומנט בעת הקריאה לשם המחלקה, <var>User</var>, שיוצרת את המופע.
</p>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
ואם כבר יש לנו משהו שרץ כשאנחנו יוצרים את המופע... והוא יודע לקבל פרמטרים...<br>
אתם חושבים על מה שאני חושב?<br>
בואו נשנה את השם של <var>create_user</var> ל־<code>__init__</code>!<br>
בצורה הזו נוכל לצקת את התכונות למופע מייד עם יצירתו, ולוותר על קריאה נפרדת לפעולה שמטרתה למלא את הערכים:
</p>
|
class User:
def __init__(self, first_name, last_name, nickname, current_age):
self.first_name = first_name
self.last_name = last_name
self.nickname = nickname
self.age = current_age
print("Yayy! We have just created a new instance! :D")
def __str__(self):
full_name = f'{self.first_name} {self.last_name}'
return f'{self.nickname} ({full_name}) is {self.age} years old.'
user5 = User('Lorne', 'Malvo', 'Mick', 58)
print(user5)
|
week07/1_Classes.ipynb
|
PythonFreeCourse/Notebooks
|
mit
|
<p style="text-align: right; direction: rtl; float: right; clear: both;">
איגדנו את יצירת תכונות המופע תחת פעולה אחת, שרצה כשהוא נוצר.<br>
הרעיון הנפלא הזה נפוץ מאוד בשפות תכנות שתומכות במחלקות, ומוכרת בשם <dfn>פעולת אתחול</dfn> (<dfn>Initialization Method</dfn>).<br>
זו גם הסיבה לשם הפעולה – המילה init נגזרת מהמילה initialization, אתחול.
</p>
<div class="align-center" style="display: flex; text-align: right; direction: rtl; clear: both;">
<div style="display: flex; width: 10%; float: right; clear: both;">
<img src="images/exercise.svg" style="height: 50px !important;" alt="תרגול">
</div>
<div style="width: 70%">
<p style="text-align: right; direction: rtl; float: right; clear: both;">
שפצו את מחלקת הנקודה שיצרתם, כך שתכיל <code>__init__</code> ו־<code>__str__</code>.
</p>
</div>
<div style="display: flex; width: 20%; border-right: 0.1rem solid #A5A5A5; padding: 1rem 2rem;">
<p style="text-align: center; direction: rtl; justify-content: center; align-items: center; clear: both;">
<strong>חשוב!</strong><br>
פתרו לפני שתמשיכו!
</p>
</div>
</div>
<span style="text-align: right; direction: rtl; float: right; clear: both;">ייצור מסחרי</span>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
צ'יקצ'וק שמה את ידה על פרטי המשתמשים של הרשת החברתית המתחרה, סניילצ'אט.<br>
רשימת המשתמשים נראית כך:
</p>
|
snailchat_users = [
['Mike', 'Shugarberg', 'Marker', 36],
['Hammer', 'Doorsoy', 'Tzweetz', 43],
['Evan', 'Spygirl', 'Odd', 30],
]
|
week07/1_Classes.ipynb
|
PythonFreeCourse/Notebooks
|
mit
|
<p style="text-align: right; direction: rtl; float: right; clear: both;">
נניח, לכאורה בלבד, שאנחנו רוצים להעתיק את אותה רשימת משתמשים ולצרף אותה לרשת החברתית שלנו.<br>
קחו דקה וחשבו איך הייתם עושים את זה.
</p>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
זכרו שקריאה למחלקה <var>User</var> היא ככל קריאה לפונקציה אחרת,<br>
ושהמופע שחוזר ממנה הוא ערך בדיוק כמו כל ערך אחר.
</p>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
נוכל ליצור רשימת מופעים של משתמשים. לדוגמה:
</p>
|
our_users = []
for user_details in snailchat_users:
new_user = User(*user_details) # Unpacking – התא הראשון עובר לפרמטר התואם, וכך גם השני, השלישי והרביעי
our_users.append(new_user)
print(new_user)
|
week07/1_Classes.ipynb
|
PythonFreeCourse/Notebooks
|
mit
|
<p style="text-align: right; direction: rtl; float: right; clear: both;">
בקוד שלמעלה יצרנו רשימה ריקה, שאותה נמלא במשתמשים <strike>שנגנוב</strike> שנשאיל מסניילצ'אט.<br>
נעביר את הפרטים של כל אחד מהמשתמשים המופיעים ב־<var>snailchat_users</var>, ל־<code>__init__</code> של <var>User</var>,<br>
ונצרף את המופע החדש שנוצר לתוך הרשימה החדשה שיצרנו.
</p>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
עכשיו הרשימה <var>our_users</var> היא רשימה לכל דבר, שכוללת את כל המשתמשים החדשים שהצטרפו לרשת החברתית שלנו:
</p>
|
print(our_users[0])
print(our_users[1])
print(our_users[2])
|
week07/1_Classes.ipynb
|
PythonFreeCourse/Notebooks
|
mit
|
<div class="align-center" style="display: flex; text-align: right; direction: rtl; clear: both;">
<div style="display: flex; width: 10%; float: right; clear: both;">
<img src="images/exercise.svg" style="height: 50px !important;" alt="תרגול">
</div>
<div style="width: 70%">
<p style="text-align: right; direction: rtl; float: right; clear: both;">
צרו את רשימת כל הנקודות שה־x וה־y שלהן הוא מספר שלם בין 0 ל־6.<br>
לדוגמה, רשימת כל הנקודות שה־x וה־y שלהן הוא בין 0 ל־2 היא:<br>
<samp dir="ltr">[(0, 0), (0, 1), (1, 0), (1, 1), (0, 2), (1, 2), (2, 0), (2, 1), (2, 2)]</samp>
</p>
</div>
<div style="display: flex; width: 20%; border-right: 0.1rem solid #A5A5A5; padding: 1rem 2rem;">
<p style="text-align: center; direction: rtl; justify-content: center; align-items: center; clear: both;">
<strong>חשוב!</strong><br>
פתרו לפני שתמשיכו!
</p>
</div>
</div>
<span style="text-align: right; direction: rtl; float: right; clear: both;">טעויות נפוצות</span>
<span style="text-align: right; direction: rtl; float: right; clear: both;">גבולות מרחב הערכים</span>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
נסקור כמה דוגמאות כדי לוודא שבאמת הבנו כיצד מתנהגות מחלקות.<br>
נגדיר את מחלקת <var>User</var> שאנחנו מכירים, ונצרף לה את הפעולה <var>celebrate_birthday</var>, שכזכור, מגדילה את גיל המשתמש ב־1:
</p>
|
class User:
def __init__(self, first_name, last_name, nickname, current_age):
self.first_name = first_name
self.last_name = last_name
self.nickname = nickname
self.age = current_age
def celebrate_birthday(self):
age = age + 1
def __str__(self):
full_name = f'{self.first_name} {self.last_name}'
return f'{self.nickname} ({full_name}) is {self.age} years old.'
|
week07/1_Classes.ipynb
|
PythonFreeCourse/Notebooks
|
mit
|
<p style="text-align: right; direction: rtl; float: right; clear: both;">
ניסיון ליצור מופע של משתמש ולחגוג לו יום הולדת יגרום לשגיאה.<br>
תוכלו לנחש מה תהיה השגיאה עוד לפני שתריצו?
</p>
|
user6 = User('Winston', 'Smith', 'Jeeves', 39)
user6.celebrate_birthday()
|
week07/1_Classes.ipynb
|
PythonFreeCourse/Notebooks
|
mit
|
<p style="text-align: right; direction: rtl; float: right; clear: both;">
ניסינו לשנות את המשתנה <var>age</var> – אך הוא אינו מוגדר.<br>
כדי לשנות את הגיל של המשתמש שיצרנו, נהיה חייבים להתייחס ל־<code>self.age</code>.<br>
אם לא נציין במפורש שאנחנו רוצים לשנות את התכונה <var>age</var> ששייכת ל־<var>self</var>, פייתון לא תדע לאיזה מופע אנחנו מתכוונים.<br>
נתקן:
</p>
|
class User:
def __init__(self, first_name, last_name, nickname, current_age):
self.first_name = first_name
self.last_name = last_name
self.nickname = nickname
self.age = current_age
def celebrate_birthday(self):
self.age = self.age + 1
def __str__(self):
full_name = f'{self.first_name} {self.last_name}'
return f'{self.nickname} ({full_name}) is {self.age} years old.'
user6 = User('Winston', 'Smith', 'Jeeves', 39)
print(f"User before birthday: {user6}")
user6.celebrate_birthday()
print(f"User after birthday: {user6}")
|
week07/1_Classes.ipynb
|
PythonFreeCourse/Notebooks
|
mit
|
<p style="text-align: right; direction: rtl; float: right; clear: both;">
באותה המידה, תכונות שהוגדרו כחלק ממופע לא מוגדרות מחוצה לו.<br>
אפשר להשתמש, לדוגמה, בשם המשתנה <var>age</var> מבלי לחשוש לפגוע בתפקוד המחלקה או בתפקוד המופעים:
</p>
|
user6 = User('Winston', 'Smith', 'Jeeves', 39)
print(user6)
age = 10
print(user6)
|
week07/1_Classes.ipynb
|
PythonFreeCourse/Notebooks
|
mit
|
<p style="text-align: right; direction: rtl; float: right; clear: both;">
כדי לשנות את גילו של המשתמש, נצטרך להתייחס אל התכונה שלו בצורת הכתיבה שלמדנו:
</p>
|
user6.age = 10
print(user6)
|
week07/1_Classes.ipynb
|
PythonFreeCourse/Notebooks
|
mit
|
<span style="text-align: right; direction: rtl; float: right; clear: both;">תכונה או פעולה שלא קיימות</span>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
שגיאה שמתרחשת לא מעט היא פנייה לתכונה או לפעולה שלא קיימות עבור המופע.<br>
לדוגמה:
</p>
|
class Dice:
def __init__(self, number):
if 1 <= number <= 6:
self.is_valid = True
dice_bag = [Dice(roll_result) for roll_result in range(7)]
|
week07/1_Classes.ipynb
|
PythonFreeCourse/Notebooks
|
mit
|
<p style="text-align: right; direction: rtl; float: right; clear: both;">
יצרנו רשימת קוביות וביצענו השמה כך ש־<var>dice_bag</var> תצביע עליה.<br>
כעת נדפיס את התכונה <var>is_valid</var> של כל אחת מהקוביות:
</p>
|
for dice in dice_bag:
print(dice.is_valid)
|
week07/1_Classes.ipynb
|
PythonFreeCourse/Notebooks
|
mit
|
<p style="text-align: right; direction: rtl; float: right; clear: both;">
הבעיה היא שהקוביה הראשונה שיצרנו קיבלה את המספר 0.<br>
במקרה כזה, התנאי בפעולת האתחול (<code>__init__</code>) לא יתקיים, והתכונה <var>is_valid</var> לא תוגדר.<br>
כשהלולאה תגיע לקובייה 0 ותנסה לגשת לתכונה <var>is_valid</var>, נגלה שהיא לא קיימת עבור הקובייה 0, ונקבל <var>AttributeError</var>.
</p>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
נתקן:
</p>
|
class Dice:
def __init__(self, number):
self.is_valid = (1 <= number <= 6) # לא חייבים סוגריים
dice_bag = [Dice(roll_result) for roll_result in range(7)]
for dice in dice_bag:
print(dice.is_valid)
|
week07/1_Classes.ipynb
|
PythonFreeCourse/Notebooks
|
mit
|
<span style="text-align: right; direction: rtl; float: right; clear: both;">סיכום</span>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
במחברת זו רכשנו כלים לעבודה עם מחלקות ועצמים, ולייצוג אוספים של תכונות ופעולות.<br>
כלים אלו יעזרו לנו לארגן טוב יותר את התוכנית שלנו ולייצג ישויות מהעולם האמיתי בצורה אינטואיטיבית יותר.
</p>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
נהוג לכנות את עולם המחלקות בשם "<dfn>תכנות מונחה עצמים</dfn>" (<dfn>Object Oriented Programming</dfn>, או <dfn>OOP</dfn>).<br>
זו פרדיגמת תכנות הדוגלת ביצירת מחלקות לצורך חלוקת קוד טובה יותר,<br>
ובתיאור עצמים מהעולם האמיתי בצורה טובה יותר, כאוספים של תכונות ופעולות.
</p>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
תכנות מונחה עצמים הוא פיתוח מאוחר יותר של פרדיגמת תכנות אחרת שאתם כבר מכירים, הנקראת "<dfn>תכנות פרוצדורלי</dfn>".<br>
פרדיגמה זו דוגלת בחלוקת הקוד לתתי־תוכניות קטנות (מה שאתם מכירים כפונקציות), כדי ליצור קוד שמחולק טוב יותר וקל יותר לתחזוק.
</p>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
פייתון תומכת הן בתכנות פרוצדורלי והן בתכנות מונחה עצמים.
</p>
<span style="text-align: right; direction: rtl; float: right; clear: both;">מונחים</span>
<dl style="text-align: right; direction: rtl; float: right; clear: both;">
<dt>מחלקה (Class)</dt>
<dd>
תבנית, או שבלונה, שמתארת אוסף של תכונות ופעולות שיש ביניהן קשר.<br>
המחלקה מגדירה מבנה שבעזרתו נוכל ליצור בקלות עצם מוגדר, שוב ושוב.<br>
לדוגמה: מחלקה המתארת משתמש ברשת חברתית, מחלקה המתארת כלי רכב, מחלקה המתארת נקודה במישור.
</dd>
<dt>מופע (Instance)</dt>
<dd>
נקרא גם <dfn>עצם</dfn> (<dfn>Object</dfn>).<br>
ערך שנוצר על ידי מחלקה כלשהי. סוג הערך ייקבע לפי המחלקה שיצרה אותו.<br>
הערך נוצר לפי התבנית ("השבלונה") של המחלקה שממנה הוא נוצר, ומוצמדות לו הפעולות שהוגדרו במחלקה.<br>
המופע הוא יחידה עצמאית שעומדת בפני עצמה. לרוב מחלקה תשמש אותנו ליצירת מופעים רבים.<br>
לדוגמה: המופע "נקודה שנמצאת ב־<span dir="ltr">(5, 3)</span>" יהיה מופע שנוצר מהמחלקה "נקודה".
</dd>
<dt>תכונה (Property, Member)</dt>
<dd>
ערך אופייני למופע שנוצר מהמחלקה.<br>
משתנים השייכים למופע שנוצר מהמחלקה, ומכילים ערכים שמתארים אותו.<br>
לדוגמה: לנקודה במישור יש ערך x וערך y. אלו 2 תכונות של הנקודה.<br>
נוכל להחליט שתכונותיה של מחלקת מכונית יהיו צבע, דגם ויצרן.
</dd>
<dt>פעולה (Method)</dt>
<dd>
פונקציה שמוגדרת בגוף המחלקה.<br>
מתארת התנהגויות אפשריות של המופע שייווצר מהמחלקה.<br>
לדוגמה: פעולה על נקודה במישור יכולה להיות מציאת מרחקה מראשית הצירים.<br>
פעולה על שולחן יכולה להיות "קצץ 5 סנטימטר מגובהו".
</dd>
<dt>שדה (Field, Attribute)</dt>
<dd>
שם כללי הנועד לתאר תכונה או פעולה.<br>
שדות של מופע מסוים יהיו כלל התכונות והפעולות שאפשר לגשת אליהן מאותו מופע.<br>
לדוגמה: השדות של נקודה יהיו התכונות x ו־y, והפעולה שבודקת את מרחקה מראשית הצירים.
</dd>
<dt>פעולה מיוחדת (Special Method)</dt>
<dd>
ידועה גם כ־<dfn>dunder method</dfn> (double under, קו תחתון כפול) או כ־<dfn>magic method</dfn> (פעולת קסם).<br>
פעולה שהגדרתה במחלקה גורמת למחלקה או למופעים הנוצרים ממנה להתנהגות מיוחדת.<br>
דוגמאות לפעולות שכאלו הן <code>__init__</code> ו־<code>__str__</code>.
</dd>
<dt>פעולת אתחול (Initialization Method)</dt>
<dd>
פעולה שרצה עם יצירת מופע חדש מתוך מחלקה.<br>
לרוב משתמשים בפעולה זו כדי להזין במופע ערכים התחלתיים.
</dd>
<dt>תכנות מונחה עצמים (Object Oriented Programming)</dt>
<dd>
פרדיגמת תכנות שמשתמשת במחלקות בקוד ככלי העיקרי להפשטה של העולם האמיתי.<br>
בפרדיגמה זו נהוג ליצור מחלקות המייצגות תבניות של עצמים, ולאפיין את העצמים באמצעות תכונות ופעולות.<br>
בעזרת המחלקות אפשר ליצור מופעים, שהם ייצוג של פריט בודד (עצם, אובייקט) שנוצר לפי תבנית המחלקה.
</dd>
</dl>
<span style="text-align: right; direction: rtl; float: right; clear: both;">תרגיל לדוגמה</span>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
כתבו מחלקה המייצגת נתיב תקין במערכת ההפעלה חלונות.<br>
הנתיב מחולק לחלקים באמצעות התו / או התו \.<br>
החלק הראשון בנתיב הוא תמיד אות הכונן ואחריה נקודתיים.<br>
החלקים שנמצאים אחרי החלק הראשון, ככל שיש כאלו, הם תיקיות וקבצים.<br>
דוגמאות לנתיבים תקינים:
</p>
<ul style="text-align: right; direction: rtl; float: right; clear: both;">
<li><span dir="ltr">C:\Users\Yam\python.jpg</span></li>
<li><span dir="ltr">C:/Users/Yam/python.jpg</span></li>
<li><span dir="ltr">C:</span></li>
<li><span dir="ltr">C:\</span></li>
<li><span dir="ltr">C:/</span></li>
<li><span dir="ltr">C:\User/</span></li>
<li><span dir="ltr">D:/User/</span></li>
<li><span dir="ltr">C:/User</span></li>
</ul>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
המחלקה תכלול את הפעולות הבאות:
</p>
<ul style="text-align: right; direction: rtl; float: right; clear: both;">
<li>אחזר את אות הכונן בעזרת הפעולה <var>get_drive_letter</var>.</li>
<li>אחזר את הנתיב ללא חלקו האחרון בעזרת הפעולה <var>get_dirname</var>.</li>
<li>אחזר את שם החלק האחרון בנתיב, בעזרת הפעולה <var>get_basename</var>.</li>
<li>אחזר את סיומת הקובץ בעזרת הפעולה <var>get_extension</var>.</li>
<li>אחזר אם הנתיב קיים במחשב בעזרת הפעולה <var>is_exists</var>.</li>
<li>אחזר את הנתיב כולו כמחרוזת, כשהתו המפריד הוא <samp>/</samp>, וללא <samp>/</samp> בסוף הנתיב.</li>
</ul>
|
import os
class Path:
def __init__(self, path):
self.fullpath = path
self.parts = list(self.get_parts())
def get_parts(self):
current_part = ""
for char in self.fullpath:
if char in r"\/":
yield current_part
current_part = ""
else:
current_part = current_part + char
if current_part != "":
yield current_part
def get_drive_letter(self):
return self.parts[0].rstrip(":")
def get_dirname(self):
path = "/".join(self.parts[:-1])
return Path(path)
def get_basename(self):
return self.parts[-1]
def get_extension(self):
name = self.get_basename()
i = name.rfind('.')
if 0 < i < len(name) - 1:
return name[i + 1:]
return ''
def is_exists(self):
return os.path.exists(str(self))
def normalize_path(self):
normalized = "\\".join(self.parts)
return normalized.rstrip("\\")
def info_message(self):
return f"""
Some info about "{self}":
Drive letter: {self.get_drive_letter()}
Dirname: {self.get_dirname()}
Last part of path: {self.get_basename()}
File extension: {self.get_extension()}
Is exists?: {self.is_exists()}
""".strip()
def __str__(self):
return self.normalize_path()
EXAMPLES = (
r"C:\Users\Yam\python.jpg",
r"C:/Users/Yam/python.jpg",
r"C:",
r"C:\\",
r"C:/",
r"C:\Users/",
r"D:/Users/",
r"C:/Users",
)
for example in EXAMPLES:
path = Path(example)
print(path.info_message())
print()
|
week07/1_Classes.ipynb
|
PythonFreeCourse/Notebooks
|
mit
|
<span style="text-align: right; direction: rtl; float: right; clear: both;">תרגילים</span>
<span style="text-align: right; direction: rtl; float: right; clear: both;">סקרנות</span>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
מחלקת המוצר בצ'יקצ'וק החליטה להוסיף פיצ'ר שמאפשר למשתמשים ליצור סקרים, וכרגיל כל העבודה נופלת עליכם.<br>
כתבו מחלקה בשם <var>Poll</var> שמייצגת סקר.<br>
פעולת האתחול של המחלקה תקבל כפרמטר את שאלת הסקר, וכפרמטר נוסף iterable עם כל אפשרויות ההצבעה לסקר.<br>
כל אפשרות הצבעה בסקר מיוצגת על ידי מחרוזת.<br>
המחלקה תכיל את הפעולות הבאות:
</p>
<ol style="text-align: right; direction: rtl; float: right; clear: both;">
<li><var>vote</var> שמקבלת כפרמטר אפשרות הצבעה לסקר ומגדילה את מספר ההצבעות בו ב־1.</li>
<li><var>add_option</var>, שמקבלת כפרמטר אפשרות הצבעה לסקר ומוסיפה אותה.</li>
<li><var>remove_option</var> שמקבלת כפרמטר אפשרות הצבעה לסקר ומוחקת אותה.</li>
<li><var>get_votes</var> המחזירה את כל האפשרויות כרשימה של tuple, המסודרים לפי כמות ההצבעות.<br>
בכל tuple התא הראשון יהיה שם האפשרות בסקר, והתא השני יהיה מספר ההצבעות.</li>
<li><var>get_winner</var> המחזירה את שם האפשרות שקיבלה את מרב ההצבעות.</li>
</ol>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
במקרה של תיקו, החזירו מ־<var>get_winner</var> את אחת האפשרויות המובילות.<br>
החזירו מהפעולות <var>vote</var>, <var>add_option</var> ו־<var>remove_option</var> את הערך <samp>True</samp> אם הפעולה עבדה כמצופה.<br>
במקרה של הצבעה לאפשרות שאינה קיימת, מחיקת אפשרות שאינה קיימת או הוספת אפשרות שכבר קיימת, החזירו <samp>False</samp>.<br>
</p>
<p style="text-align: right; direction: rtl; float: right; clear: both;">
ודאו שהקוד הבא מדפיס רק <samp>True</samp> עבור התוכנית שכתבתם:
</p>
|
def cast_multiple_votes(poll, votes):
for vote in votes:
poll.vote(vote)
bridge_question = Poll('What is your favourite colour?', ['Blue', 'Yellow'])
cast_multiple_votes(bridge_question, ['Blue', 'Blue', 'Yellow'])
print(bridge_question.get_winner() == 'Blue')
cast_multiple_votes(bridge_question, ['Yellow', 'Yellow'])
print(bridge_question.get_winner() == 'Yellow')
print(bridge_question.get_votes() == [('Yellow', 3), ('Blue', 2)])
bridge_question.remove_option('Yellow')
print(bridge_question.get_winner() == 'Blue')
print(bridge_question.get_votes() == [('Blue', 2)])
bridge_question.add_option('Yellow')
print(bridge_question.get_votes() == [('Blue', 2), ('Yellow', 0)])
print(not bridge_question.add_option('Blue'))
print(bridge_question.get_votes() == [('Blue', 2), ('Yellow', 0)])
|
week07/1_Classes.ipynb
|
PythonFreeCourse/Notebooks
|
mit
|
The command %matplotlib inline is not a Python command, but an IPython command. When using the console, or the notebook, it makes the plots appear inline. You do not want to use this in a plain Python code.
|
from math import sin, pi
x = []
y = []
for i in range(201):
x.append(0.01*i)
y.append(sin(pi*x[-1])**2)
pyplot.plot(x, y)
pyplot.show()
|
04-basic-plotting.ipynb
|
jamesmarva/maths-with-python
|
mit
|
We have defined two sequences - in this case lists, but tuples would also work. One contains the $x$-axis coordinates, the other the data points to appear on the $y$-axis. A basic plot is produced using the plot command of pyplot. However, this plot will not automatically appear on the screen, as after plotting the data you may wish to add additional information. Nothing will actually happen until you either save the figure to a file (using pyplot.savefig(<filename>)) or explicitly ask for it to be displayed (with the show command). When the plot is displayed the program will typically pause until you dismiss the plot.
This plotting interface is straightforward, but the results are not particularly nice. The following commands illustrate some of the ways of improving the plot:
|
from math import sin, pi
x = []
y = []
for i in range(201):
x.append(0.01*i)
y.append(sin(pi*x[-1])**2)
pyplot.plot(x, y, marker='+', markersize=8, linestyle=':',
linewidth=3, color='b', label=r'$\sin^2(\pi x)$')
pyplot.legend(loc='lower right')
pyplot.xlabel(r'$x$')
pyplot.ylabel(r'$y$')
pyplot.title('A basic plot')
pyplot.show()
|
04-basic-plotting.ipynb
|
jamesmarva/maths-with-python
|
mit
|
Whilst most of the commands are self-explanatory, a note should be made of the strings line r'$x$'. These strings are in LaTeX format, which is the standard typesetting method for professional-level mathematics. The $ symbols surround mathematics. The r before the definition of the string is Python notation, not LaTeX. It says that the following string will be "raw": that backslash characters should be left alone. Then, special LaTeX commands have a backslash in front of them: here we use \pi and \sin. Most basic symbols can be easily guess (eg \theta or \int), but there are useful lists of symbols, and a reverse search site available. We can also use ^ to denote superscripts (used here), _ to denote subscripts, and use {} to group terms.
By combining these basic commands with other plotting types (semilogx and loglog, for example), most simple plots can be produced quickly.
Here are some more examples:
|
from math import sin, pi, exp, log
x = []
y1 = []
y2 = []
for i in range(201):
x.append(1.0+0.01*i)
y1.append(exp(sin(pi*x[-1])))
y2.append(log(pi+x[-1]*sin(x[-1])))
pyplot.loglog(x, y1, linestyle='--', linewidth=4,
color='k', label=r'$y_1=e^{\sin(\pi x)}$')
pyplot.loglog(x, y2, linestyle='-.', linewidth=4,
color='r', label=r'$y_2=\log(\pi+x\sin(x))$')
pyplot.legend(loc='lower right')
pyplot.xlabel(r'$x$')
pyplot.ylabel(r'$y$')
pyplot.title('A basic logarithmic plot')
pyplot.show()
from math import sin, pi, exp, log
x = []
y1 = []
y2 = []
for i in range(201):
x.append(1.0+0.01*i)
y1.append(exp(sin(pi*x[-1])))
y2.append(log(pi+x[-1]*sin(x[-1])))
pyplot.semilogy(x, y1, linestyle='None', marker='o',
color='g', label=r'$y_1=e^{\sin(\pi x)}$')
pyplot.semilogy(x, y2, linestyle='None', marker='^',
color='r', label=r'$y_2=\log(\pi+x\sin(x))$')
pyplot.legend(loc='lower right')
pyplot.xlabel(r'$x$')
pyplot.ylabel(r'$y$')
pyplot.title('A different logarithmic plot')
pyplot.show()
|
04-basic-plotting.ipynb
|
jamesmarva/maths-with-python
|
mit
|
File browser
|
Image('images/lego-filebrowser.png', width='80%')
|
12-JupyterLab.ipynb
|
ellisonbg/talk-2015
|
mit
|
Terminal
|
Image('images/lego-terminal.png', width='80%')
|
12-JupyterLab.ipynb
|
ellisonbg/talk-2015
|
mit
|
Text editor (a place to type code)
|
Image('images/lego-texteditor.png', width='80%')
|
12-JupyterLab.ipynb
|
ellisonbg/talk-2015
|
mit
|
Output
|
Image('images/lego-output.png', width='80%')
|
12-JupyterLab.ipynb
|
ellisonbg/talk-2015
|
mit
|
사전 제작 Estimator
<table class="tfo-notebook-buttons" align="left">
<td><a target="_blank" href="https://www.tensorflow.org/tutorials/estimator/premade"><img src="https://www.tensorflow.org/images/tf_logo_32px.png">TensorFlow.org에서 보기</a></td>
<td><a target="_blank" href="https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/tutorials/estimator/premade.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png">Google Colab에서 실행하기</a></td>
<td><a target="_blank" href="https://github.com/tensorflow/docs/blob/master/site/en/tutorials/estimator/premade.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png">GitHub에서소스 보기</a></td>
<td><a href="https://storage.googleapis.com/tensorflow_docs/docs/site/en/tutorials/estimator/premade.ipynb"><img src="https://www.tensorflow.org/images/download_logo_32px.png">노트북 다운로드하기</a></td>
</table>
이 튜토리얼에서는 Estimator를 사용하여 TensorFlow에서 Iris 분류 문제를 해결하는 방법을 보여줍니다. Estimator는 완전한 모델을 TensorFlow에서 높은 수준으로 표현한 것이며, 간편한 크기 조정과 비동기식 훈련에 목적을 두고 설계되었습니다. 자세한 내용은 Estimator를 참조하세요.
TensorFlow 2.0에서 Keras API는 이러한 작업을 상당 부분 동일하게 수행할 수 있으며 배우기 쉬운 API로 여겨집니다. 새로 시작하는 경우 Keras로 시작하는 것이 좋습니다. TensorFlow 2.0에서 사용 가능한 고급 API에 대한 자세한 정보는 Keras에 표준화를 참조하세요.
시작을 위한 준비
시작하려면 먼저 TensorFlow와 필요한 여러 라이브러리를 가져옵니다.
|
import tensorflow as tf
import pandas as pd
|
site/ko/tutorials/estimator/premade.ipynb
|
tensorflow/docs-l10n
|
apache-2.0
|
데이터세트
이 문서의 샘플 프로그램은 아이리스 꽃을 꽃받침잎과 꽃잎의 크기에 따라 세 가지 종으로 분류하는 모델을 빌드하고 테스트합니다.
Iris 데이터세트를 사용하여 모델을 훈련합니다. Iris 데이터세트에는 네 가지 특성과 하나의 레이블이 있습니다. 이 네 가지 특성은 개별 아이리스 꽃의 다음과 같은 식물 특성을 식별합니다.
꽃받침잎 길이
꽃받침잎 너비
꽃잎 길이
꽃잎 너비
이 정보를 바탕으로 데이터를 구문 분석하는 데 도움이 되는 몇 가지 상수를 정의할 수 있습니다.
|
CSV_COLUMN_NAMES = ['SepalLength', 'SepalWidth', 'PetalLength', 'PetalWidth', 'Species']
SPECIES = ['Setosa', 'Versicolor', 'Virginica']
|
site/ko/tutorials/estimator/premade.ipynb
|
tensorflow/docs-l10n
|
apache-2.0
|
그 다음, Keras 및 Pandas를 사용하여 Iris 데이터세트를 다운로드하고 구문 분석합니다. 훈련 및 테스트를 위해 별도의 데이터세트를 유지합니다.
|
train_path = tf.keras.utils.get_file(
"iris_training.csv", "https://storage.googleapis.com/download.tensorflow.org/data/iris_training.csv")
test_path = tf.keras.utils.get_file(
"iris_test.csv", "https://storage.googleapis.com/download.tensorflow.org/data/iris_test.csv")
train = pd.read_csv(train_path, names=CSV_COLUMN_NAMES, header=0)
test = pd.read_csv(test_path, names=CSV_COLUMN_NAMES, header=0)
|
site/ko/tutorials/estimator/premade.ipynb
|
tensorflow/docs-l10n
|
apache-2.0
|
데이터를 검사하여 네 개의 float 특성 열과 하나의 int32 레이블이 있는지 확인할 수 있습니다.
|
train.head()
|
site/ko/tutorials/estimator/premade.ipynb
|
tensorflow/docs-l10n
|
apache-2.0
|
각 데이터세트에 대해 예측하도록 모델을 훈련할 레이블을 분할합니다.
|
train_y = train.pop('Species')
test_y = test.pop('Species')
# The label column has now been removed from the features.
train.head()
|
site/ko/tutorials/estimator/premade.ipynb
|
tensorflow/docs-l10n
|
apache-2.0
|
Estimator를 사용한 프로그래밍 개요
이제 데이터가 설정되었으므로 TensorFlow Estimator를 사용하여 모델을 정의할 수 있습니다. Estimator는 tf.estimator.Estimator에서 파생된 임의의 클래스입니다. TensorFlow는 일반적인 ML 알고리즘을 구현하기 위해 tf.estimator(예: LinearRegressor) 모음을 제공합니다. 그 외에도 고유한 사용자 정의 Estimator를 작성할 수 있습니다. 처음 시작할 때는 사전 제작된 Estimator를 사용하는 것이 좋습니다.
사전 제작된 Estimator를 기초로 TensorFlow 프로그램을 작성하려면 다음 작업을 수행해야 합니다.
하나 이상의 입력 함수를 작성합니다.
모델의 특성 열을 정의합니다.
특성 열과 다양한 하이퍼 매개변수를 지정하여 Estimator를 인스턴스화합니다.
Estimator 객체에서 하나 이상의 메서드를 호출하여 적합한 입력 함수를 데이터 소스로 전달합니다.
이러한 작업이 Iris 분류를 위해 어떻게 구현되는지 알아보겠습니다.
입력 함수 작성하기
훈련, 평가 및 예측을 위한 데이터를 제공하려면 입력 함수를 작성해야 합니다.
입력 함수는 다음 두 요소 튜플을 출력하는 tf.data.Dataset 객체를 반환하는 함수입니다.
features -다음과 같은 Python 사전:
각 키가 특성의 이름입니다.
각 값은 해당 특성 값을 모두 포함하는 배열입니다.
label - 모든 예제의 레이블 값을 포함하는 배열입니다.
입력 함수의 형식을 보여주기 위해 여기에 간단한 구현을 나타냈습니다.
|
def input_evaluation_set():
features = {'SepalLength': np.array([6.4, 5.0]),
'SepalWidth': np.array([2.8, 2.3]),
'PetalLength': np.array([5.6, 3.3]),
'PetalWidth': np.array([2.2, 1.0])}
labels = np.array([2, 1])
return features, labels
|
site/ko/tutorials/estimator/premade.ipynb
|
tensorflow/docs-l10n
|
apache-2.0
|
입력 함수에서 원하는 대로 features 사전 및 label 목록이 생성되도록 할 수 있습니다. 그러나 모든 종류의 데이터를 구문 분석할 수 있는 TensorFlow의 Dataset API를 사용하는 것이 좋습니다.
Dataset API는 많은 일반적인 경우를 자동으로 처리할 수 있습니다. 예를 들어, Dataset API를 사용하면 대규모 파일 모음에서 레코드를 병렬로 쉽게 읽고 이를 단일 스트림으로 결합할 수 있습니다.
이 예제에서는 작업을 단순화하기 위해 pandas 데이터를 로드하고 이 인메모리 데이터에서 입력 파이프라인을 빌드합니다.
|
def input_fn(features, labels, training=True, batch_size=256):
"""An input function for training or evaluating"""
# Convert the inputs to a Dataset.
dataset = tf.data.Dataset.from_tensor_slices((dict(features), labels))
# Shuffle and repeat if you are in training mode.
if training:
dataset = dataset.shuffle(1000).repeat()
return dataset.batch(batch_size)
|
site/ko/tutorials/estimator/premade.ipynb
|
tensorflow/docs-l10n
|
apache-2.0
|
특성 열 정의하기
특성 열은 모델이 특성 사전의 원시 입력 데이터를 사용하는 방식을 설명하는 객체입니다. Estimator 모델을 빌드할 때는 모델에서 사용할 각 특성을 설명하는 특성 열 목록을 전달합니다. tf.feature_column 모듈은 모델에 데이터를 나타내기 위한 많은 옵션을 제공합니다.
Iris의 경우 4개의 원시 특성은 숫자 값이므로, 네 개의 특성 각각을 32-bit 부동 소수점 값으로 나타내도록 Estimator 모델에 알려주는 특성 열 목록을 빌드합니다. 따라서 특성 열을 작성하는 코드는 다음과 같습니다.
|
# Feature columns describe how to use the input.
my_feature_columns = []
for key in train.keys():
my_feature_columns.append(tf.feature_column.numeric_column(key=key))
|
site/ko/tutorials/estimator/premade.ipynb
|
tensorflow/docs-l10n
|
apache-2.0
|
특성 열은 여기에 표시된 것보다 훨씬 정교할 수 있습니다. 이 가이드에서 특성 열에 대한 자세한 내용을 읽을 수 있습니다.
모델이 원시 특성을 나타내도록 할 방식에 대한 설명이 준비되었으므로 Estimator를 빌드할 수 있습니다.
Estimator 인스턴스화하기
Iris 문제는 고전적인 분류 문제입니다. 다행히도 TensorFlow는 다음을 포함하여 여러 가지 사전 제작된 분류자 Estimator를 제공합니다.
다중 클래스 분류를 수행하는 심층 모델을 위한 tf.estimator.DNNClassifier
넓고 깊은 모델을 위한 tf.estimator.DNNLinearCombinedClassifier
선형 모델에 기초한 분류자를 위한 tf.estimator.LinearClassifier
Iris 문제의 경우 tf.estimator.DNNClassifier가 최선의 선택인 것으로 여겨집니다. 이 Estimator를 인스턴스화하는 방법은 다음과 같습니다.
|
# Build a DNN with 2 hidden layers with 30 and 10 hidden nodes each.
classifier = tf.estimator.DNNClassifier(
feature_columns=my_feature_columns,
# Two hidden layers of 30 and 10 nodes respectively.
hidden_units=[30, 10],
# The model must choose between 3 classes.
n_classes=3)
|
site/ko/tutorials/estimator/premade.ipynb
|
tensorflow/docs-l10n
|
apache-2.0
|
훈련, 평가 및 예측하기
이제 Estimator 객체가 준비되었으므로 메서드를 호출하여 다음을 수행할 수 있습니다.
모델을 훈련합니다.
훈련한 모델을 평가합니다.
훈련한 모델을 사용하여 예측을 수행합니다.
모델 훈련하기
다음과 같이 Estimator의 train 메서드를 호출하여 모델을 훈련합니다.
|
# Train the Model.
classifier.train(
input_fn=lambda: input_fn(train, train_y, training=True),
steps=5000)
|
site/ko/tutorials/estimator/premade.ipynb
|
tensorflow/docs-l10n
|
apache-2.0
|
Estimator가 예상한 대로 인수를 사용하지 않는 입력 함수를 제공하면서 인수를 포착하기 위해 lambda에서 input_fn 호출을 래핑합니다. steps 인수는 여러 훈련 단계를 거친 후에 훈련을 중지하도록 메서드에 지시합니다.
훈련한 모델 평가하기
모델을 훈련했으므로 성능에 대한 통계를 얻을 수 있습니다. 다음 코드 블록은 테스트 데이터에서 훈련한 모델의 정확도를 평가합니다.
|
eval_result = classifier.evaluate(
input_fn=lambda: input_fn(test, test_y, training=False))
print('\nTest set accuracy: {accuracy:0.3f}\n'.format(**eval_result))
|
site/ko/tutorials/estimator/premade.ipynb
|
tensorflow/docs-l10n
|
apache-2.0
|
train 메서드에 대한 호출과 달리 평가할 steps 인수를 전달하지 않았습니다. eval에 대한 input_fn은 단 하나의 데이터 epoch만 생성합니다.
eval_result 사전에는 average_loss(샘플당 평균 손실), loss(미니 배치당 평균 손실) 및 Estimator의 global_step 값(받은 훈련 반복 횟수)도 포함됩니다.
훈련한 모델에서 예측(추론)하기
우수한 평가 결과를 생성하는 훈련한 모델을 만들었습니다. 이제 훈련한 모델을 사용하여 레이블이 지정되지 않은 일부 측정을 바탕으로 아이리스 꽃의 종을 예측할 수 있습니다. 훈련 및 평가와 마찬가지로 단일 함수 호출을 사용하여 예측합니다.
|
# Generate predictions from the model
expected = ['Setosa', 'Versicolor', 'Virginica']
predict_x = {
'SepalLength': [5.1, 5.9, 6.9],
'SepalWidth': [3.3, 3.0, 3.1],
'PetalLength': [1.7, 4.2, 5.4],
'PetalWidth': [0.5, 1.5, 2.1],
}
def input_fn(features, batch_size=256):
"""An input function for prediction."""
# Convert the inputs to a Dataset without labels.
return tf.data.Dataset.from_tensor_slices(dict(features)).batch(batch_size)
predictions = classifier.predict(
input_fn=lambda: input_fn(predict_x))
|
site/ko/tutorials/estimator/premade.ipynb
|
tensorflow/docs-l10n
|
apache-2.0
|
predict 메서드는 Python iterable을 반환하여 각 예제에 대한 예측 결과 사전을 생성합니다. 다음 코드는 몇 가지 예측과 해당 확률을 출력합니다.
|
for pred_dict, expec in zip(predictions, expected):
class_id = pred_dict['class_ids'][0]
probability = pred_dict['probabilities'][class_id]
print('Prediction is "{}" ({:.1f}%), expected "{}"'.format(
SPECIES[class_id], 100 * probability, expec))
|
site/ko/tutorials/estimator/premade.ipynb
|
tensorflow/docs-l10n
|
apache-2.0
|
Generating a click example
Lets start by degradating some audio files with some clicks of different amplitudes
|
fs = 44100.
audio_dir = '../../audio/'
audio = es.MonoLoader(filename='{}/{}'.format(audio_dir,
'recorded/vignesh.wav'),
sampleRate=fs)()
originalLen = len(audio)
jumpLocation1 = int(originalLen / 4.)
jumpLocation2 = int(originalLen / 2.)
jumpLocation3 = int(originalLen * 3 / 4.)
audio[jumpLocation1] += .5
audio[jumpLocation2] += .15
audio[jumpLocation3] += .05
groundTruth = esarr([jumpLocation1, jumpLocation2, jumpLocation3]) / fs
for point in groundTruth:
l1 = plt.axvline(point, color='g', alpha=.5)
times = np.linspace(0, len(audio) / fs, len(audio))
plt.plot(times, audio)
l1.set_label('Click locations')
plt.legend()
plt.title('Signal with artificial clicks of different amplitudes')
|
src/examples/tutorial/example_clickdetector.ipynb
|
carthach/essentia
|
agpl-3.0
|
Lets listen to the clip to have an idea on how audible the clips are
|
Audio(audio, rate=fs)
|
src/examples/tutorial/example_clickdetector.ipynb
|
carthach/essentia
|
agpl-3.0
|
The algorithm
This algorithm outputs the starts and ends timestapms of the clicks. The following plots show how the algorithm performs in the previous examples
|
starts, ends = compute(audio)
fig, ax = plt.subplots(len(groundTruth))
plt.subplots_adjust(hspace=.4)
for idx, point in enumerate(groundTruth):
l1 = ax[idx].axvline(starts[idx], color='r', alpha=.5)
ax[idx].axvline(ends[idx], color='r', alpha=.5)
l2 = ax[idx].axvline(point, color='g', alpha=.5)
ax[idx].plot(times, audio)
ax[idx].set_xlim([point-.001, point+.001])
ax[idx].set_title('Click located at {:.2f}s'.format(point))
fig.legend((l1, l2), ('Detected click', 'Ground truth'), 'upper right')
|
src/examples/tutorial/example_clickdetector.ipynb
|
carthach/essentia
|
agpl-3.0
|
BigQuery Data
If you have not gone through the KFP Walkthrough lab, you will need to run the following cell to create a BigQuery dataset and table containing the data required for this lab.
NOTE If you already have the covertype data in a bigquery table at <PROJECT_ID>.covertype_dataset.covertype you may skip to Understanding the pipeline design.
|
%%bash
DATASET_LOCATION=US
DATASET_ID=covertype_dataset
TABLE_ID=covertype
DATA_SOURCE=gs://workshop-datasets/covertype/small/dataset.csv
SCHEMA=Elevation:INTEGER,\
Aspect:INTEGER,\
Slope:INTEGER,\
Horizontal_Distance_To_Hydrology:INTEGER,\
Vertical_Distance_To_Hydrology:INTEGER,\
Horizontal_Distance_To_Roadways:INTEGER,\
Hillshade_9am:INTEGER,\
Hillshade_Noon:INTEGER,\
Hillshade_3pm:INTEGER,\
Horizontal_Distance_To_Fire_Points:INTEGER,\
Wilderness_Area:STRING,\
Soil_Type:STRING,\
Cover_Type:INTEGER
bq --location=$DATASET_LOCATION --project_id=$PROJECT mk --dataset $DATASET_ID
bq --project_id=$PROJECT --dataset_id=$DATASET_ID load \
--source_format=CSV \
--skip_leading_rows=1 \
--replace \
$TABLE_ID \
$DATA_SOURCE \
$SCHEMA
|
notebooks/kubeflow_pipelines/pipelines/solutions/kfp_pipeline_vertex_automl_batch_predictions.ipynb
|
GoogleCloudPlatform/asl-ml-immersion
|
apache-2.0
|
Understanding the pipeline design
The workflow implemented by the pipeline is defined using a Python based Domain Specific Language (DSL). The pipeline's DSL is in the pipeline_vertex/pipeline_vertex_automl_batch_preds.py file that we will generate below.
The pipeline's DSL has been designed to avoid hardcoding any environment specific settings like file paths or connection strings. These settings are provided to the pipeline code through a set of environment variables.
Building and deploying the pipeline
Let us write the pipeline to disk:
|
%%writefile ./pipeline_vertex/pipeline_vertex_automl_batch_preds.py
"""Kubeflow Covertype Pipeline."""
import os
from google_cloud_pipeline_components.aiplatform import (
AutoMLTabularTrainingJobRunOp,
TabularDatasetCreateOp,
ModelBatchPredictOp
)
from kfp.v2 import dsl
PIPELINE_ROOT = os.getenv("PIPELINE_ROOT")
PROJECT = os.getenv("PROJECT")
DATASET_SOURCE = os.getenv("DATASET_SOURCE")
PIPELINE_NAME = os.getenv("PIPELINE_NAME", "covertype")
DISPLAY_NAME = os.getenv("MODEL_DISPLAY_NAME", PIPELINE_NAME)
TARGET_COLUMN = os.getenv("TARGET_COLUMN", "Cover_Type")
BATCH_PREDS_SOURCE_URI = os.getenv("BATCH_PREDS_SOURCE_URI")
@dsl.pipeline(
name=f"{PIPELINE_NAME}-vertex-automl-pipeline-batch-preds",
description=f"AutoML Vertex Pipeline for {PIPELINE_NAME}",
pipeline_root=PIPELINE_ROOT,
)
def create_pipeline():
dataset_create_task = TabularDatasetCreateOp(
display_name=DISPLAY_NAME,
bq_source=DATASET_SOURCE,
project=PROJECT,
)
automl_training_task = AutoMLTabularTrainingJobRunOp(
project=PROJECT,
display_name=DISPLAY_NAME,
optimization_prediction_type="classification",
dataset=dataset_create_task.outputs["dataset"],
target_column=TARGET_COLUMN,
)
batch_predict_op = ModelBatchPredictOp(
project=PROJECT,
job_display_name="batch_predict_job",
model=automl_training_task.outputs["model"],
bigquery_source_input_uri=BATCH_PREDS_SOURCE_URI,
instances_format="bigquery",
predictions_format="bigquery",
bigquery_destination_output_uri=f'bq://{PROJECT}',
)
|
notebooks/kubeflow_pipelines/pipelines/solutions/kfp_pipeline_vertex_automl_batch_predictions.ipynb
|
GoogleCloudPlatform/asl-ml-immersion
|
apache-2.0
|
Understanding the ModelBatchPredictOp
When working with an AutoML Tabular model, the ModelBatchPredictOp can take the following inputs:
* model: The model resource to serve batch predictions with
* bigquery_source_uri: A URI to a BigQuery table containing examples to serve batch predictions on in the format bq://PROJECT.DATASET.TABLE
* instances_format: "bigquery" to serve batch predictions on BigQuery data.
* predictions_format: "bigquery" to store the results of the batch prediction in BigQuery.
* bigquery_destination_output_uri: In the format bq://PROJECT_ID. This is the project that the results of the batch prediction will be stored. The ModelBatchPredictOp will create a dataset in this project.
Upon completion of the ModelBatchPredictOp you will see a new BigQuery dataset with name prediction_<model-display-name>_<job-create-time>. Inside this dataset you will see a predictions table, containing the batch prediction examples and predicted labels. If there were any errors in the batch prediction, you will also see an errors table. The errors table contains rows for which the prediction has failed.
Create BigQuery table with data for batch predictions
Before we compile and run the pipeline, let's create a BigQuery table with data we want to serve batch predictions on. To simulate "new" data we will simply query the existing table for all columns except the label and create a table called newdata. The URI to this table will be the bigquery_source_input_uri input to the ModelBatchPredictOp.
|
%%bigquery
CREATE OR REPLACE TABLE covertype_dataset.newdata AS
SELECT * EXCEPT(Cover_Type)
FROM covertype_dataset.covertype
LIMIT 10000
|
notebooks/kubeflow_pipelines/pipelines/solutions/kfp_pipeline_vertex_automl_batch_predictions.ipynb
|
GoogleCloudPlatform/asl-ml-immersion
|
apache-2.0
|
Compile the pipeline
Let's start by defining the environment variables that will be passed to the pipeline compiler:
|
ARTIFACT_STORE = f"gs://{PROJECT}-kfp-artifact-store"
PIPELINE_ROOT = f"{ARTIFACT_STORE}/pipeline"
DATASET_SOURCE = f"bq://{PROJECT}.covertype_dataset.covertype"
BATCH_PREDS_SOURCE_URI = f"bq://{PROJECT}.covertype_dataset.newdata"
%env PIPELINE_ROOT={PIPELINE_ROOT}
%env PROJECT={PROJECT}
%env REGION={REGION}
%env DATASET_SOURCE={DATASET_SOURCE}
%env BATCH_PREDS_SOURCE_URI={BATCH_PREDS_SOURCE_URI}
|
notebooks/kubeflow_pipelines/pipelines/solutions/kfp_pipeline_vertex_automl_batch_predictions.ipynb
|
GoogleCloudPlatform/asl-ml-immersion
|
apache-2.0
|
Let us make sure that the ARTIFACT_STORE has been created, and let us create it if not:
|
!gsutil ls | grep ^{ARTIFACT_STORE}/$ || gsutil mb -l {REGION} {ARTIFACT_STORE}
|
notebooks/kubeflow_pipelines/pipelines/solutions/kfp_pipeline_vertex_automl_batch_predictions.ipynb
|
GoogleCloudPlatform/asl-ml-immersion
|
apache-2.0
|
Use the CLI compiler to compile the pipeline
We compile the pipeline from the Python file we generated into a JSON description using the following command:
|
PIPELINE_JSON = "covertype_automl_vertex_pipeline_batch_preds.json"
!dsl-compile-v2 --py pipeline_vertex/pipeline_vertex_automl_batch_preds.py --output $PIPELINE_JSON
|
notebooks/kubeflow_pipelines/pipelines/solutions/kfp_pipeline_vertex_automl_batch_predictions.ipynb
|
GoogleCloudPlatform/asl-ml-immersion
|
apache-2.0
|
Note: You can also use the Python SDK to compile the pipeline:
```python
from kfp.v2 import compiler
compiler.Compiler().compile(
pipeline_func=create_pipeline,
package_path=PIPELINE_JSON,
)
```
The result is the pipeline file.
|
!head {PIPELINE_JSON}
|
notebooks/kubeflow_pipelines/pipelines/solutions/kfp_pipeline_vertex_automl_batch_predictions.ipynb
|
GoogleCloudPlatform/asl-ml-immersion
|
apache-2.0
|
Deploy the pipeline package
|
aiplatform.init(project=PROJECT, location=REGION)
pipeline = aiplatform.PipelineJob(
display_name="automl_covertype_kfp_pipeline_batch_predictions",
template_path=PIPELINE_JSON,
enable_caching=True,
)
pipeline.run()
|
notebooks/kubeflow_pipelines/pipelines/solutions/kfp_pipeline_vertex_automl_batch_predictions.ipynb
|
GoogleCloudPlatform/asl-ml-immersion
|
apache-2.0
|
Import raw data
The user needs to specify the directories containing the data of interest. Each sample type should have a key which corresponds to the directory path. Additionally, each object should have a list that includes the channels of interest.
|
# --------------------------------
# -------- User input ------------
# --------------------------------
data = {
# Specify sample type key
'wt': {
# Specify path to data directory
'path': 'path\to\data\directory\sample1',
# Specify which channels are in the directory and are of interest
'channels': ['AT','ZRF']
},
'stype2': {
'path': 'path\to\data\directory\sample2',
'channels': ['AT','ZRF']
}
}
|
experiments/templates/TEMP-landmarks.ipynb
|
msschwartz21/craniumPy
|
gpl-3.0
|
We'll generate a list of pairs of stypes and channels for ease of use.
|
data_pairs = []
for s in data.keys():
for c in data[s]['channels']:
data_pairs.append((s,c))
|
experiments/templates/TEMP-landmarks.ipynb
|
msschwartz21/craniumPy
|
gpl-3.0
|
We can now read in all datafiles specified by the data dictionary above.
|
D = {}
for s in data.keys():
D[s] = {}
for c in data[s]['channels']:
D[s][c] = ds.read_psi_to_dict(data[s]['path'],c)
|
experiments/templates/TEMP-landmarks.ipynb
|
msschwartz21/craniumPy
|
gpl-3.0
|
Calculate landmark bins
|
# --------------------------------
# -------- User input ------------
# --------------------------------
# Pick an integer value for bin number based on results above
anum = 25
# Specify the percentiles which will be used to calculate landmarks
percbins = [50]
|
experiments/templates/TEMP-landmarks.ipynb
|
msschwartz21/craniumPy
|
gpl-3.0
|
Calculate landmark bins based on user input parameters and the previously specified control sample.
|
lm = ds.landmarks(percbins=percbins, rnull=np.nan)
lm.calc_bins(D[s_ctrl][c_ctrl], anum, theta_step)
print('Alpha bins')
print(lm.acbins)
print('Theta bins')
print(lm.tbins)
|
experiments/templates/TEMP-landmarks.ipynb
|
msschwartz21/craniumPy
|
gpl-3.0
|
Calculate landmarks
|
lmdf = pd.DataFrame()
# Loop through each pair of stype and channels
for s,c in tqdm.tqdm(data_pairs):
print(s,c)
# Calculate landmarks for each sample with this data pair
for k,df in tqdm.tqdm(D[s][c].items()):
lmdf = lm.calc_perc(df, k, '-'.join([s,c]), lmdf)
# Set timestamp for saving data
tstamp = time.strftime("%m-%d-%H-%M",time.localtime())
# Save completed landmarks to a csv file
lmdf.to_csv(tstamp+'_landmarks.csv')
# Save landmark bins to json file
bins = {
'acbins':list(lm.acbins),
'tbins':list(lm.tbins)
}
with open(tstamp+'_landmarks_bins.json', 'w') as outfile:
json.dump(bins, outfile)
|
experiments/templates/TEMP-landmarks.ipynb
|
msschwartz21/craniumPy
|
gpl-3.0
|
EEG forward operator with a template MRI
This tutorial explains how to compute the forward operator from EEG data
using the standard template MRI subject fsaverage.
.. caution:: Source reconstruction without an individual T1 MRI from the
subject will be less accurate. Do not over interpret
activity locations which can be off by multiple centimeters.
Adult template MRI (fsaverage)
First we show how fsaverage can be used as a surrogate subject.
|
# Authors: Alexandre Gramfort <[email protected]>
# Joan Massich <[email protected]>
# Eric Larson <[email protected]>
#
# License: BSD-3-Clause
import os.path as op
import numpy as np
import mne
from mne.datasets import eegbci
from mne.datasets import fetch_fsaverage
# Download fsaverage files
fs_dir = fetch_fsaverage(verbose=True)
subjects_dir = op.dirname(fs_dir)
# The files live in:
subject = 'fsaverage'
trans = 'fsaverage' # MNE has a built-in fsaverage transformation
src = op.join(fs_dir, 'bem', 'fsaverage-ico-5-src.fif')
bem = op.join(fs_dir, 'bem', 'fsaverage-5120-5120-5120-bem-sol.fif')
|
dev/_downloads/1242d47b65d952f9f80cf19fb9e5d76e/35_eeg_no_mri.ipynb
|
mne-tools/mne-tools.github.io
|
bsd-3-clause
|
Load the data
We use here EEG data from the BCI dataset.
<div class="alert alert-info"><h4>Note</h4><p>See `plot_montage` to view all the standard EEG montages
available in MNE-Python.</p></div>
|
raw_fname, = eegbci.load_data(subject=1, runs=[6])
raw = mne.io.read_raw_edf(raw_fname, preload=True)
# Clean channel names to be able to use a standard 1005 montage
new_names = dict(
(ch_name,
ch_name.rstrip('.').upper().replace('Z', 'z').replace('FP', 'Fp'))
for ch_name in raw.ch_names)
raw.rename_channels(new_names)
# Read and set the EEG electrode locations, which are already in fsaverage's
# space (MNI space) for standard_1020:
montage = mne.channels.make_standard_montage('standard_1005')
raw.set_montage(montage)
raw.set_eeg_reference(projection=True) # needed for inverse modeling
# Check that the locations of EEG electrodes is correct with respect to MRI
mne.viz.plot_alignment(
raw.info, src=src, eeg=['original', 'projected'], trans=trans,
show_axes=True, mri_fiducials=True, dig='fiducials')
|
dev/_downloads/1242d47b65d952f9f80cf19fb9e5d76e/35_eeg_no_mri.ipynb
|
mne-tools/mne-tools.github.io
|
bsd-3-clause
|
Setup source space and compute forward
|
fwd = mne.make_forward_solution(raw.info, trans=trans, src=src,
bem=bem, eeg=True, mindist=5.0, n_jobs=None)
print(fwd)
|
dev/_downloads/1242d47b65d952f9f80cf19fb9e5d76e/35_eeg_no_mri.ipynb
|
mne-tools/mne-tools.github.io
|
bsd-3-clause
|
From here on, standard inverse imaging methods can be used!
Infant MRI surrogates
We don't have a sample infant dataset for MNE, so let's fake a 10-20 one:
|
ch_names = \
'Fz Cz Pz Oz Fp1 Fp2 F3 F4 F7 F8 C3 C4 T7 T8 P3 P4 P7 P8 O1 O2'.split()
data = np.random.RandomState(0).randn(len(ch_names), 1000)
info = mne.create_info(ch_names, 1000., 'eeg')
raw = mne.io.RawArray(data, info)
|
dev/_downloads/1242d47b65d952f9f80cf19fb9e5d76e/35_eeg_no_mri.ipynb
|
mne-tools/mne-tools.github.io
|
bsd-3-clause
|
Get an infant MRI template
To use an infant head model for M/EEG data, you can use
:func:mne.datasets.fetch_infant_template to download an infant template:
|
subject = mne.datasets.fetch_infant_template('6mo', subjects_dir, verbose=True)
|
dev/_downloads/1242d47b65d952f9f80cf19fb9e5d76e/35_eeg_no_mri.ipynb
|
mne-tools/mne-tools.github.io
|
bsd-3-clause
|
It comes with several helpful built-in files, including a 10-20 montage
in the MRI coordinate frame, which can be used to compute the
MRI<->head transform trans:
|
fname_1020 = op.join(subjects_dir, subject, 'montages', '10-20-montage.fif')
mon = mne.channels.read_dig_fif(fname_1020)
mon.rename_channels(
{f'EEG{ii:03d}': ch_name for ii, ch_name in enumerate(ch_names, 1)})
trans = mne.channels.compute_native_head_t(mon)
raw.set_montage(mon)
print(trans)
|
dev/_downloads/1242d47b65d952f9f80cf19fb9e5d76e/35_eeg_no_mri.ipynb
|
mne-tools/mne-tools.github.io
|
bsd-3-clause
|
There are also BEM and source spaces:
|
bem_dir = op.join(subjects_dir, subject, 'bem')
fname_src = op.join(bem_dir, f'{subject}-oct-6-src.fif')
src = mne.read_source_spaces(fname_src)
print(src)
fname_bem = op.join(bem_dir, f'{subject}-5120-5120-5120-bem-sol.fif')
bem = mne.read_bem_solution(fname_bem)
|
dev/_downloads/1242d47b65d952f9f80cf19fb9e5d76e/35_eeg_no_mri.ipynb
|
mne-tools/mne-tools.github.io
|
bsd-3-clause
|
You can ensure everything is as expected by plotting the result:
|
fig = mne.viz.plot_alignment(
raw.info, subject=subject, subjects_dir=subjects_dir, trans=trans,
src=src, bem=bem, coord_frame='mri', mri_fiducials=True, show_axes=True,
surfaces=('white', 'outer_skin', 'inner_skull', 'outer_skull'))
mne.viz.set_3d_view(fig, 25, 70, focalpoint=[0, -0.005, 0.01])
|
dev/_downloads/1242d47b65d952f9f80cf19fb9e5d76e/35_eeg_no_mri.ipynb
|
mne-tools/mne-tools.github.io
|
bsd-3-clause
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.