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