markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
Examining the survival statistics, the majority of males younger than 10 survived the ship sinking, whereas most males age 10 or older did not survive the ship sinking. Let's continue to build on our previous prediction: If a passenger was female, then we will predict they survive. If a passenger was male and younger t...
def predictions_2(data): """ Model with two features: - Predict a passenger survived if they are female. - Predict a passenger survived if they are male and younger than 10. """ predictions = [] for _, passenger in data.iterrows(): # Remove the 'pass' statement...
udacity/working_titanic_survival_exploration/Titanic_Survival_Exploration.ipynb
harish-garg/Machine-Learning
mit
Answer: 79.35% Adding the feature Age as a condition in conjunction with Sex improves the accuracy by a small margin more than with simply using the feature Sex alone. Now it's your turn: Find a series of features and conditions to split the data on to obtain an outcome prediction accuracy of at least 80%. This may re...
survival_stats(data, outcomes, 'Age', ["Sex == 'male'", "SibSp == 1"])
udacity/working_titanic_survival_exploration/Titanic_Survival_Exploration.ipynb
harish-garg/Machine-Learning
mit
After exploring the survival statistics visualization, fill in the missing code below so that the function will make your prediction. Make sure to keep track of the various features and conditions you tried before arriving at your final prediction model. Hint: You can start your implementation of this function using th...
def predictions_3(data): """ Model with multiple features. Makes a prediction with an accuracy of at least 80%. """ predictions = [] for _, passenger in data.iterrows(): # Remove the 'pass' statement below # and write your prediction conditions here if passenger['Sex']...
udacity/working_titanic_survival_exploration/Titanic_Survival_Exploration.ipynb
harish-garg/Machine-Learning
mit
When iteratively removing weak features the choice of model is important. We will discuss the different models available for regression and classification next week but there are a few points relevant to feature selection we will cover here. A linear model is a useful and easily interpreted model, and when used for fea...
from sklearn import linear_model from sklearn.datasets import load_digits from sklearn.feature_selection import RFE # Load the digits dataset digits = load_digits() X = digits.images.reshape((len(digits.images), -1)) y = digits.target # Create the RFE object and rank each pixel clf = linear_model.LogisticRegression(...
Wk10/Wk10-dimensionality-reduction-clustering.ipynb
briennakh/BIOF509
mit
Exercises Apply feature selection to the Olivetti faces dataset, identifying the most important 25% of features. Apply PCA and LDA to the digits dataset used above Clustering In clustering we attempt to group observations in such a way that observations assigned to the same cluster are more similar to each other than...
import matplotlib import matplotlib.pyplot as plt from skimage.data import camera from skimage.filters import threshold_otsu matplotlib.rcParams['font.size'] = 9 image = camera() thresh = threshold_otsu(image) binary = image > thresh #fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(8, 2.5)) fig = plt.figure(fi...
Wk10/Wk10-dimensionality-reduction-clustering.ipynb
briennakh/BIOF509
mit
Different clustering algorithms Cluster comparison The following algorithms are provided by scikit-learn K-means Affinity propagation Mean Shift Spectral clustering Ward Agglomerative Clustering DBSCAN Birch K-means clustering divides samples between clusters by attempting to minimize the within-cluster sum of squar...
from sklearn import cluster, datasets dataset, true_labels = datasets.make_blobs(n_samples=200, n_features=2, random_state=0, centers=3, cluster_std=0.1) fig, ax = plt.subplots(1,1) ax.scatter(dataset[:,0], dataset[:,1], c=true_labels) plt.show() # Clustering algorithm can ...
Wk10/Wk10-dimensionality-reduction-clustering.ipynb
briennakh/BIOF509
mit
Since month in dimple only except 2 digit format, change this
df['month'] = df['month'].map(lambda x: '0' + str(x) if len(str(x)) < 2 else x) df.month.unique()
p6-datviz/analysis.ipynb
napjon/ds-nd
mit
We want to have total number of operations and total minutes delay. So we're going to aggregate it per month.
agg_month_sum = df.groupby('month',as_index=False).sum() not_ontime_flights = ['arr_cancelled','arr_diverted','arr_del15'] agg_month_sum['on_time_flights'] = agg_month_sum['arr_flights'] - agg_month_sum[not_ontime_flights].sum(axis=1) delayed_columns = agg_month_sum.columns[agg_month_sum.columns.str.endswith('_delay'...
p6-datviz/analysis.ipynb
napjon/ds-nd
mit
At this point in time, the model is still empty
print('%i reactions in initial model' % len(cobra_model.reactions)) print('%i metabolites in initial model' % len(cobra_model.metabolites)) print('%i genes in initial model' % len(cobra_model.genes))
documentation_builder/building_model.ipynb
jerkos/cobrapy
lgpl-2.1
We will add the reaction to the model, which will also add all associated metabolites and genes
cobra_model.add_reaction(reaction) # Now there are things in the model print('%i reaction in model' % len(cobra_model.reactions)) print('%i metabolites in model' % len(cobra_model.metabolites)) print('%i genes in model' % len(cobra_model.genes))
documentation_builder/building_model.ipynb
jerkos/cobrapy
lgpl-2.1
We can iterate through the model objects to observe the contents
# Iterate through the the objects in the model print("Reactions") print("---------") for x in cobra_model.reactions: print("%s : %s" % (x.id, x.reaction)) print("Metabolites") print("-----------") for x in cobra_model.metabolites: print('%s : %s' % (x.id, x.formula)) print("Genes") print("-----") for x in cobra...
documentation_builder/building_model.ipynb
jerkos/cobrapy
lgpl-2.1
TODO: Examine all the reviews. For each word in a positive review, increase the count for that word in both your positive counter and the total words counter; likewise, for each word in a negative review, increase the count for that word in both your negative counter and the total words counter. Note: Throughout these ...
# TODO: Loop over all the words in all the reviews and increment the counts in the appropriate counter objects for i,r in enumerate(reviews): words = r.split(' ') positive = labels[i] == 'POSITIVE' for w in words: if positive: positive_counts[w] += 1 else: negative_co...
sentiment-network/Sentiment_Classification_Projects.ipynb
marko911/deep-learning
mit
As you can see, common words like "the" appear very often in both positive and negative reviews. Instead of finding the most common words in positive or negative reviews, what you really want are the words found in positive reviews more often than in negative reviews, and vice versa. To accomplish this, you'll need to ...
# Create Counter object to store positive/negative ratios pos_neg_ratios = Counter() # TODO: Calculate the ratios of positive and negative uses of the most common words # Consider words to be "common" if they've been used at least 100 times for w in list(total_counts): pos_neg_ratios[w] = positive_counts[w] ...
sentiment-network/Sentiment_Classification_Projects.ipynb
marko911/deep-learning
mit
Looking closely at the values you just calculated, we see the following: Words that you would expect to see more often in positive reviews – like "amazing" – have a ratio greater than 1. The more skewed a word is toward postive, the farther from 1 its positive-to-negative ratio will be. Words that you would expect to...
# TODO: Convert ratios to logs for w,ratio in pos_neg_ratios.items(): if ratio <1: pos_neg_ratios[w] = -np.log(1/(ratio+0.01)) elif ratio >1: pos_neg_ratios[w] = np.log(ratio)
sentiment-network/Sentiment_Classification_Projects.ipynb
marko911/deep-learning
mit
TODO: Complete the implementation of update_input_layer. It should count how many times each word is used in the given review, and then store those counts at the appropriate indices inside layer_0.
def update_input_layer(review): """ Modify the global layer_0 to represent the vector form of review. The element at a given index of layer_0 should represent how many times the given word occurs in the review. Args: review(string) - the string of the review Returns: None """ ...
sentiment-network/Sentiment_Classification_Projects.ipynb
marko911/deep-learning
mit
End of Project 2. Watch the next video to see Andrew's solution, then continue on to the next lesson. Project 3: Building a Neural Network<a id='project_3'></a> TODO: We've included the framework of a class called SentimentNetork. Implement all of the items marked TODO in the code. These include doing the following: - ...
import time import sys import numpy as np from collections import Counter # Encapsulate our neural network in a class class SentimentNetwork: def __init__(self, reviews, labels, hidden_nodes = 10, learning_rate = 0.1): """Create a SentimenNetwork with the given settings Args: reviews(li...
sentiment-network/Sentiment_Classification_Projects.ipynb
marko911/deep-learning
mit
Now do some waveform creation:
N = 40 x = numpy.array(range(40)) data = 0.99*numpy.exp(-((x-20)/4)**2) plt.plot(data,"o-") handle.write(":DATA:POINTS VOLATILE,{}".format(N)) handle.ask(":DATA:POINTS? VOLATILE")
Rigol Arb Gen Waveform Creation.ipynb
DawesLab/Instruments
gpl-3.0
Now to reverse engineer the VCA response:
def VfromI(Intensity): """Implement the inverted response function. See data fit in google drive AOM folder.""" V = (.0039757327 + (.0039757327 ** 2 + 4 *.0078826605 * Intensity) ** (1/2))/(2*.0078826605) return V voltages = VfromI(data) floats = voltages/voltages.max() # values scaled to 0-1.0 floats han...
Rigol Arb Gen Waveform Creation.ipynb
DawesLab/Instruments
gpl-3.0
Running TPOTClassifier In the interest of time, we'll only use a 500,000 row sample of this file. 500,000 rows is more than enough for this example.
NROWS = 500_000 X_train, X_test, y_train, y_test = prepare_higgs(nrows=NROWS)
tutorials/Higgs_Boson.ipynb
weixuanfu/tpot
lgpl-3.0
Note that for cuML to work correctly, you must set n_jobs=1 (the default setting).
%%time # cuML TPOT setup SEED = 12 GENERATIONS = 10 POP_SIZE = 10 CV = 2 tpot = TPOTClassifier( generations=GENERATIONS, population_size=POP_SIZE, random_state=SEED, config_dict="TPOT cuML", n_jobs=1, # cuML requires n_jobs=1, the default cv=CV, verbosity=2, ) tpot.fit(X_train, y_train) ...
tutorials/Higgs_Boson.ipynb
weixuanfu/tpot
lgpl-3.0
Loading the data set Data in GUODA is stored on a clustered file system called HDFS. The Jupyter notebooks are all configured to read and write to HDFS automatically so all file paths are in the HDFS system. You can read more about working with files and how to see what data sets are availible on the Jupyter service wi...
df = sqlContext.read.load("/guoda/data/idigbio-20190612T171757.parquet") df.count()
01_iDigBio_Specimens_Collected_Over_Time.ipynb
bio-guoda/guoda-examples
mit
Examining the data Now that the data is in memory, let's look at some of the methods availible to examine it before we move on to summarizing it. This will let you see how data is represented both in Spark and Python as well as what kind of data is availible in the iDigBio data frames. Data frame structure First we can...
df.printSchema()
01_iDigBio_Specimens_Collected_Over_Time.ipynb
bio-guoda/guoda-examples
mit
Next we can look at the first row of data. The (1) after head tells Python how many rows to print. Since this is all iDigBio data, the rows are pretty big so we'll only show one.
df.head(1)
01_iDigBio_Specimens_Collected_Over_Time.ipynb
bio-guoda/guoda-examples
mit
Summarizing the data That's certainly more data than we need to make the graph. Since there is one row in the data frame for each specimen record, what we need to do is group the records by the year they were collected and then count the number of records in each group and associate that with the year. The data frame w...
# The outer "(" and ")" surround the chain of Python method calls to allow them to # span lines. This is a common convention and makes the data processing pipeline # easy to read and modify. # # The persist() function tells Spark to store the data frame in memory so it can be # accessed repeatedly without having to be...
01_iDigBio_Specimens_Collected_Over_Time.ipynb
bio-guoda/guoda-examples
mit
Let's take a look at this new data frame using some of the commands from above:
year_summary.count() year_summary.printSchema() year_summary.head(10)
01_iDigBio_Specimens_Collected_Over_Time.ipynb
bio-guoda/guoda-examples
mit
Now that our data is both much smaller and mostly numeric, we can use the describe() method to quickly make summary statistics. This method returns a data frame so we have to use show() to actually print the whole contents of the data frame.
year_summary.describe().show()
01_iDigBio_Specimens_Collected_Over_Time.ipynb
bio-guoda/guoda-examples
mit
Spark data frames, Pandas data frames, and filtering The term "data frame" is a concept for how data is arranged. Different programming languages and even libraries in a single programming language have different implimentations of this idea. We have been working with a Spark data frame. Now we want to do some graphing...
pandas_year_summary = (year_summary .filter(year_summary.yearcollected >= 1817) .filter(year_summary.yearcollected <= 2017) .orderBy("yearcollected") .toPandas() ) pandas_year_summary.head()
01_iDigBio_Specimens_Collected_Over_Time.ipynb
bio-guoda/guoda-examples
mit
(Notice that the display of the first rows looks different from when we ran head() on the Spark data frame? That's because we're looking at the display generated by the Pandas library instead of the Spark library.) Making a graph The number of specimens collected in a year is discrete data so a bar graph is one appropr...
plt.bar(pandas_year_summary["yearcollected"], pandas_year_summary["count"], edgecolor='none', width=1.0 ) plt.title("Specimens in iDigBio by Collection Year and Continent") plt.ylabel("Number of Specimen Records") plt.xlabel("Year")
01_iDigBio_Specimens_Collected_Over_Time.ipynb
bio-guoda/guoda-examples
mit
Variacion por cuadro de Vt del 0.0004%
%matplotlib inline import math import numpy as np import scipy as sp import matplotlib.pyplot as plt import pylab as plb def matrix(m_length,m_width): "Return matrix with no homogeneus resitivity" m = np.zeros((m_length,m_width)) return m Material_length=963e-6 scmos_process = 3.e-6 wafer_thickness = 0.05e-...
notebooks/Cmos - Transistors (variant Vt property).ipynb
jagarzone6/cmos
mit
Matriz de Vt ideal Vt_n_Ideal
Vt_n_Ideal = matrix(int(size_m),int(size_m)) for i in range(0,int(math.sqrt(Vt_n_Ideal.size))): for j in range(0,int(math.sqrt(Vt_n_Ideal.size))): Vt_n_Ideal[i][j]= Vt_n_base plt.matshow(Vt_n_Ideal) plt.show()
notebooks/Cmos - Transistors (variant Vt property).ipynb
jagarzone6/cmos
mit
Matriz de Vt ideal Vt_p_Ideal
Vt_p_Ideal = matrix(int(size_m),int(size_m)) for i in range(0,int(math.sqrt(Vt_p_Ideal.size))): for j in range(0,int(math.sqrt(Vt_p_Ideal.size))): Vt_p_Ideal[i][j]= Vt_p_base plt.matshow(Vt_p_Ideal) plt.show()
notebooks/Cmos - Transistors (variant Vt property).ipynb
jagarzone6/cmos
mit
OPCION 1 Creacion de las matrices del material con variaciones en Vt_n y Vt_p a partir de la esquina
Vt_n = matrix(int(size_m),int(size_m)) def set_corner_Vt_n(): for i in range(0,int(math.sqrt(Vt_n.size))): for j in range(0,int(math.sqrt(Vt_n.size))): Vt_n[i][j]= Vt_n_base+(i+j)*delta_Vt set_corner_Vt_n() plt.matshow(Vt_n) plt.show() Vt_p = matrix(int(size_m),int(size_m)) def set_...
notebooks/Cmos - Transistors (variant Vt property).ipynb
jagarzone6/cmos
mit
OPCION 2 Creacion de las matrices del material con variaciones en Vt_n y Vt_p del centro hacia afuera
Vt_n = matrix(int(size_m),int(size_m)) def centroid_Vt_n(center,i,j): "Return a value of Vt_n for a single shape" difJ=abs(center-j) difI=abs(center-i) xy=0 if difJ > difI: xy=difJ else: xy=difI Vtn= Vt_n_base+(xy)*delta_Vt return Vtn def set_centroid_Vt_n(): ...
notebooks/Cmos - Transistors (variant Vt property).ipynb
jagarzone6/cmos
mit
Ingrese las dimensiones LxW de los transistores
display(Image(url='images/WLCMOS.png')) W_base=2 WTA=60 WTB=60 WTC=60 WTD=60 lenght_active_si_transistor = 6 L=2 display(Image(url='images/Transistor.png')) print("W_base de 2 unidades")
notebooks/Cmos - Transistors (variant Vt property).ipynb
jagarzone6/cmos
mit
OPCION 1 de Diseño de los transistores de optimizacion de espacio con centroide comun en la oblea, para usar 2 de esos en la simulacion del espejo de corriente
paint_matrix = matrix(int(size_m),int(size_m)) common_source=9 def opcion1(): M_center=int((int(math.sqrt(paint_matrix.size))-1)/2) TA = matrix(W_base,int((WTA/W_base+1)*(lenght_active_si_transistor/2))) for i in range(M_center-2-TA.shape[0],M_center-2): for j in range(M_center-2-TA.shape[1],M_cent...
notebooks/Cmos - Transistors (variant Vt property).ipynb
jagarzone6/cmos
mit
Calculo del valor promedio de Vt para cada transistor
def prom_Vt_n_for_transistor(transistor_num): "Return a prom value of Vt_n for a single transistor in the wafer" Vtn_sum=0 Vtn_found=0 for i in range(0,int(math.sqrt(paint_matrix.size))): for j in range(0,int(math.sqrt(paint_matrix.size))): if paint_matrix[i][j] == transistor_num: ...
notebooks/Cmos - Transistors (variant Vt property).ipynb
jagarzone6/cmos
mit
Con variacion de variacion a partir de la esquina de Vt en la oblea
print("Para la opcion diseno 1: Transistores ahorro de espacio con centroide: \n") paint_matrix = matrix(int(size_m),int(size_m)) opcion1() set_corner_Vt_n() plt.matshow(Vt_n) plt.show() plt.matshow(paint_matrix) plt.show() Vtn_T1=prom_Vt_n_for_transistor(1) Vtn_T2=prom_Vt_n_for_transistor(2) Vtn_T3=prom_Vt_n_for_trans...
notebooks/Cmos - Transistors (variant Vt property).ipynb
jagarzone6/cmos
mit
Con variacion del centro hacia afuera de Vt en la oblea
print("Para la opcion diseno 1: Transistores ahorro de espacio con centroide: \n") paint_matrix = matrix(int(size_m),int(size_m)) opcion1() set_centroid_Vt_n() plt.matshow(Vt_n) plt.show() plt.matshow(paint_matrix) plt.show() Vtn_T1=prom_Vt_n_for_transistor(1) Vtn_T2=prom_Vt_n_for_transistor(2) Vtn_T3=prom_Vt_n_for_tra...
notebooks/Cmos - Transistors (variant Vt property).ipynb
jagarzone6/cmos
mit
Funcion para editar los archivo de simulacion del espejo NMOS 'espejoNmosPythonFile.cir' y el espejo P 'espejoPmosPythonFile.cir'
import sys import fileinput def modificar_cir_Espejo_NMOS(W,L,Vt_T1,Vt_T2): text="* Simulación Circuito Espejo de Corriente con Ncmos, valores reales de Kp_n y Vt"+"\n"+ \ "* Universidad Nacional de Colombia 2016"+"\n"+ \ "* CMOS Analógico"+"\n"+ \ "* Grupo Jorge Garzón, Esteban Iafrancesco A"+"\n"+ \ ...
notebooks/Cmos - Transistors (variant Vt property).ipynb
jagarzone6/cmos
mit
Espejo NMOS con variaciones de Vt_n en la oblea Simulacion con variacion desde el centro de Vt_n en la oblea y centroide comun entre 2 transistores (de los 4 disponibles) para formar el espejo de corriente.
paint_matrix = matrix(int(size_m),int(size_m)) opcion1() set_corner_Vt_n() plt.matshow(Vt_n) plt.show() plt.matshow(paint_matrix) plt.show() Vtn_T1=prom_Vt_n_for_transistor(1) Vtn_T2=prom_Vt_n_for_transistor(2) Vtn_T3=prom_Vt_n_for_transistor(3) Vtn_T4=prom_Vt_n_for_transistor(4) #modificar_cir_Espejo_NMOS(WTA,L,Vtn_T...
notebooks/Cmos - Transistors (variant Vt property).ipynb
jagarzone6/cmos
mit
Simulacion con variacion desde el centro de Vt_n en la oblea y centroide comun entre 2 transistores (de los 4 disponibles) para formar el espejo de corriente.
paint_matrix = matrix(int(size_m),int(size_m)) opcion1() set_centroid_Vt_n() plt.matshow(Vt_n) plt.show() plt.matshow(paint_matrix) plt.show() Vtn_T1=prom_Vt_n_for_transistor(1) Vtn_T2=prom_Vt_n_for_transistor(2) Vtn_T3=prom_Vt_n_for_transistor(3) Vtn_T4=prom_Vt_n_for_transistor(4) #modificar_cir_Espejo_NMOS(WTA,L,Vtn...
notebooks/Cmos - Transistors (variant Vt property).ipynb
jagarzone6/cmos
mit
Simulacion con variacion desde la esquina de Vt_n en la oblea y diseno 2 de surce compartido, centroide comun entre 2 transistores para formar el espejo de corriente.
paint_matrix = matrix(int(size_m),int(size_m)) opcion2() set_corner_Vt_n() plt.matshow(Vt_n) plt.show() plt.matshow(paint_matrix) plt.show() Vtn_T1=prom_Vt_n_for_transistor(4) Vtn_T2=prom_Vt_n_for_transistor(5) #modificar_cir_Espejo_NMOS(WTA,L,Vtn_T1,Vtn_T2) display(Image(url='images/corner_Vt_CS_n.png')) print("VDD ...
notebooks/Cmos - Transistors (variant Vt property).ipynb
jagarzone6/cmos
mit
Simulacion con variacion desde el centro de Vt_n en la oblea y diseno 2 de surce compartido, centroide comun entre 2 transistores para formar el espejo de corriente.
paint_matrix = matrix(int(size_m),int(size_m)) opcion2() set_centroid_Vt_n() plt.matshow(Vt_n) plt.show() plt.matshow(paint_matrix) plt.show() Vtn_T1=prom_Vt_n_for_transistor(4) Vtn_T2=prom_Vt_n_for_transistor(5) #modificar_cir_Espejo_NMOS(WTA,L,Vtn_T1,Vtn_T2) display(Image(url='images/center_Vt_CS_n.png')) print("VD...
notebooks/Cmos - Transistors (variant Vt property).ipynb
jagarzone6/cmos
mit
Espejo PMOS con variaciones en la oblea desde la esquina Simulacion con variacion desde la esquina de Vt_p en la oblea y centroide comun entre 2 transistores (de los 4 disponibles) para formar el espejo de corriente.
paint_matrix = matrix(int(size_m),int(size_m)) opcion1() set_corner_Vt_p() plt.matshow(Vt_p) plt.show() plt.matshow(paint_matrix) plt.show() Vtp_T1=prom_Vt_p_for_transistor(1) Vtp_T2=prom_Vt_p_for_transistor(2) Vtp_T3=prom_Vt_p_for_transistor(3) Vtp_T4=prom_Vt_p_for_transistor(4) #modificar_cir_Espejo_PMOS(WTA,L,Vtp_...
notebooks/Cmos - Transistors (variant Vt property).ipynb
jagarzone6/cmos
mit
Simulacion con variacion desde el centro de Vt_p en la oblea y centroide comun entre 2 transistores (de los 4 disponibles) para formar el espejo de corriente.
paint_matrix = matrix(int(size_m),int(size_m)) opcion1() set_centroid_Vt_p() plt.matshow(Vt_p) plt.show() plt.matshow(paint_matrix) plt.show() Vtp_T1=prom_Vt_p_for_transistor(1) Vtp_T2=prom_Vt_p_for_transistor(2) Vtp_T3=prom_Vt_p_for_transistor(3) Vtp_T4=prom_Vt_p_for_transistor(4) #modificar_cir_Espejo_PMOS(WTA,L,Vt...
notebooks/Cmos - Transistors (variant Vt property).ipynb
jagarzone6/cmos
mit
Simulacion con variacion desde la esquina de Vt_p en la oblea y diseno 2 de surce compartido, centroide comun entre 2 transistores para formar el espejo de corriente.
paint_matrix = matrix(int(size_m),int(size_m)) opcion2() set_corner_Vt_p() plt.matshow(Vt_p) plt.show() plt.matshow(paint_matrix) plt.show() Vtp_T1=prom_Vt_p_for_transistor(4) Vtp_T2=prom_Vt_p_for_transistor(5) #modificar_cir_Espejo_PMOS(WTA,L,Vtp_T1,Vtp_T2) display(Image(url='images/corner_Vt_CS_p.png')) print("VDD ...
notebooks/Cmos - Transistors (variant Vt property).ipynb
jagarzone6/cmos
mit
Simulacion con variacion desde el centro de Vt_p en la oblea y diseno 2 de surce compartido, centroide comun entre 2 transistores para formar el espejo de corriente.
paint_matrix = matrix(int(size_m),int(size_m)) opcion2() set_centroid_Vt_p() plt.matshow(Vt_p) plt.show() plt.matshow(paint_matrix) plt.show() Vtp_T1=prom_Vt_p_for_transistor(4) Vtp_T2=prom_Vt_p_for_transistor(5) #modificar_cir_Espejo_PMOS(WTA,L,Vtp_T1,Vtp_T2) display(Image(url='images/center_Vt_CS_p.png')) print("VD...
notebooks/Cmos - Transistors (variant Vt property).ipynb
jagarzone6/cmos
mit
Linear Regression Prepare train and test data.
data_original = np.loadtxt('stanford_dl_ex/ex1/housing.data') data = np.insert(data_original, 0, 1, axis=1) np.random.shuffle(data) train_X = data[:400, :-1] train_y = data[:400, -1] test_X = data[400:, :-1] test_y = data[400:, -1] m, n = train_X.shape
Learning_Curve_and_Other_Visualizations.ipynb
HaFl/ufldl-tutorial-python
mit
Define functions for Linear Regression (using Gradient Descent).
def cost_function(theta, X, y): squared_errors = (X.dot(theta) - y) ** 2 J = 0.5 * squared_errors.sum() return J def gradient(theta, X, y): errors = X.dot(theta) - y return errors.dot(X) def train(X, y): return scipy.optimize.minimize( fun=cost_function, x0=np.random.rand(n), ...
Learning_Curve_and_Other_Visualizations.ipynb
HaFl/ufldl-tutorial-python
mit
Learning Curve Define the number of equally sized parts the training data should be split up into. This equals the number of models that will be created.
fractions = 20
Learning_Curve_and_Other_Visualizations.ipynb
HaFl/ufldl-tutorial-python
mit
In every iteration: 1. Add one fraction of the full train set to the current train set. 2. Train a model. 3. Compute and save its Root Mean Square Error for both the current train set and the test set.
rms_train = np.zeros(fractions) rms_test = np.zeros(fractions) for i, fraction in enumerate(np.linspace(m / fractions, m, fractions)): optimal_theta = train(train_X[:fraction], train_y[:fraction]) rms_train[i] = np.sqrt(np.mean((train_X[:fraction].dot(optimal_theta) - train_y[:fraction]) ** 2)) rms_test[i] ...
Learning_Curve_and_Other_Visualizations.ipynb
HaFl/ufldl-tutorial-python
mit
Now we can plot the Learning Curve.
plt.figure(figsize=(8, 6)) plt.xlim(0, m + m / fractions) plt.xlabel('Training Instances Used') plt.ylabel('RMS Error') plt.plot(np.linspace(m / fractions, m, fractions), rms_train, c='g', marker='o', label='Train') plt.plot(np.linspace(m / fractions, m, fractions), rms_test, c='b', marker='o', label='Test') plt.legend...
Learning_Curve_and_Other_Visualizations.ipynb
HaFl/ufldl-tutorial-python
mit
3D Plots Scatter Plots The column with index 6 corresponds to the "Average Number of Rooms".<br> The column with index 13 corresponds to the "% lower status of the population".<br> See https://archive.ics.uci.edu/ml/datasets/Housing for more information.
fig = plt.figure(figsize=(17, 5)) ax = fig.add_subplot(131) ax.scatter(train_X[:40, 6], train_y[:40], c='b', marker='o') ax.set_xlabel('Avg Number of Rooms') ax.set_ylabel('House Price (in thousands)') ax = fig.add_subplot(132, projection='3d') ax.scatter(train_X[:40, 6], train_X[:40, 13], train_y[:40], c='r', marker...
Learning_Curve_and_Other_Visualizations.ipynb
HaFl/ufldl-tutorial-python
mit
Contour Plots First, let's define a new training function which also returns the theta values of every optimization step.
def train_with_history(X, y): theta = np.random.rand(X.shape[1]) history = [theta] optimal_theta = scipy.optimize.minimize( fun=cost_function, x0=theta, args=(X, y), method='bfgs', jac=gradient, options={'maxiter': 200, 'disp': False}, callback=lambda ...
Learning_Curve_and_Other_Visualizations.ipynb
HaFl/ufldl-tutorial-python
mit
Also, we need to scale down the dimensions of our train data to two.
contour_train_X = train_X[:, (6, 13)]
Learning_Curve_and_Other_Visualizations.ipynb
HaFl/ufldl-tutorial-python
mit
Gather optimal theta as well as all theta values on the way there.
optimal_theta, history = train_with_history(contour_train_X, train_y)
Learning_Curve_and_Other_Visualizations.ipynb
HaFl/ufldl-tutorial-python
mit
Define a grid of potentially relevant theta values and compute J for all of them.
theta0 = np.linspace(optimal_theta[0] - 5, optimal_theta[0] + 5, 100) theta1 = np.linspace(optimal_theta[1] - 5, optimal_theta[1] + 5, 100) J_values = np.zeros(shape=(theta0.size, theta1.size)) for i, theta0_val in enumerate(theta0): for j, theta1_val in enumerate(theta1): J_values[i, j] = cost_function(n...
Learning_Curve_and_Other_Visualizations.ipynb
HaFl/ufldl-tutorial-python
mit
Finally, reward ourselves with some high class contour plots.
fig = plt.figure(figsize=(14, 6)) ax = fig.add_subplot(121) ax.contour(theta0, theta1, J_values, cmap=cm.coolwarm) ax.scatter(optimal_theta[0], optimal_theta[1]) ax.plot(history[:, 0], history[:, 1], 'k-', marker='o') ax = fig.add_subplot(122, projection='3d') ax.contourf(theta0, theta1, J_values, cmap=cm.coolwarm) a...
Learning_Curve_and_Other_Visualizations.ipynb
HaFl/ufldl-tutorial-python
mit
Compute source power spectral density (PSD) of VectorView and OPM data Here we compute the resting state from raw for data recorded using a Neuromag VectorView system and a custom OPM system. The pipeline is meant to mostly follow the Brainstorm :footcite:TadelEtAl2011 OMEGA resting tutorial pipeline &lt;bst_omega_&gt;...
# Authors: Denis Engemann <denis.engemann@gmail.com> # Luke Bloy <luke.bloy@gmail.com> # Eric Larson <larson.eric.d@gmail.com> # # License: BSD-3-Clause import os.path as op from mne.filter import next_fast_len import mne print(__doc__) data_path = mne.datasets.opm.data_path() subject = 'OPM_sam...
0.24/_downloads/b36af73820a7a52a4df3c42b66aef8a5/source_power_spectrum_opm.ipynb
mne-tools/mne-tools.github.io
bsd-3-clause
Exercice 1 - manipulation des bases Durée : 10 minutes Importer la base de données relatives aux joueurs de la Coupe du Monde 2014 Déterminer le nombre de joueurs dans chaque équipe et créer un dictionnaire { équipe : Nombre de joueurs} Déterminer quels sont les 3 joueurs qui ont couvert le plus de distance. Y a t il ...
import pandas as pd data_players = pd.read_excel("Players_WC2014.xlsx", engine='openpyxl') data_players.head()
_doc/notebooks/td2a_eco/td2a_eco_exercices_de_manipulation_de_donnees_correction_a.ipynb
sdpython/ensae_teaching_cs
mit
Nombre de joueurs par équipe
data_players.groupby(['Team']).size().to_dict()
_doc/notebooks/td2a_eco/td2a_eco_exercices_de_manipulation_de_donnees_correction_a.ipynb
sdpython/ensae_teaching_cs
mit
Les joueurs ayant couvert le plus de distance
## quels joueurs ont couvert le plus de distance ? data_players['Distance Covered'] = data_players['Distance Covered'].str.replace('km','') data_players['Distance Covered'] = pd.to_numeric(data_players['Distance Covered']) data_players.sort_values(['Distance Covered'], ascending = 0).head(n=3)
_doc/notebooks/td2a_eco/td2a_eco_exercices_de_manipulation_de_donnees_correction_a.ipynb
sdpython/ensae_teaching_cs
mit
On voit un clair effet de sélection sur cette variable : ce sont les joueurs dont les équipes ont été le plus loin dans la compétition qui couvert le plus de distance. Qui a été le plus efficace ? On a besoin de rendre la variable Top Speed numérique, et de créer une nouvelle variable avec le poucentage de possession d...
## Qui a été le plus rapide ? data_players['Top Speed'] = data_players['Top Speed'].str.replace('km/h','') data_players['Top Speed'] = pd.to_numeric(data_players['Top Speed']) data_players.sort_values(['Top Speed'], ascending = 0).head(n=3) ## Parmis ceux qui sont dans le décile des plus rapides, qui a passé le plus ...
_doc/notebooks/td2a_eco/td2a_eco_exercices_de_manipulation_de_donnees_correction_a.ipynb
sdpython/ensae_teaching_cs
mit
Accessing rows and columns You can use loc and iloc as a chain to access the elements. Go from outer index to inner index
#access columns as usual df['A'] #access rows df.loc['G1'] #acess a single row form inner df.loc['G1'].loc[1] #access a single cell df.loc['G2'].loc[3]['B']
python_crash_course/pandas_cheat_sheet_2.ipynb
AtmaMani/pyChakras
mit
Naming indices Indices can have names (appear similar to column names)
df.index.names df.index.names = ['Group', 'Serial'] df
python_crash_course/pandas_cheat_sheet_2.ipynb
AtmaMani/pyChakras
mit
Accessing rows and columns using cross section The xs method allows to get a cross section. The advantage is it can penetrate a multilevel index in a single step. Now that we have named the indices, we can use cross section effectively
# Get all rows with Serial 1 df.xs(1, level='Serial') # Get rows with serial 2 in group 1 df.xs(['G1',2])
python_crash_course/pandas_cheat_sheet_2.ipynb
AtmaMani/pyChakras
mit
Missing data You can either drop rows/cols with missing values using dropna() or fill those cells with values using the fillna() methods. dropna Use dropna(axis, thresh...) where axis is 0 for rows, 1 for cols and thresh represents how many occurrences of nan before dropping happens
d = {'a':[1,2,np.nan], 'b':[np.nan, 5, np.nan], 'c':[6,7,8]} dfna = pd.DataFrame(d) dfna # dropping rows with one or more na values dfna.dropna() # dropping cols with one or more na values dfna.dropna(axis=1) # Dropping rows only if 2 or more cols have na values dfna.dropna(axis=0, thresh=2)
python_crash_course/pandas_cheat_sheet_2.ipynb
AtmaMani/pyChakras
mit
fillna
dfna.fillna(value=999) # filling with mean value of entire dataframe dfna.fillna(value = dfna.mean()) # fill with mean value row by row dfna['a'].fillna(value = dfna['a'].mean())
python_crash_course/pandas_cheat_sheet_2.ipynb
AtmaMani/pyChakras
mit
Data aggregation Pandas allows sql like control on the dataframes. You can treat each DF as a table and perform sql aggregation. groupby Format is: df.groupby('col_name').aggregation()
comp_data = {'Company':['GOOG','GOOG','MSFT','MSFT','FB','FB'], 'Person':['Sam','Charlie','Amy','Vanessa','Carl','Sarah'], 'Sales':[200,120,340,124,243,350]} comp_df = pd.DataFrame(comp_data) comp_df
python_crash_course/pandas_cheat_sheet_2.ipynb
AtmaMani/pyChakras
mit
mean min max
# mean sales by company - automatically only applies mean on numerical columns comp_df.groupby('Company').mean() # standard deviation in sales by company comp_df.groupby('Company').std()
python_crash_course/pandas_cheat_sheet_2.ipynb
AtmaMani/pyChakras
mit
You can run other aggregation functions like mean, min, max, std, count etc. Lets look at describe which does all of it. describe
comp_df.groupby('Company').describe()
python_crash_course/pandas_cheat_sheet_2.ipynb
AtmaMani/pyChakras
mit
transpose Long over due, you can tile a DF by calling the transpose() method.
comp_df.groupby('Company').describe().transpose() comp_df.groupby('Company').describe().index
python_crash_course/pandas_cheat_sheet_2.ipynb
AtmaMani/pyChakras
mit
Combining DataFrames You can concatenate, merge and join data frames. Lets take a look at 3 DataFrames
df1 = pd.DataFrame({'A': ['A0', 'A1', 'A2', 'A3'],'B': ['B0', 'B1', 'B2', 'B3'], 'C': ['C0', 'C1', 'C2', 'C3'],'D': ['D0', 'D1', 'D2', 'D3']}, index=[0, 1, 2, 3]) df2 = pd.DataFrame({'A': ['A4', 'A5', 'A6', 'A7'], 'B': ['B4', 'B5', 'B6', 'B7'], 'C': ['C4', 'C5', 'C6', 'C7...
python_crash_course/pandas_cheat_sheet_2.ipynb
AtmaMani/pyChakras
mit
concat pd.concat([list_of_df], axis=0) will extend a dataframe either along rows or columns. All DF in the list should be of same dimension.
# extend along rows pd.concat([df1, df2]) #flows well because index is sequential and colmns match #extend along columns pd.concat([df1, df2], axis=1) #fills NaN when index dont match
python_crash_course/pandas_cheat_sheet_2.ipynb
AtmaMani/pyChakras
mit
merge merge lets you do a sql merge with inner, outer, right and left joins. pd.merge(left, right, how='outer', on='key') where, left and right are your two DataFrames (tables) and on refers to the foreign key
left = pd.DataFrame({'key1': ['K0', 'K1', 'K2', 'K3'],'A': ['A0', 'A1', 'A2', 'A3'], 'B': ['B0', 'B1', 'B2', 'B3']}) right = pd.DataFrame({'key1': ['K0', 'K1', 'K2', 'K3'],'B': ['C0', 'C1', 'C2', 'C3'], 'C': ['D0', 'D1', 'D2', 'D3']}) left right
python_crash_course/pandas_cheat_sheet_2.ipynb
AtmaMani/pyChakras
mit
inner merge Inner join keeps only the intersection.
#merge along key1 pd.merge(left, right, how='inner', on='key1')
python_crash_course/pandas_cheat_sheet_2.ipynb
AtmaMani/pyChakras
mit
When both tables have same column names that are not used for merging (on) then pandas appends x and y to their names to differentiate merge on multiple columns Sometimes, your foreign key is composite. Then you can merge on multiple keys by passing a list to the on argument. Now lets add a key2 column to both the tabl...
left['key2'] = ['K0', 'K1', 'K0', 'K1'] left right['key2'] = ['K0', 'K0', 'K0', 'K0'] right pd.merge(left, right, how='inner', on=['key1', 'key2'])
python_crash_course/pandas_cheat_sheet_2.ipynb
AtmaMani/pyChakras
mit
inner merge will only keep the intersection, thus only 2 rows. outer merge Use how='outer' to keep the union of both the tables. pandas fills NaN when a cell has no values.
om = pd.merge(left, right, how='outer', on=['key1', 'key2']) om
python_crash_course/pandas_cheat_sheet_2.ipynb
AtmaMani/pyChakras
mit
Sorting Use DataFrame.sort_values(by=columns, inplace=False, ascending=True) to sort the table.
om.sort_values(by=['key1', 'key2']) #now you got the merge sorted by columns.
python_crash_course/pandas_cheat_sheet_2.ipynb
AtmaMani/pyChakras
mit
right merge how='right' will keep all the rows of right table and drop the rows of left table that dont have a matching keys.
pd.merge(left, right, how='right', on=['key1', 'key2']).sort_values(by='key1')
python_crash_course/pandas_cheat_sheet_2.ipynb
AtmaMani/pyChakras
mit
left merge how='left' will similarly keep all rows of left and those rows of right that has a matching foreign key.
pd.merge(left, right, how='left', on=['key1', 'key2']).sort_values(by='key1')
python_crash_course/pandas_cheat_sheet_2.ipynb
AtmaMani/pyChakras
mit
join Joins are like merges but work on index instead of columns. Further, they are by default either left or right with inner as mode of joins. See example below:
df_a = pd.DataFrame({'A': ['A0', 'A1', 'A2'], 'B': ['B0', 'B1', 'B2']}, index=['K0', 'K1', 'K2']) df_b = pd.DataFrame({'C': ['C0', 'C2', 'C3'], 'D': ['D0', 'D2', 'D3']}, index=['K0', 'K2', 'K3']) df_a df_b #join b to a, default mod...
python_crash_course/pandas_cheat_sheet_2.ipynb
AtmaMani/pyChakras
mit
Thus all rows of df_a and those in df_b. If df_b did not have that index, then NaN for values.
#join b to a df_b.join(df_a) #outer join - union of outputs df_b.join(df_a, how='outer')
python_crash_course/pandas_cheat_sheet_2.ipynb
AtmaMani/pyChakras
mit
Running dynamic presentations You need to install the RISE Ipython Library from Damián Avila for dynamic presentations To convert and run this as a static presentation run the following command:
# I can't see notes in this - Not sure what the issue is. Try this in a solely python 2 environment #PRIGINAL !ipython nbconvert 2016_Nottingham_GIServices_Lecture3_Beck_InteroperabilitySemanticsAndOpenData.ipynb --to slides --post serve !ipython nbconvert 2016_Nottingham_GIServices_Lecture3_Beck_InteroperabilityS...
20160202_Nottingham_GIServices_Lecture3_Beck_InteroperabilitySemanticsAndOpenData/.ipynb_checkpoints/2016_Nottingham_GIServices_Lecture3_Beck_InteroperabilitySemanticsAndOpenData-checkpoint.ipynb
AntArch/Presentations_Github
cc0-1.0
\newpage About me Honorary Research Fellow, University of Nottingham: orcid Director, Geolytics Limited - A spatial data analytics consultancy About this presentation Available on GitHub - https://github.com/AntArch/Presentations_Github/ Fully referenced PDF \newpage Contribution to GIScience learning outcomes Thi...
# THINGS TO DISCUSS ## Data needs to be credible, accessible, properly licenceed. Bring in Internet of Things
20160202_Nottingham_GIServices_Lecture3_Beck_InteroperabilitySemanticsAndOpenData/.ipynb_checkpoints/2016_Nottingham_GIServices_Lecture3_Beck_InteroperabilitySemanticsAndOpenData-checkpoint.ipynb
AntArch/Presentations_Github
cc0-1.0
A potted history of mapping In the beginning was the geoword and the word was cartography \newpage Cartography was king. Static representations of spatial knowledge with the cartographer deciding what to represent. Hence, maps are domain specific knowledge repositories for spatial data \newpage And then there w...
from IPython.display import YouTubeVideo YouTubeVideo('jUzGF401vLc')
20160202_Nottingham_GIServices_Lecture3_Beck_InteroperabilitySemanticsAndOpenData/.ipynb_checkpoints/2016_Nottingham_GIServices_Lecture3_Beck_InteroperabilitySemanticsAndOpenData-checkpoint.ipynb
AntArch/Presentations_Github
cc0-1.0
\newpage A more robust logic Would need to decouple licence incompatibility from licence name into licence clause (see table below) Deal with all licence type Provide recommendations based on desired derivative licence type Link this through to the type of process in a workflow: data derivation is, from a licence posi...
and more ``` If X spatiallyContains Y and X is a city then Y is a place and Y is a cityPart. Every city is a place. What is a place. ``` and more ``` UK isPartOf Europe. UK is sameAs UnitedKingdom. If X has a port then X borders Water. What borders Water? ```
20160202_Nottingham_GIServices_Lecture3_Beck_InteroperabilitySemanticsAndOpenData/.ipynb_checkpoints/2016_Nottingham_GIServices_Lecture3_Beck_InteroperabilitySemanticsAndOpenData-checkpoint.ipynb
AntArch/Presentations_Github
cc0-1.0
Now we apply the $k$-means algorithm. Therefore we: Set the maximum number of iterations. Set random inital center positions. Iteratively: 1. Assignment step: Calculate Euclidean distances between each data point and each center position and assign to nearest one. 2. Plot the assigned data points (just for vi...
max_iter = 16 # Set the maximum number of iterations. update_empty_centers = True # If True, a center point with no assigned data points gets a new random position. # Set random init center positions in range of training_data. def get_rand_centers(num): centers_x1 = (np.max(training_set[:,0])-np.min(training_set[:,...
mloc/ch6_Unsupervised_Learning/KMeans_Illustration.ipynb
kit-cel/wt
gpl-2.0
Python tutorials and references Following are some resources to learn Python Article with reviews about various tutorials http://noeticforce.com/best-free-tutorials-to-learn-python-pdfs-ebooks-online-interactive user voted list of tutorials on quora: https://www.quora.com/What-is-the-best-online-resource-to-learn-Pyth...
l1 = list() type(l1) l2 = [] len(l2)
python_crash_course/python_cheat_sheet_1.ipynb
AtmaMani/pyChakras
mit
list slicing
l3 = [1,2,3,4,5,6,7,8,9] l3[:] #prints all l3[0] l3[:4] #prints first 4. the : is slicing operator l3[4:7] #upto 1 less than highest index a = len(l3) l3[a-1] #negative index for traversing in opposite dir l3[-4:] #to pick the last 4 elements l3.reverse() #happens inplace l3
python_crash_course/python_cheat_sheet_1.ipynb
AtmaMani/pyChakras
mit
append and extend
l3.append(10) #to add new values l3 a1 = ['a','b','c'] l3.append(a1) l3[-1] a1 = ['a','b','c'] l3.extend(a1) #to splice two lists. need not be same data type l3 lol = [[1,2,3],[4,5,6]] #lol - list of lists len(lol) lol[1].reverse() lol[1]
python_crash_course/python_cheat_sheet_1.ipynb
AtmaMani/pyChakras
mit
mutability of lists list elements are mutable and can be changed
l3 l3[-1] = 'solar fare' #modify the last element l3 #list.insert(index, object) to insert a new value print(str(len(l3))) #before insertion l3.insert(1,'two') l3 # l3.pop(index) remove item at index and give that item l3.pop(-3) #remove 3rd item from last and give them l3 # l3.clear() to empty a list lol.clear()...
python_crash_course/python_cheat_sheet_1.ipynb
AtmaMani/pyChakras
mit
Lists and indices
# l3.index(value, <start, <stop>>) returns the first occurrence of element l3.index(10)
python_crash_course/python_cheat_sheet_1.ipynb
AtmaMani/pyChakras
mit
Find all the indices of an element
# indices = [i for i, x in enumerate(my_list) if x == "whatever"] #find all occurrence of 10 indices_of_10 = [i for i, x in enumerate(l3) if x == 10] indices_of_10 list(enumerate(l3))
python_crash_course/python_cheat_sheet_1.ipynb
AtmaMani/pyChakras
mit
Dictionaries Key value pairs d1 = dict() d2 = {'key1':value, 'key2':value2}
d1 = dict() d2 = {} len(d2) d3 = {'day':'Thursday', 'day_of_week':5, 'start_of_week':'Sunday', 'day_of_year':123, 'dod':{'month_of_year':'Feb', 'year':2017}, 'list1':[8,7,66]} len(d3) d3.keys() d3['start_of_week'] type(d3['dod']) # now that dod is a dict, get its keys d3['dod']....
python_crash_course/python_cheat_sheet_1.ipynb
AtmaMani/pyChakras
mit
mutability of dicts dicts like lists are mutable
d3['day_of_year'] = -48 d3 # insert new values just by adding kvp (key value pair) d3['workout_of_the_week']='bungee jumpging' d3
python_crash_course/python_cheat_sheet_1.ipynb
AtmaMani/pyChakras
mit
dict exploration what happens when you inquire a key thats not present
d3['dayyy'] # safe way to get elements is to use get() d3.get('day') d3.get('dayyy') #retuns None # use items() to get a list of tuples of key value pairs d3.items() # use values() to get only the values d3.values()
python_crash_course/python_cheat_sheet_1.ipynb
AtmaMani/pyChakras
mit
Tuple tuple is a immutable list
t1 = tuple() t2 = () len(t1) type(t2) t3 = (3,4,5,'t','g','b') t3[0] #use it just like a list t3[-1]
python_crash_course/python_cheat_sheet_1.ipynb
AtmaMani/pyChakras
mit
mutability of tuples cannot modify tuples.
t3[0] = 'good evening'
python_crash_course/python_cheat_sheet_1.ipynb
AtmaMani/pyChakras
mit
Sets set is a sequence of unique values s1 = set(&lt;sequence&gt;) s2 = {}
s1 = set([1,1,1,2,2,2,4,4,4,4,4,4,4,5]) s1 s2 = {1,2,2,2,2,3} s2
python_crash_course/python_cheat_sheet_1.ipynb
AtmaMani/pyChakras
mit