markdown stringlengths 0 1.02M | code stringlengths 0 832k | output stringlengths 0 1.02M | license stringlengths 3 36 | path stringlengths 6 265 | repo_name stringlengths 6 127 |
|---|---|---|---|---|---|
**Exercise:** Plot the previous figure again, and see what font sizes have changed. Look up any other element of `rcParams`, change its value, and check the effect on the figure. If you find yourself making the same customizations in several notebooks, you can put changes to `rcParams` in a `matplotlibrc` file, [which... | plt.style.available | _____no_output_____ | MIT | 07_plot.ipynb | abostroem/AstronomicalData |
Note that `seaborn-paper`, `seaborn-talk` and `seaborn-poster` are particularly intended to prepare versions of a figure with text sizes and other features that work well in papers, talks, and posters.To use any of these style sheets, run `plt.style.use` like this:```plt.style.use('fivethirtyeight')``` The style sheet ... | import os
filename = 'az-paper-twocol.mplstyle'
path = 'https://github.com/AllenDowney/AstronomicalData/raw/main/data/'
if not os.path.exists(filename):
print(download(path+filename)) | _____no_output_____ | MIT | 07_plot.ipynb | abostroem/AstronomicalData |
You can use it like this:```plt.style.use('./az-paper-twocol.mplstyle')```The prefix `./` tells Matplotlib to look for the file in the current directory. As an alternative, you can install a style sheet for your own use by putting it in your configuration directory. To find out where that is, you can run the following... | plt.rcParams['text.usetex'] = True | _____no_output_____ | MIT | 07_plot.ipynb | abostroem/AstronomicalData |
If you go back and draw the figure again, you should see the difference.If you get an error message like```LaTeX Error: File `type1cm.sty' not found.```You might have to install a package that contains the fonts LaTeX needs. On some systems, the packages `texlive-latex-extra` or `cm-super` might be what you need. [Se... | import os
filename = 'gd1_dataframe.hdf5'
path = 'https://github.com/AllenDowney/AstronomicalData/raw/main/data/'
if not os.path.exists(filename):
print(download(path+filename))
import pandas as pd
centerline = pd.read_hdf(filename, 'centerline') | _____no_output_____ | MIT | 07_plot.ipynb | abostroem/AstronomicalData |
And define the coordinates of the rectangle we selected. | pm1_min = -8.9
pm1_max = -6.9
pm2_min = -2.2
pm2_max = 1.0
pm1_rect = [pm1_min, pm1_min, pm1_max, pm1_max]
pm2_rect = [pm2_min, pm2_max, pm2_max, pm2_min] | _____no_output_____ | MIT | 07_plot.ipynb | abostroem/AstronomicalData |
To plot this rectangle, we'll use a feature we have not seen before: `Polygon`, which is provided by Matplotlib.To create a `Polygon`, we have to put the coordinates in an array with `x` values in the first column and `y` values in the second column. | import numpy as np
vertices = np.transpose([pm1_rect, pm2_rect])
vertices | _____no_output_____ | MIT | 07_plot.ipynb | abostroem/AstronomicalData |
The following function takes a `DataFrame` as a parameter, plots the proper motion for each star, and adds a shaded `Polygon` to show the region we selected. | from matplotlib.patches import Polygon
def plot_proper_motion(df):
pm1 = df['pm_phi1']
pm2 = df['pm_phi2']
plt.plot(pm1, pm2, 'ko', markersize=0.3, alpha=0.3)
poly = Polygon(vertices, closed=True,
facecolor='C1', alpha=0.4)
plt.gca().add_patch(poly)
plt.xlabel('$\... | _____no_output_____ | MIT | 07_plot.ipynb | abostroem/AstronomicalData |
Notice that `add_patch` is like `invert_yaxis`; in order to call it, we have to use `gca` to get the current axes.Here's what the new version of the figure looks like. We've changed the labels on the axes to be consistent with the paper. | plt.rcParams['text.usetex'] = False
plt.style.use('default')
plot_proper_motion(centerline) | _____no_output_____ | MIT | 07_plot.ipynb | abostroem/AstronomicalData |
Upper leftNow let's work on the panel in the upper left. We have to reload `candidates`. | import os
filename = 'gd1_candidates.hdf5'
path = 'https://github.com/AllenDowney/AstronomicalData/raw/main/data/'
if not os.path.exists(filename):
print(download(path+filename))
import pandas as pd
filename = 'gd1_candidates.hdf5'
candidate_df = pd.read_hdf(filename, 'candidate_df') | _____no_output_____ | MIT | 07_plot.ipynb | abostroem/AstronomicalData |
Here's a function that takes a `DataFrame` of candidate stars and plots their positions in GD-1 coordindates. | def plot_first_selection(df):
x = df['phi1']
y = df['phi2']
plt.plot(x, y, 'ko', markersize=0.3, alpha=0.3)
plt.xlabel('$\phi_1$ [deg]')
plt.ylabel('$\phi_2$ [deg]')
plt.title('Proper motion selection', fontsize='medium')
plt.axis('equal') | _____no_output_____ | MIT | 07_plot.ipynb | abostroem/AstronomicalData |
And here's what it looks like. | plot_first_selection(candidate_df) | _____no_output_____ | MIT | 07_plot.ipynb | abostroem/AstronomicalData |
Lower rightFor the figure in the lower right, we need to reload the merged `DataFrame`, which contains data from Gaia and photometry data from Pan-STARRS. | import pandas as pd
filename = 'gd1_merged.hdf5'
merged = pd.read_hdf(filename, 'merged') | _____no_output_____ | MIT | 07_plot.ipynb | abostroem/AstronomicalData |
From the previous notebook, here's the function that plots the color-magnitude diagram. | import matplotlib.pyplot as plt
def plot_cmd(table):
"""Plot a color magnitude diagram.
table: Table or DataFrame with photometry data
"""
y = table['g_mean_psf_mag']
x = table['g_mean_psf_mag'] - table['i_mean_psf_mag']
plt.plot(x, y, 'ko', markersize=0.3, alpha=0.3)
plt.xlim([0, 1.... | _____no_output_____ | MIT | 07_plot.ipynb | abostroem/AstronomicalData |
And here's what it looks like. | plot_cmd(merged) | _____no_output_____ | MIT | 07_plot.ipynb | abostroem/AstronomicalData |
**Exercise:** Add a few lines to `plot_cmd` to show the Polygon we selected as a shaded area. Run these cells to get the polygon coordinates we saved in the previous notebook. | import os
filename = 'gd1_polygon.hdf5'
path = 'https://github.com/AllenDowney/AstronomicalData/raw/main/data/'
if not os.path.exists(filename):
print(download(path+filename))
coords_df = pd.read_hdf(filename, 'coords_df')
coords = coords_df.to_numpy()
coords
# Solution
#poly = Polygon(coords, closed=True,
# ... | _____no_output_____ | MIT | 07_plot.ipynb | abostroem/AstronomicalData |
SubplotsNow we're ready to put it all together. To make a figure with four subplots, we'll use `subplot2grid`, [which requires two arguments](https://matplotlib.org/3.3.1/api/_as_gen/matplotlib.pyplot.subplot2grid.html):* `shape`, which is a tuple with the number of rows and columns in the grid, and* `loc`, which is ... | shape = (2, 2)
plt.subplot2grid(shape, (0, 0))
plot_first_selection(candidate_df)
plt.subplot2grid(shape, (0, 1))
plot_proper_motion(centerline)
plt.subplot2grid(shape, (1, 0))
plot_second_selection(selected)
plt.subplot2grid(shape, (1, 1))
plot_cmd(merged)
poly = Polygon(coords, closed=True,
facecol... | _____no_output_____ | MIT | 07_plot.ipynb | abostroem/AstronomicalData |
We use [`plt.tight_layout`](https://matplotlib.org/3.3.1/tutorials/intermediate/tight_layout_guide.html) at the end, which adjusts the sizes of the panels to make sure the titles and axis labels don't overlap.**Exercise:** See what happens if you leave out `tight_layout`. Adjusting proportionsIn the previous figure, t... | plt.figure(figsize=(9, 4.5))
shape = (2, 4)
plt.subplot2grid(shape, (0, 0), colspan=3)
plot_first_selection(candidate_df)
plt.subplot2grid(shape, (0, 3))
plot_proper_motion(centerline)
plt.subplot2grid(shape, (1, 0), colspan=3)
plot_second_selection(selected)
plt.subplot2grid(shape, (1, 3))
plot_cmd(merged)
poly = ... | _____no_output_____ | MIT | 07_plot.ipynb | abostroem/AstronomicalData |
Exercises Playing with the interpreterTry to execute some simple statements and expressions (one at a time) e.g```print("Hello!")1j**21 / 21 // 25 + 510 / 2 + 5my_tuple = (1, 2, 3)my_tuple[0] = 12.3**4.5```Do you understand what is going on in all cases? Most Python functions and objects can provide documentation via ... | print = __builtin__.print
print("hello") | _____no_output_____ | MIT | notebooks/exercises/.ipynb_checkpoints/2 - Data types and expressions-checkpoint.ipynb | smasoka/python-introduction |
Data Transformation Logistic Regression - on [Titanic Dataset](https://www.kaggle.com/c/titanic)- Models the probability an object belongs to a class- Values ranges from 0 to 1- Can use threshold to classify into which classes a class belongs- An S-shaped curve$\begin{align}\sigma(t) = \frac{1}{1 + e^{-t}}\end{align... | import pandas as pd
df_train = pd.read_csv('../data/titanic_train.csv')
df_train.head(8) | _____no_output_____ | MIT | classification/notebooks/.ipynb_checkpoints/05 - Validation Measures-checkpoint.ipynb | pshn111/Machine-Learning-Package |
Data Statistics Describing the statistics for numerical features | df_train.describe() | _____no_output_____ | MIT | classification/notebooks/.ipynb_checkpoints/05 - Validation Measures-checkpoint.ipynb | pshn111/Machine-Learning-Package |
Find the count of the non-NaN values per feature | df_train.count() | _____no_output_____ | MIT | classification/notebooks/.ipynb_checkpoints/05 - Validation Measures-checkpoint.ipynb | pshn111/Machine-Learning-Package |
What features can be removed? Remove features that are not related to your outcome | df_train.drop(['Name', 'Ticket'], axis=1, inplace=True) | _____no_output_____ | MIT | classification/notebooks/.ipynb_checkpoints/05 - Validation Measures-checkpoint.ipynb | pshn111/Machine-Learning-Package |
Remove column with missing data | df_train.drop(['Cabin'], axis=1, inplace=True) | _____no_output_____ | MIT | classification/notebooks/.ipynb_checkpoints/05 - Validation Measures-checkpoint.ipynb | pshn111/Machine-Learning-Package |
Data Imputation - Filling in missing values- Select a percentage threshold that you would want to accomodate- Around 1/5th to 1/3rd of the data (20% to 33.3%)- if more than 50% of the data is missing, you will be generating data for the majority of your dataset - Not a good thing to do | from matplotlib import pyplot as plt
import seaborn as sns
plt.figure(figsize=(7,5))
sns.boxplot(x='Pclass',y='Age',data=df_train)
from matplotlib import pyplot as plt
import seaborn as sns
plt.figure(figsize=(7,5))
sns.boxplot(x='Sex',y='Age',data=df_train)
from matplotlib import pyplot as plt
import seaborn as sns
pl... | _____no_output_____ | MIT | classification/notebooks/.ipynb_checkpoints/05 - Validation Measures-checkpoint.ipynb | pshn111/Machine-Learning-Package |
Drop Rows | df_train.dropna(inplace=True)
df_train.count() | _____no_output_____ | MIT | classification/notebooks/.ipynb_checkpoints/05 - Validation Measures-checkpoint.ipynb | pshn111/Machine-Learning-Package |
Data Transformation Convert the categorical values to numeric- Find the columns that are explicitly categorical - like male, female- Find the columns that are although numerical, represent categorical features One-Hot Encoding- A technique to create multiple feature for each corrsponding value | import numpy as np
col = 'Sex'
print(np.unique(df_train[col]))
import numpy as np
col = 'Embarked'
print(np.unique(df_train[col]))
import numpy as np
col = 'Pclass'
print(np.unique(df_train[col]))
sex = pd.get_dummies(df_train["Sex"],drop_first=True)
embarked = pd.get_dummies(df_train["Embarked"],drop_first=True)
pclas... | _____no_output_____ | MIT | classification/notebooks/.ipynb_checkpoints/05 - Validation Measures-checkpoint.ipynb | pshn111/Machine-Learning-Package |
Drop the columns that were used for transformation | df_train.drop(['Sex', 'Embarked', 'Pclass', 'PassengerId'], axis=1, inplace=True)
df_train.head() | _____no_output_____ | MIT | classification/notebooks/.ipynb_checkpoints/05 - Validation Measures-checkpoint.ipynb | pshn111/Machine-Learning-Package |
Add encoded columns to the training dataset | df_train = pd.concat([df_train,pclass,sex,embarked],axis=1)
df_train.head() | _____no_output_____ | MIT | classification/notebooks/.ipynb_checkpoints/05 - Validation Measures-checkpoint.ipynb | pshn111/Machine-Learning-Package |
Save the transformed file as a pickle file | df_train.shape
import pickle as pkl
df_train.to_pickle('../data/titanic_tansformed.pkl') | _____no_output_____ | MIT | classification/notebooks/.ipynb_checkpoints/05 - Validation Measures-checkpoint.ipynb | pshn111/Machine-Learning-Package |
Logistic Regression | data = df_train.drop("Survived",axis=1)
label = df_train["Survived"]
data.head()
from sklearn.cross_validation import train_test_split
data_train, data_test, label_train, label_test = train_test_split(data, label, test_size = 0.3, random_state = 101)
from sklearn.linear_model import LogisticRegression
# Run Logistic R... | _____no_output_____ | MIT | classification/notebooks/.ipynb_checkpoints/05 - Validation Measures-checkpoint.ipynb | pshn111/Machine-Learning-Package |
Accuracy | print('Accuracy', log_regr.score(data_test, label_test))
print('Coefficients', log_regr.coef_)
print('Intercept', log_regr.intercept_) | Accuracy 0.8127340823970037
Coefficients [[-0.02813121 -0.22110356 -0.0893393 0.00480662 -0.49460192 -1.58514132
-2.33322621 -0.02832966 -0.26523619]]
Intercept [2.81524481]
| MIT | classification/notebooks/.ipynb_checkpoints/05 - Validation Measures-checkpoint.ipynb | pshn111/Machine-Learning-Package |
Precision Recall | from sklearn.metrics import classification_report
print(classification_report(label_test, predictions)) | precision recall f1-score support
0 0.81 0.91 0.86 163
1 0.83 0.65 0.73 104
avg / total 0.81 0.81 0.81 267
| MIT | classification/notebooks/.ipynb_checkpoints/05 - Validation Measures-checkpoint.ipynb | pshn111/Machine-Learning-Package |
Cross Validation | from sklearn.model_selection import StratifiedKFold
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
# skf = StratifiedKFold(n_splits=5)
log_regr = LogisticRegression()
log_regr.fit(data_train, label_train)
score = log_regr.score(data_train, label_train)
print('Tr... | Train accuracy score 0.8102893890675241
Cross Val Accuracy for each run [0.74603175 0.6984127 0.77777778 0.88888889 0.79365079 0.76190476
0.81967213 0.81967213 0.90163934 0.7704918 ]
CrossVal Accuracy 0.7978142076502732
| MIT | classification/notebooks/.ipynb_checkpoints/05 - Validation Measures-checkpoint.ipynb | pshn111/Machine-Learning-Package |
AUC - Receiver Operating Characteristics- How much a model is capable of distinguishing between classes- Higher the AUC, better the model is$\begin{align}True Positive Rate = \frac{TP}{TP + FN}\end{align}$$\begin{align}\ False Positive Rate = 1 - \frac{TN}{TN + FP} = \frac{FP}{TN + FP}\end{align}$ | from sklearn import metrics
fpr, tpr, threshold = metrics.roc_curve(label_test, log_regr.predict(data_test))
roc_auc = metrics.auc(fpr, tpr)
print('AUCROC Stage1 vs Healthy: ' , roc_auc)
import matplotlib.pyplot as plt
plt.title('Receiver Operating Characteristic')
plt.plot(fpr, tpr, 'b', label = 'AUC = %0.2f' % roc_... | _____no_output_____ | MIT | classification/notebooks/.ipynb_checkpoints/05 - Validation Measures-checkpoint.ipynb | pshn111/Machine-Learning-Package |
**_Privacy and Confidentiality Exercises_** This notebook shows you how to prepare your results for export and what you have to keep in mind in general when you want to export output. You will learn how to prepare files for export so they meet our export requirements. | # Load packages
%pylab inline
from __future__ import print_function
import os
import pandas as pd
import numpy as np
import psycopg2
import matplotlib.pyplot as plt
%matplotlib inline
matplotlib.style.use('ggplot') | _____no_output_____ | CC0-1.0 | notebooks_business_vitality/week_2/9_1_Disclosure_Review.ipynb | Coleridge-Initiative/ada-2018-uchicago |
General Remarks on Disclosure ReviewThis notebook provides you with information on how to prepare research output for disclosure control. It outlines how to prepare different kind of outputs before submitting an export request and gives you an overview of the information needed for disclosure review. Files you can ex... | # get working directory
mypath = (os.getcwd())
print(mypath)
# connect to database
db_name = "appliedda"
hostname = "10.10.2.10"
conn = psycopg2.connect(database=db_name, host = hostname) | _____no_output_____ | CC0-1.0 | notebooks_business_vitality/week_2/9_1_Disclosure_Review.ipynb | Coleridge-Initiative/ada-2018-uchicago |
pull dataIn this example we will use the workers who had a job in both MO and IL at some point over the course of our datasets (2005-2016) | # Get data
query = """
SELECT *, il_wage + mo_wage AS earnings
FROM ada_18_uchi.il_mo_overlap_by_qtr
WHERE year = 2011
AND quarter IN (2,3)"""
# Save query in dataframe
df = pd.read_sql( query, con = conn )
# Check dataframe
df.head()
# another way to check dataframe
df.info()
# basic stats of
df.describe()
# let's ad... | _____no_output_____ | CC0-1.0 | notebooks_business_vitality/week_2/9_1_Disclosure_Review.ipynb | Coleridge-Initiative/ada-2018-uchicago |
We now have loaded the data that we need to generate some basic statistics about our populations we want to compare | # Let's look at some first desccriptives by group
grouped = df.groupby('earn_cat')
grouped.describe()
grouped.describe().T | _____no_output_____ | CC0-1.0 | notebooks_business_vitality/week_2/9_1_Disclosure_Review.ipynb | Coleridge-Initiative/ada-2018-uchicago |
Statistics in this table will be released if the statistic is based on at least 10 entities (in this example individuals). We can see that the total number of individuals we observe in each group completely satisfies this (see cell count). However, we also report percentiles, and we report the minimum and maximum value... | # Now let's export the statistics. Ideally we want to have a csv file
# We can safe the statistics in a dataframe
export1 = grouped.describe()
# and then print to csv
export1.to_csv('descriptives_by_group.csv') | _____no_output_____ | CC0-1.0 | notebooks_business_vitality/week_2/9_1_Disclosure_Review.ipynb | Coleridge-Initiative/ada-2018-uchicago |
Reminder: Export of StatisticsYou can save any dataframe as a csv file and export this csv file. The only thing you have to keep in mind is that besides the statistic X you are interested in you have to include a variable count of X so we can see on how many observations the statistic is based on. This also applies if... | df[['il_flag', 'mo_flag']].describe(percentiles = [.5, .9, .99, .999])
# for this example let's cap the job counts to 5
df['il_flag'] = df['il_flag'].apply(lambda x: x if x < 5 else 5)
df['mo_flag'] = df['mo_flag'].apply(lambda x: x if x < 5 else 5)
# Let's say we are interested in plotting parts of the crosstabulation... | _____no_output_____ | CC0-1.0 | notebooks_business_vitality/week_2/9_1_Disclosure_Review.ipynb | Coleridge-Initiative/ada-2018-uchicago |
In this graph it is not clearly visible how many observations are in each bar. Thus we either have to provide a corresponding table (as we generated earlier), or we can use the table=True option to add a table of counts to the graph. In addition, we wnat to make sure that all our axes and legend are labeled properly. | # Graphical representation including underlying values: the option table=True displays the underlying counts
mygraph = graph.unstack().plot(kind='bar', table=True, figsize=(7,5), fontsize=7)
# Adjust legend and axes
mygraph.legend(["Unknown","1", "2", "3", "4", '5'], loc = 1, ncol= 3, fontsize=9)
mygraph.set_ylabel("Nu... | _____no_output_____ | CC0-1.0 | notebooks_business_vitality/week_2/9_1_Disclosure_Review.ipynb | Coleridge-Initiative/ada-2018-uchicago |
> in this example there is a problematic value, we will instead cap to 4 maximum jobs to ensure all cells are more than 10 | # for this example let's cap the job counts to 5
df['il_flag'] = df['il_flag'].apply(lambda x: x if x < 4 else 4)
df['mo_flag'] = df['mo_flag'].apply(lambda x: x if x < 4 else 4)
# create our new "graph" dataframe to plot with
graph = df.groupby(['earn_cat', 'il_flag'])['ssn'].count()
# confirm we solved the issue
myg... | _____no_output_____ | CC0-1.0 | notebooks_business_vitality/week_2/9_1_Disclosure_Review.ipynb | Coleridge-Initiative/ada-2018-uchicago |
Generate Balanced Training Data | training_datapath = '../random_forest_ranking/training_data_dwd.csv'
final_list = []
for i,file in enumerate(glob.glob(train_candidate_path + '*.csv')):
file_name = file.split('/')[-1]
print(file_name)
try:
d_sample = pd.read_csv(file)
grouped_obj = d_sample.groupby(['row', 'column'])
... | _____no_output_____ | MIT | t2dv2-candidate-feature-model_training/table-linker-t2dv2-candidate-feature-model_training.ipynb | nicklein/table-linker-pipelines |
Data Exploration | train_datapath = '../random_forest_ranking/training_data_dwd.csv'
df = pd.read_csv(train_datapath)
df.info()
# Features we need to include in training
features = ['pagerank','retrieval_score','monge_elkan',
'des_cont_jaccard','jaro_winkler','graph-embedding-score',
'singleton','num_char','num_tok... | <class 'pandas.core.frame.DataFrame'>
RangeIndex: 48365 entries, 0 to 48364
Data columns (total 10 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 pagerank 48365 non-null float64
1 retrieval_score 48365 non-null float64
2 ... | MIT | t2dv2-candidate-feature-model_training/table-linker-t2dv2-candidate-feature-model_training.ipynb | nicklein/table-linker-pipelines |
Train a Random Forest Regressor | train_data = df[features]
y_label = df[evaluation_label]
model = RandomForestRegressor(n_estimators=100, max_features="log2",min_samples_leaf=3)
model.fit(train_data,y_label)
y_pred = model.predict(train_data)
mean_squared_error(y_label, y_pred)
model_save_path = '../random_forest_ranking/rf_tuned_dwd_ranking.pkl'
pic... | _____no_output_____ | MIT | t2dv2-candidate-feature-model_training/table-linker-t2dv2-candidate-feature-model_training.ipynb | nicklein/table-linker-pipelines |
Predicting Scores for Train set | train_candidate_path = '/Users/rijulvohra/Documents/work/Novartis-ISI/novartis-isi-git/entity_linking/t2dv2-raw/t2dv2/canonical-with-context/t2dv2-train-candidates-dwd-v2/'
train_pred_output = '/Users/rijulvohra/Documents/work/Novartis-ISI/novartis-isi-git/entity_linking/t2dv2-raw/t2dv2/canonical-with-context/t2dv2-tra... | Train MSE is: 0.4519201624197591
| MIT | t2dv2-candidate-feature-model_training/table-linker-t2dv2-candidate-feature-model_training.ipynb | nicklein/table-linker-pipelines |
Predicting Scores for dev set | dev_candidate_path = '/Users/rijulvohra/Documents/work/Novartis-ISI/novartis-isi-git/entity_linking/t2dv2-raw/t2dv2/canonical-with-context/t2dv2-dev-candidates-dwd-v2/'
dev_pred_output = '/Users/rijulvohra/Documents/work/Novartis-ISI/novartis-isi-git/entity_linking/t2dv2-raw/t2dv2/canonical-with-context/t2dv2-dev-rf-pr... | Dev MSE is: 0.40129949369858403
| MIT | t2dv2-candidate-feature-model_training/table-linker-t2dv2-candidate-feature-model_training.ipynb | nicklein/table-linker-pipelines |
Evaluation | final_score_path = dev_pred_output
import os
eval_file_names = []
for (dirpath, dirnames, filenames) in os.walk(final_score_path):
for fn in filenames:
if "csv" not in fn:
continue
abs_fn = dirpath + fn
assert os.path.isfile(abs_fn)
if os.path.getsize(abs_fn) == 0:
... | _____no_output_____ | MIT | t2dv2-candidate-feature-model_training/table-linker-t2dv2-candidate-feature-model_training.ipynb | nicklein/table-linker-pipelines |
Logistic Regression with Hyperparameter Optimization (scikit-learn) Imports | import warnings
from sklearn.exceptions import ConvergenceWarning
warnings.filterwarnings("ignore", category=ConvergenceWarning)
import itertools
import time
import numpy as np
import pandas as pd
from sklearn import model_selection
from sklearn import linear_model
from sklearn import metrics | _____no_output_____ | Apache-2.0 | client/workflows/examples-without-verta/notebooks/sklearn-census.ipynb | conradoverta/modeldb |
--- Prepare Data | try:
import wget
except ImportError:
!pip install wget # you may need pip3
import wget
train_data_url = "http://s3.amazonaws.com/verta-starter/census-train.csv"
train_data_filename = wget.download(train_data_url)
test_data_url = "http://s3.amazonaws.com/verta-starter/census-test.csv"
test_data_filename = wg... | _____no_output_____ | Apache-2.0 | client/workflows/examples-without-verta/notebooks/sklearn-census.ipynb | conradoverta/modeldb |
Prepare Hyperparameters | hyperparam_candidates = {
'C': [1e-4, 1e-1, 1, 10, 1e3],
'solver': ['liblinear', 'lbfgs'],
'max_iter': [15, 28],
}
# total models 20
# create hyperparam combinations
hyperparam_sets = [dict(zip(hyperparam_candidates.keys(), values))
for values
in itertools.product(*hy... | _____no_output_____ | Apache-2.0 | client/workflows/examples-without-verta/notebooks/sklearn-census.ipynb | conradoverta/modeldb |
Run Validation | # create validation split
(X_val_train, X_val_test,
y_val_train, y_val_test) = model_selection.train_test_split(X_train, y_train,
test_size=0.2,
shuffle=True)
def run_experiment(hyperparams):
... | _____no_output_____ | Apache-2.0 | client/workflows/examples-without-verta/notebooks/sklearn-census.ipynb | conradoverta/modeldb |
Pick the best hyperparameters and train the full data | best_hyperparams = {}
model = linear_model.LogisticRegression(multi_class='auto', **best_hyperparams)
model.fit(X_train, y_train) | _____no_output_____ | Apache-2.0 | client/workflows/examples-without-verta/notebooks/sklearn-census.ipynb | conradoverta/modeldb |
Calculate Accuracy on Full Training Set | train_acc = model.score(X_train, y_train)
print("Training accuracy: {:.4f}".format(train_acc)) | _____no_output_____ | Apache-2.0 | client/workflows/examples-without-verta/notebooks/sklearn-census.ipynb | conradoverta/modeldb |
After downloading, install unrar on your computer$ sudo apt-get install unrarUnrar data | import os
path2data = "../../../data"
sub_folder = "hmdb51_org"
sub_folder_jpg = "hmdb51_jpg"
path2aCatgs = os.path.join(path2data, sub_folder)
listOfCategories = os.listdir(path2aCatgs)
listOfCategories, len(listOfCategories)
for cat in listOfCategories:
print("category:", cat)
path2acat = os.path.join(path2... | ../../../data/hmdb51_jpg/kick/50_FIRST_DATES_kick_f_cm_np1_ba_med_19
../../../data/hmdb51_jpg/kick/American_History_X_kick_f_nm_np1_le_bad_37
../../../data/hmdb51_jpg/kick/American_History_X_kick_l_cm_np1_le_med_33
../../../data/hmdb51_jpg/kick/Best_fight_scene_in_history_of_movie_kick_f_cm_np2_ba_bad_2
../../../data/h... | MIT | Chapter10/prepare_data.ipynb | kwhkim/PyTorch-Computer-Vision-Cookbook |
Other widget librariesWe would have loved to show you everything the Jupyter Widgets ecosystem has to offer today, but we are blessed to have such an active community of widget creators and unfortunately can't fit all widgets in a single session, no matter how long. This notebook lists some of the widget libraries we ... | from ipywidgets import Text, HTML, HBox
from ipyleaflet import GeoJSON, WidgetControl, Map
import json
m = Map(center = (43,-100), zoom = 4)
geo_json_data = json.load(open('us-states-density-colored.json'))
geojson = GeoJSON(data=geo_json_data, hover_style={'color': 'black', 'dashArray': '5, 5', 'weight': 2})
m.add_l... | _____no_output_____ | BSD-3-Clause | notebooks/07.More-libraries/07.05-other-widget-libraries.ipynb | datalayer-contrib/ipywidgets-tutorial |
pythreejs: 3D rendering in the browser A Jupyter - threejs bridge https://github.com/jupyter-widgets/pythreejsPythreejs is a jupyter interactive widget bringing fast WebGL 3d visualization to the Jupyter notebook.- Originally authored by Jason Grout, currently maintained by Vidar Tonaas Fauske- BSD LicensedPythreejs ... | from pythreejs import *
import numpy as np
from IPython.display import display
from ipywidgets import HTML, Text, Output, VBox
from traitlets import link, dlink
# Generate surface data:
view_width = 600
view_height = 400
nx, ny = (20, 20)
xmax=1
x = np.linspace(-xmax, xmax, nx)
y = np.linspace(-xmax, xmax, ny)
xx, yy =... | _____no_output_____ | BSD-3-Clause | notebooks/07.More-libraries/07.05-other-widget-libraries.ipynb | datalayer-contrib/ipywidgets-tutorial |
bqplot: complex interactive visualizations https://github.com/bloomberg/bqplot A Jupyter - d3.js bridgebqplot is a jupyter interactive widget library bringing d3.js visualization to the Jupyter notebook.- Apache Licensedbqplot implements the abstractions of Wilkinson’s “The Grammar of Graphics” as interactive Jupyter ... | import numpy as np
import bqplot as bq
xs = bq.LinearScale()
ys = bq.LinearScale()
x = np.arange(100)
y = np.cumsum(np.random.randn(2, 100), axis=1) #two random walks
line = bq.Lines(x=x, y=y, scales={'x': xs, 'y': ys}, colors=['red', 'green'])
xax = bq.Axis(scale=xs, label='x', grid_lines='solid')
yax = bq.Axis(scale... | _____no_output_____ | BSD-3-Clause | notebooks/07.More-libraries/07.05-other-widget-libraries.ipynb | datalayer-contrib/ipywidgets-tutorial |
ipympl: The Matplotlib Jupyter Widget Backend https://github.com/matplotlib/ipymplEnabling interaction with matplotlib charts in the Jupyter notebook and JupyterLab- BSD-3-Clause**Installation:**```bashconda install -c conda-forge ipympl``` Enabling the `widget` backend. This requires ipympl. ipympl can be install via... | %matplotlib widget
import numpy as np
import matplotlib.pyplot as plt
from ipywidgets import VBox, FloatSlider | _____no_output_____ | BSD-3-Clause | notebooks/07.More-libraries/07.05-other-widget-libraries.ipynb | datalayer-contrib/ipywidgets-tutorial |
When using the `widget` backend from ipympl, fig.canvas is a proper Jupyter interactive widget, which can be embedded in Layout classes like HBox and Vbox.One can bound figure attributes to other widget values. | plt.ioff()
plt.clf()
slider = FloatSlider(
value=1.0,
min=0.02,
max=2.0
)
fig1 = plt.figure(1)
x1 = np.linspace(0, 20, 500)
lines = plt.plot(x1, np.sin(slider.value * x1))
def update_lines(change):
lines[0].set_data(x1, np.sin(change.new * x1))
fig1.canvas.draw()
fig1.canvas.flush_events()... | _____no_output_____ | BSD-3-Clause | notebooks/07.More-libraries/07.05-other-widget-libraries.ipynb | datalayer-contrib/ipywidgets-tutorial |
ipytree: Interactive tree view based on ipywidgets https://github.com/QuantStack/ipytree/ipytree is a jupyter interactive widget library which provides a tree widget to the Jupyter notebook.- MIT Licensed**Installation:**```bashconda install -c conda-forge ipytree``` Create a tree | from ipywidgets import Text, link
from ipytree import Tree, Node
tree = Tree()
tree.add_node(Node('node1'))
node2 = Node('node2')
tree.add_node(node2)
tree
node3 = Node('node3', disabled=True)
node4 = Node('node4')
node5 = Node('node5', [Node('1'), Node('2')])
node2.add_node(node3)
node2.add_node(node4)
node2.add_nod... | _____no_output_____ | BSD-3-Clause | notebooks/07.More-libraries/07.05-other-widget-libraries.ipynb | datalayer-contrib/ipywidgets-tutorial |
[Schema](Schema.ipynb) [JSON-LD en linked data](json-ld-linked-data.ipynb) JSON-schemaMet JSON-schema kun je schema's voor JSON-objecten maken.Deze kun je gebruiken als documentatie van JSON-objecten die bijvoorbeeld in een web-API gebruikt worden.Vervolgens kun je JSON-objecten valideren tegen een schema.Dit kan han... | contact_schema = {
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "Contact",
"description": "schema for documents in the contacts collection",
"type": "object",
"properties": {
"name": {"type": "string"},
"email": {"type": "string"},
"telephone": {"type": "str... | _____no_output_____ | MIT | json-schema.ipynb | eelcodijkstra/mongodb-binder |
JSON-schema in PythonJe kunt in Python een schema definiëren als een Python dictionary.(Dit is vrijwel dezelfde notatie als JSON.)De libraries `jsonschema` (https://python-jsonschema.readthedocs.io) en `fastjsonschema` geven je functies om JSON-objecten te valideren tegen een schema. | from jsonschema import validate
mycontact = {
"name": "Harry van Doorn",
"email": "harryvdoorm@friendmail.org",
"tel": "06-1357 8642"
}
validate(instance=mycontact, schema=contact_schema) | _____no_output_____ | MIT | json-schema.ipynb | eelcodijkstra/mongodb-binder |
* Verbeter `mycontact` en valideer opnieuw. ArraysAls we meerdere e-mailadressen toestaan dan kunnen we daarvan een `array` maken: | contact_schema_1 = {
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "Contact",
"description": "schema for documents in the contacts collection",
"type": "object",
"properties": {
"name": {"type": "string"},
"email": {"type": "array",
"items": {"type... | _____no_output_____ | MIT | json-schema.ipynb | eelcodijkstra/mongodb-binder |
* Verbeter het veld `email` door daar een array van te maken, en valideer opnieuw. AlternatievenIn een contact moeten we tenminste een e-mailadres opnemen of een telefoonnummer, beide is niet verplicht.We gebruiken hiervoor het keyword `anyOf`, met een lijst van alternatieven. | contact_schema_2 = {
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "Contact",
"description": "schema for documents in the contacts collection",
"type": "object",
"required": ["name"],
"properties": {
"name": {"type": "string"}
},
"a... | _____no_output_____ | MIT | json-schema.ipynb | eelcodijkstra/mongodb-binder |
Load Data | def mnist_data():
compose = transforms.Compose(
[transforms.ToTensor(),
transforms.Normalize((.5, .5, .5), (.5, .5, .5))
])
out_dir = '{}/dataset'.format(DATA_FOLDER)
return datasets.MNIST(root=out_dir, train=True, transform=compose, download=True)
# Load data
data = mnist_data()
# ... | _____no_output_____ | MIT | 1. Vanilla GAN TensorFlow.ipynb | HarshRangwala/ML-Competitions |
Initialize Graph | ## Discriminator
# Input
X = tf.placeholder(tf.float32, shape=(None, IMAGE_PIXELS))
# Layer 1 Variables
D_W1 = tf.Variable(xavier_init([784, 1024]))
D_B1 = tf.Variable(xavier_init([1024]))
# Layer 2 Variables
D_W2 = tf.Variable(xavier_init([1024, 512]))
D_B2 = tf.Variable(xavier_init([512]))
# Layer 3 Variables
D_W... | _____no_output_____ | MIT | 1. Vanilla GAN TensorFlow.ipynb | HarshRangwala/ML-Competitions |
Train Testing | num_test_samples = 16
test_noise = noise(num_test_samples, NOISE_SIZE) | _____no_output_____ | MIT | 1. Vanilla GAN TensorFlow.ipynb | HarshRangwala/ML-Competitions |
Inits | num_epochs = 200
# Start interactive session
session = tf.InteractiveSession()
# Init Variables
tf.global_variables_initializer().run()
# Init Logger
logger = Logger(model_name='DCGAN1', data_name='CIFAR10') | _____no_output_____ | MIT | 1. Vanilla GAN TensorFlow.ipynb | HarshRangwala/ML-Competitions |
Train | # Iterate through epochs
for epoch in range(num_epochs):
for n_batch, (batch,_) in enumerate(data_loader):
# 1. Train Discriminator
X_batch = images_to_vectors(batch.permute(0, 2, 3, 1).numpy())
feed_dict = {X: X_batch, Z: noise(BATCH_SIZE, NOISE_SIZE)}
_, d_error, d_pred_re... | _____no_output_____ | MIT | 1. Vanilla GAN TensorFlow.ipynb | HarshRangwala/ML-Competitions |
1. 숫자 자료형 정수 | print(123) #양의 정수
print(-321) #음의 정수
print(0) #0 | 123
-321
0
| Apache-2.0 | python/practice/1-2_basic_operations.ipynb | daludaluking/LG_AI_all_in_one- |
실수 | print(3.14)
print(314e-2) # 314 * 10의 -2승
print(0.1*0.1) | 0.010000000000000002
| Apache-2.0 | python/practice/1-2_basic_operations.ipynb | daludaluking/LG_AI_all_in_one- |
복소수 | print(1+2j)
print((1+2j).real)
print((1+2j).imag)
print((1+2j).conjugate())
print(type(3))
print(type(3.14))
print(type(1+2j)) | <class 'int'>
<class 'float'>
<class 'complex'>
| Apache-2.0 | python/practice/1-2_basic_operations.ipynb | daludaluking/LG_AI_all_in_one- |
2. 사칙연산 | print(12+3)
print(12-3)
print(12*3)
print(12/3)
print(12**3)
print(12%3)
print(12%3) | 15
9
36
4.0
1728
0
0
| Apache-2.0 | python/practice/1-2_basic_operations.ipynb | daludaluking/LG_AI_all_in_one- |
3. 연산자의 우선순위사칙연산과 똑같음 | print(12+3*4)
print((12+3)*4) | 24
60
| Apache-2.0 | python/practice/1-2_basic_operations.ipynb | daludaluking/LG_AI_all_in_one- |
연습문제 1 1번10의 제곱을 출력해보자 | # 정답을 적어주세요
print(10**2)
# 정답을 적어주세요 | _____no_output_____ | Apache-2.0 | python/practice/1-2_basic_operations.ipynb | daludaluking/LG_AI_all_in_one- |
2번2 x 5 + 3 과 2 x (5 + 3)을 각각 화면에 출력해보자 | # 정답을 적어주세요
print(2*5+3)
# 정답을 적어주세요
print(2*(5+3)) | 16
| Apache-2.0 | python/practice/1-2_basic_operations.ipynb | daludaluking/LG_AI_all_in_one- |
3. Assignment : =변수를 할당해주는 연산자 계산을 할때 equal sign으로도 쓰임 | a=123
print(a)
print(id(a))
stock_price = 1550
print(stock_price)
print(id(stock_price))
a=123
print(a)
print(id(a))
a=b=12345678
print(a)
print(id(a))
print(b)
print(id(b))
c=12345678
d=12345678
print(c)
print(id(c))
print(d)
print(id(d)) | 12345678
139713344318928
12345678
139713344318032
| Apache-2.0 | python/practice/1-2_basic_operations.ipynb | daludaluking/LG_AI_all_in_one- |
더 알아보기 | variable = 2
variable
variable += 1
variable
variable = variable + 1
variable
variable -= 5
variable
variable *= -1
variable
variable /= 5
variable
a = 5
b = 7
c = a + b
print(c)
c = A + B | _____no_output_____ | Apache-2.0 | python/practice/1-2_basic_operations.ipynb | daludaluking/LG_AI_all_in_one- |
연습문제 2 1번사과가 5개 오렌지가 3개 있을 때 총 과일의 갯수를 구해보자 사과는 apple이라는 변수, 오렌지는 orange라는 변수에 할당 한 후, 총 과일의 갯수를 total이라는 변수에 저장해보자 | # 정답을 적어주세요
apple = 5
orange = 3
total = apple + orange
print("total = ", total)
# 아래 주석을 풀고 실행시켜서 원하는 값이 나왔는지 확인하세요
total | _____no_output_____ | Apache-2.0 | python/practice/1-2_basic_operations.ipynb | daludaluking/LG_AI_all_in_one- |
2번국어는 100점, 영어는 88점, 수학은 94점 일 때, 평균을 구하려고 한다. 각각의 점수를 kor, eng, math라는 변수에 저장한 후 평균을 구해 avg라는 변수에 할당해보자. | # 정답을 적어주세요
kor = 100
eng = 88
math = 94
avg = (kor + eng + math) / 3
# 아래 주석을 풀고 실행시켜서 원하는 값이 나왔는지 확인하세요
avg | _____no_output_____ | Apache-2.0 | python/practice/1-2_basic_operations.ipynb | daludaluking/LG_AI_all_in_one- |
基本程序设计- 一切代码输入,请使用英文输入法 | print('hello world') | hello world
| Apache-2.0 | 9.10.ipynb | ningjing957/zuoye |
编写一个简单的程序- 圆公式面积: area = radius \* radius \* 3.1415 | radius = int(input('请输入一个半径:'))
area = radius * radius * 3.1433223
print(area) | 请输入一个半径:2
12.5732892
| Apache-2.0 | 9.10.ipynb | ningjing957/zuoye |
在Python里面不需要定义数据的类型 控制台的读取与输入- input 输入进去的是字符串- eval - 在jupyter用shift + tab 键可以跳出解释文档 变量命名的规范- 由字母、数字、下划线构成- 不能以数字开头 \*- 标识符不能是关键词(实际上是可以强制改变的,但是对于代码规范而言是极其不适合)- 可以是任意长度- 驼峰式命名 变量、赋值语句和赋值表达式- 变量: 通俗理解为可以变化的量- x = 2 \* x + 1 在数学中是一个方程,而在语言中它是一个表达式- test = test + 1 \* 变量在赋值之前必须有值 同时赋值var1, var2,var3... = exp1,exp2,e... | 25/4
25//4
num = int(input('请输入一个整数:'))
if num%2==0:
print('该数为偶数')
else:
print('该数为奇数')
s = eval(input('请输入一个秒数:'))
min = s//60
s1 = s%60
print (str(min)+'分'+str(s1)+'秒') | 请输入一个秒数:500
8分20秒
| Apache-2.0 | 9.10.ipynb | ningjing957/zuoye |
科学计数法- 1.234e+2- 1.234e-2 计算表达式和运算优先级 增强型赋值运算 类型转换- float -> int- 四舍五入 round EP:- 如果一个年营业税为0.06%,那么对于197.55e+2的年收入,需要交税为多少?(结果保留2为小数)- 必须使用科学计数法 Project- 用Python写一个贷款计算器程序:输入的是月供(monthlyPayment) 输出的是总还款数(totalpayment) Homework- 1 | celsius = eval(input('请输入一个温度:'))
fahrenheit = (9/5)*celsius+32
print (fahrenheit) | 请输入一个温度:43
109.4
| Apache-2.0 | 9.10.ipynb | ningjing957/zuoye |
- 2 | import math
radius = eval(input('请输入一个半径:'))
length = eval(input('请输入一个高:'))
area = radius*radius*math.pi
volume = area*length
print (round(area,1))
print (round(volume,1)) | 请输入一个半径:5.5
请输入一个高:12
95.0
1140.4
| Apache-2.0 | 9.10.ipynb | ningjing957/zuoye |
- 3 | feet = eval(input('请输入一个英尺数:'))
meters = feet*0.305
print (meters) | 请输入一个英尺数:16.5
5.0325
| Apache-2.0 | 9.10.ipynb | ningjing957/zuoye |
- 4 | M = eval(input('请输入以kg为单位的水的质量:'))
initialTemperature = eval(input('请输入水的初始温度:'))
finalTemperature = eval(input('请输入水的最终温度:'))
Q = M*(finalTemperature-initialTemperature)*4184
print (Q) | 请输入以kg为单位的水的质量:55.5
请输入水的初始温度:3.5
请输入水的最终温度:10.5
1625484.0
| Apache-2.0 | 9.10.ipynb | ningjing957/zuoye |
- 5 | balance = eval(input('请输入差额:'))
rate = eval(input('请输入年利率:'))
interest = (balance*(rate/1200))
print (interest) | 请输入差额:1000
请输入年利率:3.5
2.916666666666667
| Apache-2.0 | 9.10.ipynb | ningjing957/zuoye |
- 6 | v0 = eval(input('请输入初速度:'))
v1 = eval(input('请输入末速度:'))
t = eval(input('以秒为单位速度变化所占用的时间:'))
a = (v1-v0)/t
print (a) | 请输入初速度:5.5
请输入末速度:50.9
以秒为单位速度变化所占用的时间:4.5
10.088888888888889
| Apache-2.0 | 9.10.ipynb | ningjing957/zuoye |
- 7 进阶 | money = eval(input('请输入每月的存钱数:'))
one = money*(1+0.00417)
two = (money+one)*(1+0.00417)
three = (money+two)*(1+0.00417)
four = (money+three)*(1+0.00417)
five = (money+four)*(1+0.00417)
six = (money+five)*(1+0.00417)
print (round(six,2)) | 请输入每月的存钱数:100
608.82
| Apache-2.0 | 9.10.ipynb | ningjing957/zuoye |
- 8 进阶 | num = eval(input('请输入一个0到1000的整数:'))
a = num%10
b = num//10
c = b%10
d = b//10
print (a+c+d) | 请输入一个0到1000的整数:152
8
| Apache-2.0 | 9.10.ipynb | ningjing957/zuoye |
Import Required Packages | # Imports
import os
import datetime
import glob
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import time
| _____no_output_____ | ISC | base/auxils/plotting_tool/CurtailmentHourly.ipynb | juanjerezm/Balmorel_code |
Input data from User | #Market analysed: 'Investment','FullYear','DayAhead','Balancing' (choose one or several)
market_analysed=['DayAhead','Balancing']
output='CurtailmentHourly'
first_timestep="2012-01-02"
#Number of timesteps (total number of combination of SSS and TTT)
number_periods=8736*12
#Time size of each time step for creating ti... | _____no_output_____ | ISC | base/auxils/plotting_tool/CurtailmentHourly.ipynb | juanjerezm/Balmorel_code |
Plot Settings | # Set plotting specifications
% matplotlib inline
plt.rcParams.update({'font.size': 21})
plt.rcParams['xtick.major.pad']='12'
plt.rc('legend', fontsize=16)
y_limit = 1.1
lw = 3 | _____no_output_____ | ISC | base/auxils/plotting_tool/CurtailmentHourly.ipynb | juanjerezm/Balmorel_code |
Read Input Files | data=pd.DataFrame()
for market in market_analysed:
csvfiles = []
for file in glob.glob("./input/results/" + market + "/*.csv"):
csvfiles.append(file)
csvfiles=[file.replace('./input\\','') for file in csvfiles]
csvfiles=[file.replace('.csv','') for file in csvfiles]
csvfiles=[file.split(... | _____no_output_____ | ISC | base/auxils/plotting_tool/CurtailmentHourly.ipynb | juanjerezm/Balmorel_code |
Additional set declaration | ccc = list(data.CCC.unique())
rrr = list(data.RRR.unique())
tech_type = list(data.TECH_TYPE.unique())
commodity = list(data.COMMODITY.unique())
fff = list(data.FFF.unique())
sss = list(full_timesteps.SSS.unique())
ttt = list(full_timesteps.TTT.unique())
| _____no_output_____ | ISC | base/auxils/plotting_tool/CurtailmentHourly.ipynb | juanjerezm/Balmorel_code |
Time step selection | # Seasons to investigate
# season_names = ['S01', 'S07', 'S20', 'S24', 'S28', 'S38', 'S42', 'S43']
# Make a list of every nth element of sss (1 <= nth <= number of elements in sss)
nth = 1
s = sss[0::nth]
# Or select seasons by names
# s = season_names
# Terms to investigate
# term_names = ['T005', 'T019', 'T033', 'T... | _____no_output_____ | ISC | base/auxils/plotting_tool/CurtailmentHourly.ipynb | juanjerezm/Balmorel_code |
Make Directories | # Make output folder
if not os.path.isdir('output'):
os.makedirs('output')
# Make CurtailmentHourly folder
if not os.path.isdir('output/' + output):
os.makedirs('output/' + output)
# Make market folder
for market in market_analysed:
if not os.path.isdir('output/' + output + '/'+ market +'/Country_wise'):
... | _____no_output_____ | ISC | base/auxils/plotting_tool/CurtailmentHourly.ipynb | juanjerezm/Balmorel_code |
Plotting | # Make data frames to plot
data_plot = data[(data.SSS.isin(s)) & (data.TTT.isin(t))]
data_plot = data[data.CCC.isin(ccc_in_focus)] | _____no_output_____ | ISC | base/auxils/plotting_tool/CurtailmentHourly.ipynb | juanjerezm/Balmorel_code |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.