markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
Get movie titles
movie_titles = pd.read_csv("Movie_Id_Titles") movie_titles.head()
Machine Learning/Recommender Systems/Recommender Systems with Python.ipynb
luizhsda10/Data-Science-Projectcs
mit
Merged dataframes
df = pd.merge(df,movie_titles,on='item_id') df.head()
Machine Learning/Recommender Systems/Recommender Systems with Python.ipynb
luizhsda10/Data-Science-Projectcs
mit
Exploratory Data Analysis
import matplotlib.pyplot as plt import seaborn as sns sns.set_style('white') %matplotlib inline
Machine Learning/Recommender Systems/Recommender Systems with Python.ipynb
luizhsda10/Data-Science-Projectcs
mit
Create a ratings dataframe with average rating and number of ratings
df.groupby('title')['rating'].mean().sort_values(ascending=False).head() df.groupby('title')['rating'].count().sort_values(ascending=False).head() ratings = pd.DataFrame(df.groupby('title')['rating'].mean()) ratings.head()
Machine Learning/Recommender Systems/Recommender Systems with Python.ipynb
luizhsda10/Data-Science-Projectcs
mit
Number of ratings column
ratings['num of ratings'] = pd.DataFrame(df.groupby('title')['rating'].count()) ratings.head()
Machine Learning/Recommender Systems/Recommender Systems with Python.ipynb
luizhsda10/Data-Science-Projectcs
mit
Data Visualization: Histogram
plt.figure(figsize=(10,4)) ratings['num of ratings'].hist(bins=70) plt.figure(figsize=(10,4)) ratings['rating'].hist(bins=70) sns.jointplot(x='rating',y='num of ratings',data=ratings,alpha=0.5)
Machine Learning/Recommender Systems/Recommender Systems with Python.ipynb
luizhsda10/Data-Science-Projectcs
mit
Recommending Similar Movies
moviemat = df.pivot_table(index='user_id',columns='title',values='rating') moviemat.head()
Machine Learning/Recommender Systems/Recommender Systems with Python.ipynb
luizhsda10/Data-Science-Projectcs
mit
Most rated movies
ratings.sort_values('num of ratings',ascending=False).head(10)
Machine Learning/Recommender Systems/Recommender Systems with Python.ipynb
luizhsda10/Data-Science-Projectcs
mit
We choose two movies: starwars, a sci-fi movie. And Liar Liar, a comedy.
ratings.head()
Machine Learning/Recommender Systems/Recommender Systems with Python.ipynb
luizhsda10/Data-Science-Projectcs
mit
Now let's grab the user ratings for those two movies:
starwars_user_ratings = moviemat['Star Wars (1977)'] liarliar_user_ratings = moviemat['Liar Liar (1997)'] starwars_user_ratings.head()
Machine Learning/Recommender Systems/Recommender Systems with Python.ipynb
luizhsda10/Data-Science-Projectcs
mit
Using corrwith() method to get correlations between two pandas series:
similar_to_starwars = moviemat.corrwith(starwars_user_ratings) similar_to_liarliar = moviemat.corrwith(liarliar_user_ratings)
Machine Learning/Recommender Systems/Recommender Systems with Python.ipynb
luizhsda10/Data-Science-Projectcs
mit
Clear data by removing NaN values and using a DataFrame instead of a series
corr_starwars = pd.DataFrame(similar_to_starwars,columns=['Correlation']) corr_starwars.dropna(inplace=True) corr_starwars.head() corr_starwars.sort_values('Correlation',ascending=False).head(10)
Machine Learning/Recommender Systems/Recommender Systems with Python.ipynb
luizhsda10/Data-Science-Projectcs
mit
Filtering out movies that have less than 100 reviews (this value was chosen based off the histogram). This is needed to get more accurate results
corr_starwars = corr_starwars.join(ratings['num of ratings']) corr_starwars.head()
Machine Learning/Recommender Systems/Recommender Systems with Python.ipynb
luizhsda10/Data-Science-Projectcs
mit
Now sort the values
corr_starwars[corr_starwars['num of ratings']>100].sort_values('Correlation',ascending=False).head()
Machine Learning/Recommender Systems/Recommender Systems with Python.ipynb
luizhsda10/Data-Science-Projectcs
mit
The same for the comedy Liar Liar:
corr_liarliar = pd.DataFrame(similar_to_liarliar,columns=['Correlation']) corr_liarliar.dropna(inplace=True) corr_liarliar = corr_liarliar.join(ratings['num of ratings']) corr_liarliar[corr_liarliar['num of ratings']>100].sort_values('Correlation',ascending=False).head()
Machine Learning/Recommender Systems/Recommender Systems with Python.ipynb
luizhsda10/Data-Science-Projectcs
mit
Note: The R code and the results in this notebook has been converted to markdown so that R is not required to build the documents. The R results in the notebook were computed using R 3.5.1 and lme4 1.1. ipython %load_ext rpy2.ipython ipython %R library(lme4) array(['lme4', 'Matrix', 'tools', 'stats', 'graphics', 'grDev...
data = sm.datasets.get_rdataset("dietox", "geepack").data md = smf.mixedlm("Weight ~ Time", data, groups=data["Pig"]) mdf = md.fit(method=["lbfgs"]) print(mdf.summary())
v0.13.2/examples/notebooks/generated/mixed_lm_example.ipynb
statsmodels/statsmodels.github.io
bsd-3-clause
Here is the same model fit using LMER in R: ipython %R print(summary(lmer("Weight ~ Time + (1 + Time | Pig)", data=dietox))) ``` Linear mixed model fit by REML ['lmerMod'] Formula: Weight ~ Time + (1 + Time | Pig) Data: dietox REML criterion at convergence: 4434.1 Scaled residuals: Min 1Q Median 3Q ...
0.294 / (19.493 * 0.416) ** 0.5 md = smf.mixedlm("Weight ~ Time", data, groups=data["Pig"], re_formula="~Time") free = sm.regression.mixed_linear_model.MixedLMParams.from_components( np.ones(2), np.eye(2) ) mdf = md.fit(free=free, method=["lbfgs"]) print(mdf.summary())
v0.13.2/examples/notebooks/generated/mixed_lm_example.ipynb
statsmodels/statsmodels.github.io
bsd-3-clause
We can further explore the random effects structure by constructing plots of the profile likelihoods. We start with the random intercept, generating a plot of the profile likelihood from 0.1 units below to 0.1 units above the MLE. Since each optimization inside the profile likelihood generates a warning (due to the ran...
import warnings with warnings.catch_warnings(): warnings.filterwarnings("ignore") likev = mdf.profile_re(0, "re", dist_low=0.1, dist_high=0.1)
v0.13.2/examples/notebooks/generated/mixed_lm_example.ipynb
statsmodels/statsmodels.github.io
bsd-3-clause
Here is a plot of the profile likelihood function. We multiply the log-likelihood difference by 2 to obtain the usual $\chi^2$ reference distribution with 1 degree of freedom.
import matplotlib.pyplot as plt plt.figure(figsize=(10, 8)) plt.plot(likev[:, 0], 2 * likev[:, 1]) plt.xlabel("Variance of random intercept", size=17) plt.ylabel("-2 times profile log likelihood", size=17)
v0.13.2/examples/notebooks/generated/mixed_lm_example.ipynb
statsmodels/statsmodels.github.io
bsd-3-clause
Here is a plot of the profile likelihood function. The profile likelihood plot shows that the MLE of the random slope variance parameter is a very small positive number, and that there is low uncertainty in this estimate.
re = mdf.cov_re.iloc[1, 1] with warnings.catch_warnings(): # Parameter is often on the boundary warnings.simplefilter("ignore", ConvergenceWarning) likev = mdf.profile_re(1, "re", dist_low=0.5 * re, dist_high=0.8 * re) plt.figure(figsize=(10, 8)) plt.plot(likev[:, 0], 2 * likev[:, 1]) plt.xlabel("Variance ...
v0.13.2/examples/notebooks/generated/mixed_lm_example.ipynb
statsmodels/statsmodels.github.io
bsd-3-clause
We create a small 2D grid where P is a tracer that we want to interpolate. In each grid cell, P has a random value between 0.1 and 1.1. We then set P[1,1] to 0, which for Parcels specifies that this is a land cell
dims = [5, 4] dx, dy = 1./dims[0], 1./dims[1] dimensions = {'lat': np.linspace(0., 1., dims[0], dtype=np.float32), 'lon': np.linspace(0., 1., dims[1], dtype=np.float32)} data = {'U': np.zeros(dims, dtype=np.float32), 'V': np.zeros(dims, dtype=np.float32), 'P': np.random.rand(dims[0], dims[...
parcels/examples/tutorial_interpolation.ipynb
OceanPARCELS/parcels
mit
We create a Particle class that can sample this field
class SampleParticle(JITParticle): p = Variable('p', dtype=np.float32) def SampleP(particle, fieldset, time): particle.p = fieldset.P[time, particle.depth, particle.lat, particle.lon]
parcels/examples/tutorial_interpolation.ipynb
OceanPARCELS/parcels
mit
Now, we perform four different interpolation on P, which we can control by setting fieldset.P.interp_method. Note that this can always be done after the FieldSet creation. We store the results of each interpolation method in an entry in the dictionary pset.
pset = {} for p_interp in ['linear', 'linear_invdist_land_tracer', 'nearest', 'cgrid_tracer']: fieldset.P.interp_method = p_interp # setting the interpolation method for fieldset.P xv, yv = np.meshgrid(np.linspace(0, 1, 8), np.linspace(0, 1, 8)) pset[p_interp] = ParticleSet(fieldset, pclass=SampleParticle...
parcels/examples/tutorial_interpolation.ipynb
OceanPARCELS/parcels
mit
And then we can show each of the four interpolation methods, by plotting the interpolated values on the Particle locations (circles) on top of the Field values (background colors)
fig, ax = plt.subplots(1, 4, figsize=(18, 5)) for i, p in enumerate(pset.keys()): data = fieldset.P.data[0, :, :] data[1, 1] = np.nan x = np.linspace(-dx/2, 1+dx/2, dims[0]+1) y = np.linspace(-dy/2, 1+dy/2, dims[1]+1) if p == 'cgrid_tracer': for lat in fieldset.P.grid.lat: ax[i]....
parcels/examples/tutorial_interpolation.ipynb
OceanPARCELS/parcels
mit
The white box is here the 'land' point where the tracer is set to zero and the crosses are the locations of the grid points. As you see, the interpolated value is always equal to the field value if the particle is exactly on the grid point (circles on crosses). For interp_method='nearest', the particle values are the ...
plt.scatter(pset['linear'].lon, pset['linear'].lat, c=pset['linear_invdist_land_tracer'].p-pset['linear'].p, edgecolors='k', s=50, cmap=cm.bwr, vmin=-0.25, vmax=0.25) plt.colorbar() plt.title("Difference between 'interp_method=linear' and 'interp_method=linear_invdist_land_tracer'") plt.show()
parcels/examples/tutorial_interpolation.ipynb
OceanPARCELS/parcels
mit
So in summary, Parcels has four different interpolation schemes for tracers: interp_method=linear: compute linear interpolation interp_method=linear_invdist_land_tracer: compute linear interpolation except near land (where field value is zero). In that case, inverse distance weighting interpolation is computed, weight...
def calc_p(t, y, x): return 10*t+x+0.2*y
parcels/examples/tutorial_interpolation.ipynb
OceanPARCELS/parcels
mit
Let's define a simple FieldSet with two timesteps, a 0.5 m/s zonal velocity and no meridional velocity.
dims = [2, 4, 5] dimensions = {'lon': np.linspace(0., 1., dims[2], dtype=np.float32), 'lat': np.linspace(0., 1., dims[1], dtype=np.float32), 'time': np.arange(dims[0], dtype=np.float32)} p = np.zeros(dims, dtype=np.float32) for i, x in enumerate(dimensions['lon']): for j, y in enumerate...
parcels/examples/tutorial_interpolation.ipynb
OceanPARCELS/parcels
mit
Now create four particles and a Sampling class so we can sample the Field P
xv, yv = np.meshgrid(np.arange(0, 1, 0.5), np.arange(0, 1, 0.5)) class SampleParticle(JITParticle): p = Variable('p', dtype=np.float32) pset = ParticleSet(fieldset, pclass=SampleParticle, lon=xv.flatten(), lat=yv.flatten())
parcels/examples/tutorial_interpolation.ipynb
OceanPARCELS/parcels
mit
The key now is that we need to create a sampling Kernel where the Field P is sampled at time+particle.dt and that we concatenate this kernel after the AdvectionRK4 Kernel
def SampleP(particle, fieldset, time): """ offset sampling by dt""" particle.p = fieldset.P[time+particle.dt, particle.depth, particle.lat, particle.lon] kernels = AdvectionRK4 + pset.Kernel(SampleP) # Note that the order of concatenation matters here!
parcels/examples/tutorial_interpolation.ipynb
OceanPARCELS/parcels
mit
We can now run these kernels on the ParticleSet
pfile = pset.ParticleFile("interpolation_offset.nc", outputdt=1) pset.execute(kernels, endtime=1, dt=1, output_file=pfile) pfile.close()
parcels/examples/tutorial_interpolation.ipynb
OceanPARCELS/parcels
mit
And we can check whether the Particle.p values indeed are consistent with the calc_p() values
for p in pset: assert np.isclose(p.p, calc_p(p.time, p.lat, p.lon))
parcels/examples/tutorial_interpolation.ipynb
OceanPARCELS/parcels
mit
And the same for the netcdf file (note that we need to convert time from nanoseconds to seconds)
ds = xr.open_dataset("interpolation_offset.nc").isel(obs=1) for i in range(len(ds['p'])): assert np.isclose(ds['p'].values[i], calc_p(float(ds['time'].values[i])/1e9, ds['lat'].values[i], ds['lon'].values[i]))
parcels/examples/tutorial_interpolation.ipynb
OceanPARCELS/parcels
mit
First, we'll download the dataset to our local machine. The data consists of characters rendered in a variety of fonts in a series of 28 by 28 images. The labels simply identify the letter presented in each image (and are limited to A-J, so, 10 classes). The training set and test set have about 500000 and 19000 image-l...
cache_file = fetch_notMNIST()
notebooks/1_notmnist.ipynb
astroNN/astroNN
mit
First, we'll print some information about the data:
with h5py.File(cache_file, 'r') as f: for name,group in f.items(): print("{}:".format(name)) for k,v in group.items(): print("\t {} {}".format(k,v.shape))
notebooks/1_notmnist.ipynb
astroNN/astroNN
mit
Problem 1 Let's take a peek at some of the data to make sure it looks sensible. Each exemplar should be an image of a character A through J rendered in a different font. Plot a 3 by 3 grid of sample images from the test set and set the title of each panel to the character name (use the labels). Hint: use matplotlib.p...
with h5py.File(cache_file, 'r') as f: pass
notebooks/1_notmnist.ipynb
astroNN/astroNN
mit
Problem 2 Now display the mean of all images from each class individually and again set the title of each panel to the corresponding character name.
with h5py.File(cache_file, 'r') as f: pass
notebooks/1_notmnist.ipynb
astroNN/astroNN
mit
Problem 3 Next, we'll randomize the data. It's important to randomize both the train and test data sets. Verify that the data is still labeled correctly after randomization.
def randomize(data, labels): pass with h5py.File(cache_file, 'r') as f: train_dataset, train_labels = randomize(f['train']['images'][:], f['train']['labels'][:]) test_dataset, test_labels = randomize(f['test']['images'][:], f['test']['labels'][:])
notebooks/1_notmnist.ipynb
astroNN/astroNN
mit
Windowing -- Tour of Beam Sometimes, we want to aggregate data, like GroupByKey or Combine, only at certain intervals, like hourly or daily, instead of processing the entire PCollection of data only once. We might want to emit a moving average as we're processing data. Maybe we want to analyze the user experience for a...
# Install apache-beam with pip. !pip install --quiet apache-beam
examples/notebooks/tour-of-beam/windowing.ipynb
axbaretto/beam
apache-2.0
First, lets define some helper functions to simplify the rest of the examples. We have a transform to help us analyze an element alongside its window information, and we have another transform to help us analyze how many elements landed into each window. We use a custom DoFn to access that information. You don't need t...
import apache_beam as beam def human_readable_window(window) -> str: """Formats a window object into a human readable string.""" if isinstance(window, beam.window.GlobalWindow): return str(window) return f'{window.start.to_utc_datetime()} - {window.end.to_utc_datetime()}' class PrintElementInfo(beam.DoFn): ...
examples/notebooks/tour-of-beam/windowing.ipynb
axbaretto/beam
apache-2.0
Now lets create some data to use in the examples. Windows define data intervals based on time, so we need to tell Apache Beam a timestamp for each element. We define a PTransform for convenience, so we can attach the timestamps automatically. Apache Beam requires us to provide the timestamp as Unix time, which is a way...
import time from apache_beam.options.pipeline_options import PipelineOptions def to_unix_time(time_str: str, time_format='%Y-%m-%d %H:%M:%S') -> int: """Converts a time string into Unix time.""" time_tuple = time.strptime(time_str, time_format) return int(time.mktime(time_tuple)) @beam.ptransform_fn @beam.typeh...
examples/notebooks/tour-of-beam/windowing.ipynb
axbaretto/beam
apache-2.0
ℹ️ After running this, it looks like the timestamps disappeared! They're actually still implicitly part of the element, just like the windowing information. If we need to access it, we can do so via a custom DoFn. Aggregation transforms use each element's timestamp along with the windowing we specified to create window...
import apache_beam as beam # All elements fall into the GlobalWindow by default. with beam.Pipeline() as pipeline: ( pipeline | 'Astrolonomical events' >> AstronomicalEvents() | 'Print element info' >> beam.ParDo(PrintElementInfo()) | 'Print window info' >> PrintWindowInfo() )
examples/notebooks/tour-of-beam/windowing.ipynb
axbaretto/beam
apache-2.0
Fixed time windows If we want to analyze our data hourly, daily, monthly, etc. We might want to create evenly spaced intervals. FixedWindows allow us to create fixed-sized windows. We only need to specify the window size in seconds. In Python, we can use timedelta to help us do the conversion of minutes, hours, or days...
import apache_beam as beam from datetime import timedelta # Fixed-sized windows of approximately 3 months. window_size = timedelta(days=3*30).total_seconds() # in seconds print(f'window_size: {window_size} seconds') with beam.Pipeline() as pipeline: elements = ( pipeline | 'Astronomical events' >> Astr...
examples/notebooks/tour-of-beam/windowing.ipynb
axbaretto/beam
apache-2.0
Sliding time windows Maybe we want a fixed-sized window, but we don't want to wait until a window finishes so we can start the new one. We might want to calculate a moving average. For example, lets say we want to analyze our data for the last three months, but we want to have a monthly report. In other words, we want ...
import apache_beam as beam from datetime import timedelta # Sliding windows of approximately 3 months every month. window_size = timedelta(days=3*30).total_seconds() # in seconds window_period = timedelta(days=30).total_seconds() # in seconds print(f'window_size: {window_size} seconds') print(f'window_period: {win...
examples/notebooks/tour-of-beam/windowing.ipynb
axbaretto/beam
apache-2.0
A thing to note with SlidingWindows is that one element might be processed multiple times because it might overlap in more than one window. In our example, the "processing" is done by PrintElementInfo which simply prints the element with its window information. For windows of three months every month, each element is p...
import apache_beam as beam from datetime import timedelta # Sliding windows of approximately 3 months every month. window_size = timedelta(days=3*30).total_seconds() # in seconds window_period = timedelta(days=30).total_seconds() # in seconds print(f'window_size: {window_size} seconds') print(f'window_period: {win...
examples/notebooks/tour-of-beam/windowing.ipynb
axbaretto/beam
apache-2.0
Note that by doing the windowing after the processing, we only process / print the elments once, but the windowing afterwards is the same. Session windows Maybe we don't want regular windows, but instead, have the windows reflect periods where activity happened. Sessions allow us to create those kinds of windows. We no...
import apache_beam as beam from datetime import timedelta # Sessions divided by approximately 1 month gaps. gap_size = timedelta(days=30).total_seconds() # in seconds print(f'gap_size: {gap_size} seconds') with beam.Pipeline() as pipeline: ( pipeline | 'Astronomical events' >> AstronomicalEvents() ...
examples/notebooks/tour-of-beam/windowing.ipynb
axbaretto/beam
apache-2.0
Load the DESI model:
fiducial_telescope = batoid.Optic.fromYaml("DESI.yaml")
notebook/DESI model details.ipynb
jmeyers314/batoid
bsd-2-clause
Corrector Internal Baffles Setup YAML to preserve dictionary order and trunctate distances (in meters) to 5 digits:
import collections def dict_representer(dumper, data): return dumper.represent_dict(data.items()) yaml.Dumper.add_representer(collections.OrderedDict, dict_representer) def float_representer(dumper, value): return dumper.represent_scalar(u'tag:yaml.org,2002:float', f'{value:.5f}') yaml.Dumper.add_represente...
notebook/DESI model details.ipynb
jmeyers314/batoid
bsd-2-clause
Define the corrector internal baffle apertures, from DESI-4103-v1. These have been checked against DESI-4037-v6, with the extra baffle between ADC1 and ADC2 added:
# baffle z-coordinates relative to FP in mm from DESI-4103-v1, checked # against DESI-4037-v6 (and with extra ADC baffle added). ZBAFFLE = np.array([ 2302.91, 2230.29, 1916.86, 1823.57, 1617.37, 1586.76, 1457.88, 1349.45, 1314.68, 1232.06, 899.67, 862.08, 568.81, 483.84, 415.22]) # baffle radii in mm from D...
notebook/DESI model details.ipynb
jmeyers314/batoid
bsd-2-clause
Calculate batoid Baffle surfaces for the corrector. These are mechanically planar, but that would put their (planar) center inside a lens, breaking the sequential tracing model. We fix this by use spherical baffle surfaces that have the same apertures. This code was originally used to read a batoid model without baff...
def baffles(nindent=10): indent = ' ' * nindent # Measure z from C1 front face in m. zbaffle = 1e-3 * (2425.007 - ZBAFFLE) # Convert r from mm to m. rbaffle = 1e-3 * RBAFFLE # By default, all baffles are planar. nbaffles = len(zbaffle) baffles = [] for i in range(nbaffles): b...
notebook/DESI model details.ipynb
jmeyers314/batoid
bsd-2-clause
Validate that the baffle edges in the final model have the correct apertures:
def validate_baffles(): corrector = fiducial_telescope['DESI.Hexapod.Corrector'] for i in range(len(ZBAFFLE)): baffle = corrector[f'Corrector.B{i+1}'] # Calculate surface z at origin in corrector coordinate system. _, _, z = batoid.CoordTransform(baffle.coordSys, corrector.coordSys).appl...
notebook/DESI model details.ipynb
jmeyers314/batoid
bsd-2-clause
Corrector Cage and Spider Calculate simplified vane coordinates using parameters from DESI-4110-v1:
def spider(dmin=1762, dmax=4940.3, ns_angle=77, widths=[28.5, 28.5, 60., 19.1], wart_r=958, wart_dth=6, wart_w=300): # Vane order is [NE, SE, SW, NW], with N along -y and E along +x. fig, ax = plt.subplots(figsize=(10, 10)) ax.add_artist(plt.Circle((0, 0), 0.5 * dmax, color='yellow')) ax.add_...
notebook/DESI model details.ipynb
jmeyers314/batoid
bsd-2-clause
Plot "User Aperture Data" from the ZEMAX "spider" surface 6, as cross check:
def plot_obs(): wart1 = np.array([ [ -233.22959, 783.94254], [-249.32698, 937.09892], [49.02959, 968.45746], [ 65.126976, 815.30108], [ -233.22959, 783.94254], ]) wart2 = np.array([ [-233.22959, 783.94254], [ -249.32698, 937.09892], [49.029593,...
notebook/DESI model details.ipynb
jmeyers314/batoid
bsd-2-clause
CGRtools has subpackage containers with data structures classes: MoleculeContainer - for molecular structure ReactionContainer - for chemical reaction CGRContainer - for Condensed Graph of Reaction QueryContainer - queries for substructure search in molecules QueryCGRContainer - queries for substructure search in CGR...
from CGRtools.containers import * # import all containers
doc/tutorial/1_data_types_and_operations.ipynb
stsouko/CGRtools
lgpl-3.0
1.1. MoleculeContainer Molecules are represented as undirected graphs. Molecules contain Atom objects and Bond objects. Atom objects are represented as dictionary with unique number for each atom as key. Bond objects are stored as sparse matrix with adjacent atoms pair as keys for rows and columns. Hereafter, atom nu...
m1.meta # dictionary for molecule properties storage. For example, DTYPE/DATUM fields of SDF file are read into this dictionary m1 # MoleculeContainer supports depiction and graphic representation in Jupyter notebooks. m1.depict() # depiction returns SVG image in format string with open('molecule.svg', 'w') as f: # ...
doc/tutorial/1_data_types_and_operations.ipynb
stsouko/CGRtools
lgpl-3.0
Each structure has additional atoms attributes: number of neighbors and hybridization. The following notations are used for hybridization of atoms. Values are given as numbers below (in parenthesis symbols that are used in SMILES-like signatures are shown): 1 (s) - all bonds of atom are single, i.e. sp3 hybridization ...
# iterate over atoms using its numbers list(m1.atoms()) # works the same as dict.items() # iterate over bonds using adjacent atoms numbers list(m1.bonds()) # access to atom by number m1.atom(1) try: m1.atom(10) # raise error for absent atom numbers except KeyError: print(format_exc()) # access to bond usin...
doc/tutorial/1_data_types_and_operations.ipynb
stsouko/CGRtools
lgpl-3.0
Atom objects are dataclasses which store information about: element isotope charge radical state xy coordinates Also atoms has methods for data integrity checks and include some internally used data.
a = m1.atom(1) # access to information a.atomic_symbol # element symbol a.charge # formal charge a.is_radical # atom radical state a.isotope # atom isotope. Default isotope if not set. Default isotopes are the same as used in InChI notation a.x # coordinates a.y #or a.xy a.neighbors # Number of neighboring atoms...
doc/tutorial/1_data_types_and_operations.ipynb
stsouko/CGRtools
lgpl-3.0
Atomic attributes are assignable. CGRtools has integrity checks for verification of changes induced by user
a.charge = 1 m1 a.charge = 0 a.is_radical = True m1 # bond objects also are data-like classes which store information about bond order b = m1.bond(3, 4) b.order try: b.order = 1 # order change not possible except AttributeError: print(format_exc())
doc/tutorial/1_data_types_and_operations.ipynb
stsouko/CGRtools
lgpl-3.0
Bonds are Read-only For bond modification one should to use delete_bond method to break bond and add_bond for creating new.
m1.delete_bond(3, 4) m1
doc/tutorial/1_data_types_and_operations.ipynb
stsouko/CGRtools
lgpl-3.0
Method delete_atom removes atom from the molecule
m1.delete_atom(3) m1 m_copy # copy unchanged!
doc/tutorial/1_data_types_and_operations.ipynb
stsouko/CGRtools
lgpl-3.0
Atoms and bonds objects can be converted into integer representation that could be used to classify their types. Atom type is represented by 21 bit code rounded to 32 bit integer number: 9 bits are used for isotope (511 posibilities, highest known isotope is ~300) 7 bits stand for atom number (2 ** 7 - 1 == 127, curre...
int(a) # 61705 == 000001111 0001000 0100 1 # 000001111 == 15 isotope # 0001000 == 8 Oxygen # 0100 == 4 (4 - 4 = 0) uncharged # 1 == 1 is radical int(b) # bonds are encoded by their order a = m_copy.atom(1) print(a.implicit_hydrogens) # get number of implicit hydrogens on atom 1 print(a.explicit_hydrogens) # get numb...
doc/tutorial/1_data_types_and_operations.ipynb
stsouko/CGRtools
lgpl-3.0
Connected components. Sometimes molecules has disconnected components (salts etc). One can find them and split molecule to separate components.
m2 # it's a salt represented as one graph m2.connected_components # tuple of tuples of atoms belonging to graph components anion, cation = m2.split() # split molecule to components anion # graph of only one salt component cation # graph of only one salt component
doc/tutorial/1_data_types_and_operations.ipynb
stsouko/CGRtools
lgpl-3.0
Union of molecules Sometimes it is more convenient to represent salts as ion pair. Otherwise ambiguity could be introduced, for example in reaction of salt exchange: Ag+ + NO3- + Na+ + Br- = Ag+ + Br- + Na+ + NO3-. Reactants and products sets are the same. In this case one can combine anion-cation pair into single gra...
salt = anion | cation # or salt = anion.union(cation) salt # this graph has disconnected components, it is considered single compound now
doc/tutorial/1_data_types_and_operations.ipynb
stsouko/CGRtools
lgpl-3.0
Substructures could be extracted from molecules.
sub = m3.substructure([4,5,6,7,8,9]) # substructure with passed atoms sub
doc/tutorial/1_data_types_and_operations.ipynb
stsouko/CGRtools
lgpl-3.0
augmented_substructure is a substructure consisting from atoms and a given number of shells of neighboring atoms around it. deep argument is a number of considered shells. It also returns projection by default.
aug = m3.augmented_substructure([10], deep=2) # atom 10 is Nitrogen aug
doc/tutorial/1_data_types_and_operations.ipynb
stsouko/CGRtools
lgpl-3.0
Atoms Ordering. This functionality is used for canonic numbering of atoms in molecules. Morgan algorithm is used for atom ranking. Property atoms_order returns dictionary of atom numbers as keys and their ranks according to canonicalization as values. Equal rank mean that atoms are symmetric (are mapped to each other i...
m5.atoms_order
doc/tutorial/1_data_types_and_operations.ipynb
stsouko/CGRtools
lgpl-3.0
Atom number can be changed by remap method. This method is useful when it is needed to change order of atoms in molecules. First argument to remap method is dictionary with existing atom numbers as keys and desired atom number as values. It is possible to change atom numbers for only part of atoms. Atom numbers could b...
m5 remapped = m5.remap({4:2}, copy=True) remapped
doc/tutorial/1_data_types_and_operations.ipynb
stsouko/CGRtools
lgpl-3.0
1.2. ReactionContainer ReactionContainer objects has the following properties: reactants - list of reactants molecules reagents - list of reagents molecules products - list of products molecules meta - dictinary of reaction metadata (DTYPE/DATUM block in RDF)
r1 # depiction supported r1.meta print(r1.reactants, r1.products) # Access to lists of reactant and products. reactant1, reactant2, reactant3 = r1.reactants product = r1.products[0]
doc/tutorial/1_data_types_and_operations.ipynb
stsouko/CGRtools
lgpl-3.0
Reactions also has standardize, kekule, thiele, implicify_hydrogens, explicify_hydrogens, etc methods (see part 3). These methods are applied independently to every molecule in reaction. 1.3. CGR CGRContainer object is similar to MoleculeConrtainer, except some methods. The following methods are not suppoted for CGRCon...
cgr1 = m7 ^ m8 # CGR from molecules # or cgr1 = m7.compose(m8) print(cgr1) cgr1 r1 cgr2 = ~r1 # CGR from reactions # or cgr2 = r1.compose() print(cgr2) # signature is printed out. cgr2.clean2d() cgr2 a = cgr2.atom(2) # atom access is the same as for MoleculeContainer a.atomic_symbol # element attribute a.isotope...
doc/tutorial/1_data_types_and_operations.ipynb
stsouko/CGRtools
lgpl-3.0
For CGRContainer attributes charge, is_radical, neighbors and hybridization refer to atom state in reactant of reaction; arguments p_charge, p_is_radical, p_neighbors and p_hybridization could be used to extract atom state in product part in reaction.
a.charge # charge of atom in reactant a.p_charge # charge of atom in product a.p_is_radical # radical state of atom in product. a.neighbors # number of neighbors of atom in reactant a.p_neighbors # number of neighbors of atom in product a.hybridization # hybridization of atom in reactant. 1 means only single bonds...
doc/tutorial/1_data_types_and_operations.ipynb
stsouko/CGRtools
lgpl-3.0
Bonds has order and p_order attribute If order attribute value is None, it means that bond was formed If p_order is None, it means that bond was broken Both order and p_order can't be None
b.order # bond order in reactant b.p_order is None # bond order in product in None
doc/tutorial/1_data_types_and_operations.ipynb
stsouko/CGRtools
lgpl-3.0
CGR can be decomposed back to reaction, i.e. reactants and products. Notice that CGR can lose information in case of unbalanced reactions (where some atoms of reactant does not have counterpart in product, and vice versa). Decomposition of CGRs for unbalanced reactions back to reaction may lead to strange (and erroneou...
reactant_part, product_part = ~cgr1 # CGR of unbalanced reaction is decomposed back into reaction # or reactant_part, product_part = cgr1.decompose() reactant_part # reactants extracted. One can notice it is initial molecule product_part #extracted products. Originally benzene was the product.
doc/tutorial/1_data_types_and_operations.ipynb
stsouko/CGRtools
lgpl-3.0
For decomposition of CGRContainer back into ReactionContainer ReactionContainer.from_cgr constructor method can be used.
decomposed = ReactionContainer.from_cgr(cgr2) decomposed.clean2d() decomposed
doc/tutorial/1_data_types_and_operations.ipynb
stsouko/CGRtools
lgpl-3.0
You can see that water absent in products initially was restored. This is a side-effect of CGR decomposing that could help with reaction balancing. But balancing using CGR decomposition works correctly only if minor part atoms are lost but multiplicity and formal charge are saved. In next release electronic state ba...
r1 # compare with initial reaction
doc/tutorial/1_data_types_and_operations.ipynb
stsouko/CGRtools
lgpl-3.0
1.4 Queries CGRtools supports special objects for Queries. Queries are designed for substructure isomorphism. User can set number of neighbors and hybridization by himself (in molecules they could be calculated but could not be changed). Queries don't have reset_query_marks method
from CGRtools.containers import* m10 # ether carb = m10.substructure([5,7,2], as_query=True) # extract of carboxyl fragment print(carb) carb
doc/tutorial/1_data_types_and_operations.ipynb
stsouko/CGRtools
lgpl-3.0
CGRs also can be transformed into Query. QueryCGRContainer is similar to QueryContainer class for CGRs and has the same API. QueryCGRContainer take into account state of atoms and bonds in reactant and product, including neighbors and hybridization
cgr_q = cgr1.substructure(cgr1, as_query=True) # transfrom CGRContainer into QueryCGRContainer #or cgr_q = QueryCGRContainer() | cgr1 # Union of Query container with CGR or Molecule gives QueryCGRContainer print(cgr_q) # print out signature of query cgr_q
doc/tutorial/1_data_types_and_operations.ipynb
stsouko/CGRtools
lgpl-3.0
1.5. Molecules, CGRs, Reactions construction CGRtools has API for objects construction from scratch. CGR and Molecule has methods add_atom and add_bond for adding atoms and bonds.
from CGRtools.containers import MoleculeContainer from CGRtools.containers.bonds import Bond from CGRtools.periodictable import Na m = MoleculeContainer() # new empty molecule m.add_atom('C') # add Carbon atom using element symbol m.add_atom(6) # add Carbon atom using element number. {'element': 6} is not valid, ...
doc/tutorial/1_data_types_and_operations.ipynb
stsouko/CGRtools
lgpl-3.0
Reactions can be constructed from molecules. Reactions are tuple-like objects. Modification impossible.
r = ReactionContainer(reactants=[m1], products=[m11]) # one-step way to construct reaction # or r = ReactionContainer([m1], [m11]) # first list of MoleculeContainers is interpreted as reactants, second one - as products r r.fix_positions() # this method fixes coordinates of molecules in reaction without calculation o...
doc/tutorial/1_data_types_and_operations.ipynb
stsouko/CGRtools
lgpl-3.0
QueryContainers can be constructed in the same way as MoleculeContainers. Unlike other containers QueryContainers additionally support atoms, neighbors and hybridization lists.
q = QueryContainer() # creation of empty container q.add_atom('N') # add N atom, any isotope, not radical, neutral charge, # number of neighbors and hybridization are irrelevant q.add_atom('C', neighbors=[2, 3], hybridization=2) # add carbon atom, any isotope, not radical, neutral charge, ...
doc/tutorial/1_data_types_and_operations.ipynb
stsouko/CGRtools
lgpl-3.0
1.6. Extending CGRtools You can easily customize CGRtools for your tasks. CGRtools is OOP-oriented library with subclassing and inheritance support. As an example, we show how special marks on atoms for ligand donor centers can be added.
from CGRtools.periodictable import Core, C, O class Marked(Core): __slots__ = '__mark' # all new attributes should be slotted! def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.__mark = None # set default value for added attribute @property def mark(self): ...
doc/tutorial/1_data_types_and_operations.ipynb
stsouko/CGRtools
lgpl-3.0
EvoFlow hello world: OneMax This notebook provide a quick introduction of how EvoFlow works by showing how you can use to solve the classic OneMax problem with it. At its core <b>EvoFlow is a modern hardware accelerated genetic algorithm framework that recast genetic algorithm programing as a dataflow computation on te...
# installing the latest version of evoflow try: import evoflow except: !pip install -U evoflow %load_ext autoreload %autoreload 2 from evoflow.engine import EvoFlow from evoflow.selection import SelectFittest from evoflow.population import randint_population from evoflow.fitness import Sum from evoflow.ops imp...
notebooks/onemax.ipynb
google-research/evoflow
apache-2.0
Population definition In this example, we are going to represent the population as a 2D tensor where: the 1st dimension is the number of chromosome (population) the 2nd dimension is the number of gene per chromosome.
POPULATION_SIZE = 64 #@param {type: "slider", min: 16, max: 2048} CHROMOSOME_SIZE = 32 #@param {type: "slider", min: 16, max: 2048} SHAPE = (POPULATION_SIZE, CHROMOSOME_SIZE) print(f"Population will have {SHAPE[0]} distinct chromosomes made of {SHAPE[1]} genes")
notebooks/onemax.ipynb
google-research/evoflow
apache-2.0
Our model need an initial population to mutate as inputs. Here, we are taking the traditional approach to initialize this population at random while ensure the gene value is either 0 or 1 by setting the max_value to 1. We will use the population in the evolve() funtion very similarly that you would feed your x_train da...
population = randint_population(SHAPE, max_value=1)
notebooks/onemax.ipynb
google-research/evoflow
apache-2.0
Evolution model setup Building an evolution model requires setup the <i>evolution operations</i> and then compiling the model. Genetic operations are represented by OPs that are very similar to the tf.keras.layers. They are combined by creating a directed graph that inter-connect them, again very similarly to what the ...
inputs = Input(shape=(SHAPE)) x = RandomMutations1D(max_gene_value=1, min_gene_value=0)(inputs) outputs = UniformCrossover1D()(x)
notebooks/onemax.ipynb
google-research/evoflow
apache-2.0
We instantiate our model by providing its inputs and outputs. Under the hood a EvoFlow model is represented as a direct graph that support multiples inputs, multiple outputs, and arbitrary branching to tackle the most complex use-cases. You can use summary() to check what your model will look like.
ef = EvoFlow(inputs, outputs) ef.summary()
notebooks/onemax.ipynb
google-research/evoflow
apache-2.0
Model compilation Before the model is ready for evolutions, it needs two additional key components that will be supplied to the compile function: How to asses how good is a given chromosome (fitness function) How to select chromosomes and renew the pool (Selection function) Fitness function The fitness function is t...
fitness_function = Sum(max_sum_value=CHROMOSOME_SIZE)
notebooks/onemax.ipynb
google-research/evoflow
apache-2.0
Modeling evolutionary selection The evolutionary process takes the fitness values and decides which chromosomes to keep. A naive form to model selection is to keep the fitest individuals and carry them over to the next generation. This is usualy referred as an elitist selection strategy. For instance, we can keep the f...
selection_strategy = SelectFittest()
notebooks/onemax.ipynb
google-research/evoflow
apache-2.0
Compilation Now that we have defined our fitness_function and our selection_strategy, our model is ready to get compiled with those as parameters.
ef.compile(selection_strategy, fitness_function)
notebooks/onemax.ipynb
google-research/evoflow
apache-2.0
Evolution We now are going to evolve our inital random population over a couple of generations. At each generation the evolution strategy keep the best invididuals and replace the low performing ones with the best one of the previous generation. generation= controls the number of time the model is applied to the popula...
GENERATIONS = 4 #@param {type: "slider", min: 5, max: 100}
notebooks/onemax.ipynb
google-research/evoflow
apache-2.0
As the model evolve, look for the value of fitness_function_max which indicate the value of the best performing chromosome. As you will see it will quickly reach 1, which indicates that we found an optimal solution
results = ef.evolve(population, generations=GENERATIONS)
notebooks/onemax.ipynb
google-research/evoflow
apache-2.0
Results Let's check that the optimal solution we found are chromosomes fully made of 1s. First let's look at how quickly our model converged. Depending on your population size and chromosomes size the convergence will be slower or faster. We encourage you to experiments with different values. Note: in the graph below...
results.plot_fitness(static=True) # note we use a static display
notebooks/onemax.ipynb
google-research/evoflow
apache-2.0
Next we can look at what the population look like using a heatmap. As the model converged to the optimal solution the top chromosomes are all made of ones and form a uniform color band. If you evolve long enough the whole heatmap will be of a solid color as all the chromosomes will contains the optimial solution.
results.display_populations(top_k=100, rounding=0)
notebooks/onemax.ipynb
google-research/evoflow
apache-2.0
Finally to convince ourselves that EvoFlow worked as intended we can display the top 10 best solutions and check they are made of 1s
results.top_k()
notebooks/onemax.ipynb
google-research/evoflow
apache-2.0
Data loading Load the training data:
import csv def load_train_data(filename): X = [] y = [] with open(filename) as fd: reader = csv.reader(fd, delimiter='\t') # ignore header row next(reader, None) for row in reader: X.append(row[1]) y.append(row[0].split()) return n...
indeed.ipynb
matheusportela/indeed-ml-codesprint
mit
Show some input and output data:
print 'Input:', X[0] print print 'Output:', y[0]
indeed.ipynb
matheusportela/indeed-ml-codesprint
mit
Preprocessing definition Preprocessing steps are applied differently for input vectors and target vectors. Input preprocessing First, we need to transform the input text into a numerical representation. This is done by generating a vector where each position is the number of occurrences for a given word in the data. Fo...
from sklearn.pipeline import Pipeline from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfTransformer X_preprocessor = Pipeline([ ('count', CountVectorizer(max_df=0.95, min_df=2, ngram_range=(1, 2))), ('tfidf', TfidfTransformer()) ])
indeed.ipynb
matheusportela/indeed-ml-codesprint
mit
Define multi-label binarizer for output data. Each target sample will be a binary array: 0 if not present, 1 otherwise.
from sklearn.preprocessing import LabelEncoder y_preprocessors = { 'job': LabelEncoder(), 'wage': LabelEncoder(), 'degree': LabelEncoder(), 'experience': LabelEncoder(), 'supervising': LabelEncoder() }
indeed.ipynb
matheusportela/indeed-ml-codesprint
mit
Separate the target vector y into one vector for each mutually exclusive tag type: ```python y = [['part-time-job', 'salary'], ['full-time-job'], ['part-time-job', 'supervising-job']] split_y = split_exclusive_tags(y) split_y { 'job': [['part-time-job'], ['full-time-job'], ['part-time-job']], 'wage': [['sala...
# Separate targets for mutually exclusive tags def split_exclusive_tags(y): split_y = { 'job': [], 'wage': [], 'degree': [], 'experience': [], 'supervising': [] } for target in y: split_y['job'].append(filter(lambda x: x in ['part-time-job', 'full-time-jo...
indeed.ipynb
matheusportela/indeed-ml-codesprint
mit
Classifier definition Define classifier as SVM with one-vs-all strategy for multilabel classification.
# F1 score: 0.511 from sklearn.multiclass import OneVsRestClassifier from sklearn.svm import LinearSVC models = { 'job': OneVsRestClassifier(LinearSVC()), 'wage': OneVsRestClassifier(LinearSVC()), 'degree': OneVsRestClassifier(LinearSVC()), 'experience': OneVsRestClassifier(LinearSVC()), 'supervisi...
indeed.ipynb
matheusportela/indeed-ml-codesprint
mit
Model usage For each mutually exclusive tag type, we train one multiclass model capable of deciding which tag (or even none) is appropriate for the given input. Initially, an attempt of a single multilabel model was used, which would be able to output multiple labels at once. However, considering that the input space w...
def fit_models(models, X_preprocessor, y_preprocessors, X, y): print 'Fitting models' split_y = split_exclusive_tags(y) X_processed = X_preprocessor.fit_transform(X) for tag_type, model in models.items(): # Learn one preprocessor for each mutually exclusive tag X_processed = X_prep...
indeed.ipynb
matheusportela/indeed-ml-codesprint
mit
Predict the output by executing the model for each tag type:
def predict_models(models, X_preprocessor, y_preprocessors, X): print 'Predicting with models' output = [[] for _ in X] for tag_type, model in models.items(): # Preprocess and use model for the given type of tag X_processed = X_preprocessor.transform(X) model_output = model...
indeed.ipynb
matheusportela/indeed-ml-codesprint
mit