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 minimization... | # 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, ... | 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)
s... | 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... | 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):
re... | 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 ca... | 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, _ =... | 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> ืชืงืื ืืฉืชืืฉ ืืชืื... | 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']... | 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... | 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... | 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>
ืืฉืชืืฉื ื ื... | 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="t... | 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;"... | 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-a... | 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... | 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_str... | 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: r... | 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... | 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;">
ื ืขืชืืง ืืช ... | 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_... | 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>... | 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>
ืืื ืคืขืืืืช ืขื ืฉื ืืืืื, ืฉืื ื ืืืืจ ืืืชื ืืืืืง... | 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;">
ืืืืื ืฉืคืื ืงืฆืืืช ืืืืคืกื <v... | 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
... | 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>
ืืคืขืื... | 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):
sel... | 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; directio... | 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... | 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>... | 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_na... | 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 ื ืื... | 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;">
ืืืจื ืฉืงืจืืื ืืืืืงื <va... | 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>
ืื ืฆืจืฃ ืืช ืืืืคืข... | 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-a... | 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... | 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... | 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):
... | 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>, ื ืืื ืฉืื... | 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>
ืืืื ืืื ืืขืืจื ืื ื ืืืจืื ืืื ืืืชืจ ืืช ืืชืืื ืืช ืฉืื ื ืืืืืฆื ืืฉืืืืช ื... | 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 = ""
... | 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;">
ืืืืงืช ืืืืฆืจ ืืฆ'ืืงืฆ'ืืง ืืืืืื ืืืืกืืฃ ืคืืฆ'ืจ ืฉืืืคืฉืจ ืืืฉืชืืฉืื ืืืฆ... | 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... | 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 dat... | 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.... | 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.... | 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='... | 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/tens... | 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=CS... | 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๋ฅผ ๊ธฐ์ด๋ก Ten... | 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 ... | 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.DNNLine... | # 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 predi... | 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... | 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]... | 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 ... | %%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:INTEG... | 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 env... | %%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("PIPELIN... | 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://PROJEC... | %%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 DATA... | 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 interes... | 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 d... | 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
act... | # Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr>
# Joan Massich <mailsik@gmail.com>
# Eric Larson <larson.eric.d@gmail.com>
#
# 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 fsa... | 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_chann... | 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.