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
**[Pandas Home Page](https://www.kaggle.com/learn/pandas)**--- IntroductionIn these exercises we'll apply groupwise analysis to our dataset.Run the code cell below to load the data before running the exercises.
import pandas as pd reviews = pd.read_csv("../input/wine-reviews/winemag-data-130k-v2.csv", index_col=0) #pd.set_option("display.max_rows", 5) from learntools.core import binder; binder.bind(globals()) from learntools.pandas.grouping_and_sorting import * print("Setup complete.")
_____no_output_____
MIT
04 Pandas Certificate/Exercise Grouping and Sorting.ipynb
mateuszczubkowski/introduction-to-python
Exercises 1.Who are the most common wine reviewers in the dataset? Create a `Series` whose index is the `taster_twitter_handle` category from the dataset, and whose values count how many reviews each person wrote.
# Your code here reviews_written = reviews.groupby('taster_twitter_handle').size() # Check your answer q1.check() #q1.hint() #q1.solution()
_____no_output_____
MIT
04 Pandas Certificate/Exercise Grouping and Sorting.ipynb
mateuszczubkowski/introduction-to-python
2.What is the best wine I can buy for a given amount of money? Create a `Series` whose index is wine prices and whose values is the maximum number of points a wine costing that much was given in a review. Sort the values by price, ascending (so that `4.0` dollars is at the top and `3300.0` dollars is at the bottom).
best_rating_per_price = reviews.groupby('price')['points'].max().sort_index() # Check your answer q2.check() #q2.hint() #q2.solution()
_____no_output_____
MIT
04 Pandas Certificate/Exercise Grouping and Sorting.ipynb
mateuszczubkowski/introduction-to-python
3.What are the minimum and maximum prices for each `variety` of wine? Create a `DataFrame` whose index is the `variety` category from the dataset and whose values are the `min` and `max` values thereof.
price_extremes = reviews.groupby('variety').price.agg([min, max]) # Check your answer q3.check() #q3.hint() #q3.solution()
_____no_output_____
MIT
04 Pandas Certificate/Exercise Grouping and Sorting.ipynb
mateuszczubkowski/introduction-to-python
4.What are the most expensive wine varieties? Create a variable `sorted_varieties` containing a copy of the dataframe from the previous question where varieties are sorted in descending order based on minimum price, then on maximum price (to break ties).
sorted_varieties = reviews.groupby('variety').price.agg([min, max]).sort_values(by=['min', 'max'], ascending=False) # Check your answer q4.check() #q4.hint() #q4.solution()
_____no_output_____
MIT
04 Pandas Certificate/Exercise Grouping and Sorting.ipynb
mateuszczubkowski/introduction-to-python
5.Create a `Series` whose index is reviewers and whose values is the average review score given out by that reviewer. Hint: you will need the `taster_name` and `points` columns.
reviewer_mean_ratings = reviews.groupby('taster_name').points.mean() # Check your answer q5.check() #q5.hint() #q5.solution()
_____no_output_____
MIT
04 Pandas Certificate/Exercise Grouping and Sorting.ipynb
mateuszczubkowski/introduction-to-python
Are there significant differences in the average scores assigned by the various reviewers? Run the cell below to use the `describe()` method to see a summary of the range of values.
reviewer_mean_ratings.describe()
_____no_output_____
MIT
04 Pandas Certificate/Exercise Grouping and Sorting.ipynb
mateuszczubkowski/introduction-to-python
6.What combination of countries and varieties are most common? Create a `Series` whose index is a `MultiIndex`of `{country, variety}` pairs. For example, a pinot noir produced in the US should map to `{"US", "Pinot Noir"}`. Sort the values in the `Series` in descending order based on wine count.
country_variety_counts = reviews.groupby(['country', 'variety']).size().sort_values(ascending=False) # Check your answer q6.check() #q6.hint() #q6.solution()
_____no_output_____
MIT
04 Pandas Certificate/Exercise Grouping and Sorting.ipynb
mateuszczubkowski/introduction-to-python
![donate.jpg](data:image/jpeg;base64,/9j/4AAQSkZJRgABAgEASABIAAD/4Q9lRXhpZgAATU0AKgAAAAgABwESAAMAAAABAAEAAAEaAAUAAAABAAAAYgEbAAUAAAABAAAAagEoAAMAAAABAAIAAAExAAIAAAAcAAAAcgEyAAIAAAAUAAAAjodpAAQAAAABAAAApAAAANAACvyAAAAnEAAK/IAAACcQQWRvYmUgUGhvdG9zaG9wIENTMiBXaW5kb3dzADIwMTg6MDI6MDUgMTQ6MDg6NTkAAAAAA6ABAAMAAAAB//8AAKACAA...
import numpy as np import pandas as pd
_____no_output_____
Apache-2.0
Blood_Donation_Analysis.ipynb
rahuldiamond/Blood-Donation-Analysis-
**Importing library for visualization**
import matplotlib.pyplot as plt %matplotlib inline import seaborn as sns
_____no_output_____
Apache-2.0
Blood_Donation_Analysis.ipynb
rahuldiamond/Blood-Donation-Analysis-
**Importing library for splitting model into train and test and for data transformation**
from sklearn.model_selection import train_test_split from sklearn.metrics import confusion_matrix,accuracy_score,roc_auc_score
_____no_output_____
Apache-2.0
Blood_Donation_Analysis.ipynb
rahuldiamond/Blood-Donation-Analysis-
**Filter the unwanted warning**
import warnings warnings.simplefilter("ignore")
_____no_output_____
Apache-2.0
Blood_Donation_Analysis.ipynb
rahuldiamond/Blood-Donation-Analysis-
**Importing all the required model for model comparision**
from sklearn.ensemble import RandomForestClassifier from sklearn.linear_model import LogisticRegression from sklearn.tree import DecisionTreeClassifier from sklearn.neural_network import MLPClassifier from sklearn.svm import SVC
_____no_output_____
Apache-2.0
Blood_Donation_Analysis.ipynb
rahuldiamond/Blood-Donation-Analysis-
** Reading the Data**
train = pd.read_csv("blood-train.csv") test = pd.read_csv("blood-test.csv")
_____no_output_____
Apache-2.0
Blood_Donation_Analysis.ipynb
rahuldiamond/Blood-Donation-Analysis-
**Printing the train and test size**
print("Train Shape : ",train.shape) print("Test Shape : ", test.shape)
Train Shape : (576, 6) Test Shape : (200, 5)
Apache-2.0
Blood_Donation_Analysis.ipynb
rahuldiamond/Blood-Donation-Analysis-
**Printing first five rows of data**
train.head()
_____no_output_____
Apache-2.0
Blood_Donation_Analysis.ipynb
rahuldiamond/Blood-Donation-Analysis-
**Counting the number of people who donated and not donated**
train["Made Donation in March 2007"].value_counts()
_____no_output_____
Apache-2.0
Blood_Donation_Analysis.ipynb
rahuldiamond/Blood-Donation-Analysis-
**Storing dependent variable in Y**
Y = train.iloc[:,-1] Y.head() train.tail()
_____no_output_____
Apache-2.0
Blood_Donation_Analysis.ipynb
rahuldiamond/Blood-Donation-Analysis-
**Removing Unnamed: 0 columns**
old_train = train train = train.iloc[:, 1:5] test = test.iloc[:, 1:5]
_____no_output_____
Apache-2.0
Blood_Donation_Analysis.ipynb
rahuldiamond/Blood-Donation-Analysis-
**Printing first rows**
train.head()
_____no_output_____
Apache-2.0
Blood_Donation_Analysis.ipynb
rahuldiamond/Blood-Donation-Analysis-
**Merging both train and test data**
df = pd.merge(train,test) df.head() df.describe()
_____no_output_____
Apache-2.0
Blood_Donation_Analysis.ipynb
rahuldiamond/Blood-Donation-Analysis-
**Setting the independent variable and dependent variable**
X = df.iloc[:,:] X.head()
_____no_output_____
Apache-2.0
Blood_Donation_Analysis.ipynb
rahuldiamond/Blood-Donation-Analysis-
** Data Exploration*** Statistics of the data*
train.describe()
_____no_output_____
Apache-2.0
Blood_Donation_Analysis.ipynb
rahuldiamond/Blood-Donation-Analysis-
*Boxplot for Different variables*
plt.figure(figsize=(20,20)) ax = sns.boxplot(x="Months since First Donation", y="Number of Donations", data=old_train)
_____no_output_____
Apache-2.0
Blood_Donation_Analysis.ipynb
rahuldiamond/Blood-Donation-Analysis-
***Boxplot for Months since Last Donation**
plt.figure(figsize=(20,10)) ax = sns.boxplot(y="Months since Last Donation", data=old_train)
_____no_output_____
Apache-2.0
Blood_Donation_Analysis.ipynb
rahuldiamond/Blood-Donation-Analysis-
**We see from the above boxplot that the maximum people have donated blood in nearby 10 months.** **Correlation between all variables [Checking how different variable are related]**
corrmat = X.corr() f, ax = plt.subplots(figsize=(9, 8)) sns.heatmap(corrmat, ax = ax, cmap= "YlGnBu", linewidths= 0.1,fmt= ".2f",annot=True)
_____no_output_____
Apache-2.0
Blood_Donation_Analysis.ipynb
rahuldiamond/Blood-Donation-Analysis-
**Printing all unique value for Month Since Last donation**
train["Months since Last Donation"].unique()
_____no_output_____
Apache-2.0
Blood_Donation_Analysis.ipynb
rahuldiamond/Blood-Donation-Analysis-
**Feature Engineering** Volume donated is also a good feature to know wether the donor will donate or not. **Creating new variable for calculating how many times a person have donated**
X["Donating for"] = (X["Months since First Donation"] - X["Months since Last Donation"])
_____no_output_____
Apache-2.0
Blood_Donation_Analysis.ipynb
rahuldiamond/Blood-Donation-Analysis-
**Seeing first five rows of the DataFrame**
X.head()
_____no_output_____
Apache-2.0
Blood_Donation_Analysis.ipynb
rahuldiamond/Blood-Donation-Analysis-
**Correlation between all variables**
corrmat=X.corr() f, ax = plt.subplots(figsize =(9, 8)) sns.heatmap(corrmat, ax = ax, cmap ="YlGnBu", linewidths = 0.1,fmt = ".2f",annot=True)
_____no_output_____
Apache-2.0
Blood_Donation_Analysis.ipynb
rahuldiamond/Blood-Donation-Analysis-
**Since Total Volume Donated (c.c.) have the very high correlation with other variables so we are dropping the variable.** **Dropping the unnecessary column**
X.drop([ 'Total Volume Donated (c.c.)'], axis=1, inplace=True) X.head()
_____no_output_____
Apache-2.0
Blood_Donation_Analysis.ipynb
rahuldiamond/Blood-Donation-Analysis-
**Shape of independent variable**
X.shape
_____no_output_____
Apache-2.0
Blood_Donation_Analysis.ipynb
rahuldiamond/Blood-Donation-Analysis-
** Feature Transformation** **Feature Scaling**
from sklearn.preprocessing import StandardScaler scale=StandardScaler()
_____no_output_____
Apache-2.0
Blood_Donation_Analysis.ipynb
rahuldiamond/Blood-Donation-Analysis-
**Fitting and transforming data**
X=scale.fit_transform(X) train=X[:576] train.shape test=X[576:] test=X[576:] Y.shape
_____no_output_____
Apache-2.0
Blood_Donation_Analysis.ipynb
rahuldiamond/Blood-Donation-Analysis-
** Model Building** **Splitting into train and test set**
xtrain,xtest,ytrain,ytest=train_test_split(train,Y,test_size=0.2,random_state=0)
_____no_output_____
Apache-2.0
Blood_Donation_Analysis.ipynb
rahuldiamond/Blood-Donation-Analysis-
StepsTo Follow Create the object Do the necessary hyperparameter tuning Fit the model Predict the test set Compute roc_auc_score Repeat above step for all model Compare roc_auc_Score of all model and choose the best model * Logistic regression* ![logis.png](data:image/png;base64,iVBORw0KGgoAAA...
logreg = LogisticRegression(random_state=7)
_____no_output_____
Apache-2.0
Blood_Donation_Analysis.ipynb
rahuldiamond/Blood-Donation-Analysis-
*Fitting the model*
logreg.fit(xtrain,ytrain)
_____no_output_____
Apache-2.0
Blood_Donation_Analysis.ipynb
rahuldiamond/Blood-Donation-Analysis-
*Predicting on the test data*
pred = logreg.predict(xtest)
_____no_output_____
Apache-2.0
Blood_Donation_Analysis.ipynb
rahuldiamond/Blood-Donation-Analysis-
*checking accuracy_score*
accuracy_score(pred,ytest)
_____no_output_____
Apache-2.0
Blood_Donation_Analysis.ipynb
rahuldiamond/Blood-Donation-Analysis-
*Printing the roc_auc_score*
roc_auc_score(pred,ytest)
_____no_output_____
Apache-2.0
Blood_Donation_Analysis.ipynb
rahuldiamond/Blood-Donation-Analysis-
** Support Vector Machine** ![sv.jpg](data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAXgBeAAD/4QEKRXhpZgAATU0AKgAAAAgABwENAAIAAAAXAAAAYgEOAAIAAABsAAAAegEaAAUAAAABAAAA5gEbAAUAAAABAAAA7gEoAAMAAAABAAMAAAExAAIAAAAMAAAA9gITAAMAAAABAAEAAAAAAABTVk06IHNlcGFyYWJsZSBjbGFzc2VzAABTdXBwb3J0IHZlY3RvcnMgdW5pcXVlbHkgY2hhcmFjdGVyaXplIG9wdGl...
SVMC = SVC(probability=True)
_____no_output_____
Apache-2.0
Blood_Donation_Analysis.ipynb
rahuldiamond/Blood-Donation-Analysis-
*Fitting the model*
SVMC.fit(train,Y)
_____no_output_____
Apache-2.0
Blood_Donation_Analysis.ipynb
rahuldiamond/Blood-Donation-Analysis-
*Predicting on the test data*
pred = SVMC.predict(xtest) accuracy_score(pred, ytest)
_____no_output_____
Apache-2.0
Blood_Donation_Analysis.ipynb
rahuldiamond/Blood-Donation-Analysis-
*Printing the confusion matrix*
confusion_matrix(pred,ytest)
_____no_output_____
Apache-2.0
Blood_Donation_Analysis.ipynb
rahuldiamond/Blood-Donation-Analysis-
*Printing the roc auc score*
roc_auc_score(pred,ytest)
_____no_output_____
Apache-2.0
Blood_Donation_Analysis.ipynb
rahuldiamond/Blood-Donation-Analysis-
** Random Forest** ![rf.png](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABJIAAAKYCAIAAACnxEUUAAB6s0lEQVR42uzdD1RU173w/U3CbeZtSMIATx+S0pTCtCUrZEnbMQ/txVWSmMJVmrAu5GWMJtFXb3QobbW1oiCvcaEimMasmAKmcWme6MNwxTd4FSPFlfBGWtNI4nBDr7RhlERieN4OgoHezEpI5126e/c9d/4xDH/m3/ezuppxODNzztnnd/b+nX3O3rFOp1MAAAAAAELVDewCAAAAACBtAwAAAACQt...
RFC = RandomForestClassifier()
_____no_output_____
Apache-2.0
Blood_Donation_Analysis.ipynb
rahuldiamond/Blood-Donation-Analysis-
*Fitting the model*
RFC.fit(xtrain,ytrain)
_____no_output_____
Apache-2.0
Blood_Donation_Analysis.ipynb
rahuldiamond/Blood-Donation-Analysis-
*Predicting the test data result*
confusion_matrix(pred,ytest) accuracy_score(pred, ytest)
_____no_output_____
Apache-2.0
Blood_Donation_Analysis.ipynb
rahuldiamond/Blood-Donation-Analysis-
*accuracy_score(pred, ytest)*
roc_auc_score(pred,ytest)
_____no_output_____
Apache-2.0
Blood_Donation_Analysis.ipynb
rahuldiamond/Blood-Donation-Analysis-
** Decision Tree** ![dtree.png](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAskAAAHzCAYAAADSPIC7AAAABGdBTUEAALGPC/xhBQAAAAFzUkdCAK7OHOkAAAAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAAAZiS0dEAP8A/wD/oL2nkwAAAAlwSFlzAAAASAAAAEgARslrPgAAgABJREFUeNrs3Xd4VGXax/Hv1Ex6L4RAQu8tdKmCgEoRRRR7xe7u2rGuu2LB1XeLDbuoqy...
model = DecisionTreeClassifier(max_leaf_nodes=4,max_features=3,max_depth=15)
_____no_output_____
Apache-2.0
Blood_Donation_Analysis.ipynb
rahuldiamond/Blood-Donation-Analysis-
*Fitting the model*
model.fit(xtrain,ytrain)
_____no_output_____
Apache-2.0
Blood_Donation_Analysis.ipynb
rahuldiamond/Blood-Donation-Analysis-
*Predicting the test data*
accuracy_score(pred, ytest)
_____no_output_____
Apache-2.0
Blood_Donation_Analysis.ipynb
rahuldiamond/Blood-Donation-Analysis-
*printing the confusion matrix*
confusion_matrix(pred,ytest)
_____no_output_____
Apache-2.0
Blood_Donation_Analysis.ipynb
rahuldiamond/Blood-Donation-Analysis-
*Printing accuracy score*
accuracy_score(pred,ytest)
_____no_output_____
Apache-2.0
Blood_Donation_Analysis.ipynb
rahuldiamond/Blood-Donation-Analysis-
*Printing roc auc score*
roc_auc_score(pred,ytest)
_____no_output_____
Apache-2.0
Blood_Donation_Analysis.ipynb
rahuldiamond/Blood-Donation-Analysis-
** MLP Classifier** ![mlp.png](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABrsAAARvCAIAAAAnp8hUAACAAElEQVR42uzdCZxcZZ3v/+c559Ta1dn3TsLOiAOIICChM6b5O1aLetm8LvfqXHCZua//eFl0Jg2SMYlmRrqVYXTGCzozf3EURWbcYNRuHTvEbgKBBAJERUAgJOkkJOlsvdRyznn+rz5P1amTqu7qTqc7qar+vHMoTtdyuuqpSlH15fc8P0spJQAAAAAAAADAYzAEAAAAAAAAAHwkhgAAAAAAAAA...
clf_neural = MLPClassifier(solver='lbfgs', alpha=1e-5, hidden_layer_sizes=(25,),random_state=1) clf_neural.fit(train, Y)
_____no_output_____
Apache-2.0
Blood_Donation_Analysis.ipynb
rahuldiamond/Blood-Donation-Analysis-
*Predicting from the fitted model on test data*
print('Predicting...\nIn Test Data') predicted = clf_neural.predict(xtest)
_____no_output_____
Apache-2.0
Blood_Donation_Analysis.ipynb
rahuldiamond/Blood-Donation-Analysis-
*printing confusion matrix*
confusion_matrix(predicted,ytest)
_____no_output_____
Apache-2.0
Blood_Donation_Analysis.ipynb
rahuldiamond/Blood-Donation-Analysis-
*Printing roc auc score*
roc_auc_score(pred,ytest) accuracy_score(pred, ytest)
_____no_output_____
Apache-2.0
Blood_Donation_Analysis.ipynb
rahuldiamond/Blood-Donation-Analysis-
**Thermodynamics: an Engineering Approach, 7th Ed**Cengel & Boles Chapter 1: Introduction and Basic Concepts Example 1-1, Page.8
#Diketahui: El_USD = 0.09 # Harga Listrik adalah 0.09 $/kWh P_wt = 30 # Wind Turbine power rate, kW t_wt = 2200 # Durasi kerja Wind Turbine dalam satu tahun, hours #Dicari: pengiritan per tahun (?) #Jawab: E_tot = P_wt * t_wt print ('Total energi adalah %f kWh' %round(E_tot,0)) #Uang yang diirit: Saved_USD = E_tot *...
Total energi adalah 66000.000000 kWh Total pengiritan adalah 5940.000000 USD
MIT
Thermodynamics_an Eng Approach_5Ed_Cengel_IDN/.ipynb_checkpoints/Chapter_1_1-checkpoint.ipynb
msuherma/termodinamika
Example 1-2, Page No.9
#Diketahui: p=850;# densitas [kg/m^3] V=2; # volume tangki [m^3] #Dicari: Massa (?) m=p*V;# rumus massa #Hasil: print ('Massa minyak di dalam tangki adalah %i kg' %round(m,0))
Massa minyak di dalam tangki adalah 1700 kg
MIT
Thermodynamics_an Eng Approach_5Ed_Cengel_IDN/.ipynb_checkpoints/Chapter_1_1-checkpoint.ipynb
msuherma/termodinamika
Example 1-3, Page No.10
#Diketahui m=1; # massa seberat 1 lbm #Konstanta yang dipakai g=32.174;# konstanta gravitasi, ft/s^2 #Dicari: Berat (w) lbf = 32.174 # Konversi 1 lbf = 32.174 lbm.ft/s^2 w=(m*g)*(1/lbf); # berat = massa * gravitasi # konversi lbf ke lbm diperlukan #Result print ('Berat benda tersebut di bumi adala...
Berat benda tersebut di bumi adalah 1 lbf
MIT
Thermodynamics_an Eng Approach_5Ed_Cengel_IDN/.ipynb_checkpoints/Chapter_1_1-checkpoint.ipynb
msuherma/termodinamika
Example 1-4, Page No.21
# Diketahui Tc=10; #deltaT karena proses pemberian kalor, C # Calculations Tk=Tc; Tr=1.8*Tk;#Konversi dari R ke K Tf=Tr; # Dihitung dengan rumus di atas #Hasil print ('perubahan suhu tersebut adalah %i K' %Tk) print ('perubahan suhu tersebut adalah %i R' %Tr) print ('perubahan suhu tersebut adalah %i F' %Tf)
perubahan suhu tersebut adalah 10 K perubahan suhu tersebut adalah 18 R perubahan suhu tersebut adalah 18 F
MIT
Thermodynamics_an Eng Approach_5Ed_Cengel_IDN/.ipynb_checkpoints/Chapter_1_1-checkpoint.ipynb
msuherma/termodinamika
Example 1-5, Page No.23
#Diketahui Patm=14.5; #tekanan atmosfir, psi Pvac=5.8; #pembacaan vacuum gage, psi #Proses perhitungan Pabs=Patm-Pvac;#vacuum selalu dihitung sbg tekanan negatif #Hasil print('P_absolut dari ruangan tersebut adalah %f psi'%round(Pabs,1))
P_absolut dari ruangan tersebut adalah 8.700000 psi
MIT
Thermodynamics_an Eng Approach_5Ed_Cengel_IDN/.ipynb_checkpoints/Chapter_1_1-checkpoint.ipynb
msuherma/termodinamika
Example 1-6, Page No.26
#Diketahui: pw=1000; # Densitas air, kg/m^3; g=9.81; # Gravitasi, m/s^2; SG=0.85;# Specific Gravity/Dens. Relatif fluida di manometer meter = 100 # 1 m = 100 cm, cm h=55/meter;# tinggi dalam satuan, cm Patm=96;# Tekanan Atmosfir, kPa # Jawab # Menghitung P menggunakan likuid pada ketinggian yang sama p=SG*pw; Ptank_ab...
absolute pressure in tank 100.600000 kPa
MIT
Thermodynamics_an Eng Approach_5Ed_Cengel_IDN/.ipynb_checkpoints/Chapter_1_1-checkpoint.ipynb
msuherma/termodinamika
Example 1-7, Page No.28
#Constants used g=9.81;#acceleration due to gravity in m/s^2; #Given values h1=0.1;# distance b/w point 1 at air-water interface and point 2 at mercury-air interface in m h2=0.2;# distance b/w oil-water interface and mercury-oil interface in m h3=0.35;# distance b/w air-mercury interface and mercury-oil interface in...
the air pressure in tank 130 kPa
MIT
Thermodynamics_an Eng Approach_5Ed_Cengel_IDN/.ipynb_checkpoints/Chapter_1_1-checkpoint.ipynb
msuherma/termodinamika
Example 1-8, Page No.31
#Constants used g=9.81;# acceleration due to gravity in m/s^2; #Given values pHg=13570;# density of mercury at 10 C in kg/m^3 h=0.74;# converting barometric reading into m from mm #Calculationa Patm=pHg*g*h/1000;# standard pressure formula #Results print ('the atmospheric pressure %f kPa' %round(Patm,1))
the atmospheric pressure 98.500000 kPa
MIT
Thermodynamics_an Eng Approach_5Ed_Cengel_IDN/.ipynb_checkpoints/Chapter_1_1-checkpoint.ipynb
msuherma/termodinamika
Example 1-9, Page No.31
#constants used g=9.81;#acceleration due to gravity in m/s^2; #given values m=60;# mass of piston in kg Patm=0.97;# atmospheric pressure in kPa A=0.04;# cross-sectional area in m^2 #calculation P=Patm+(m*g/A)/100000;# standard pressure formula print ('The pressure inside the cylinder %f bar' %round(P,2)) #The volume...
The pressure inside the cylinder 1.120000 bar If some heat is transferred to the gas and its volume is doubled, there is no change in pressure
MIT
Thermodynamics_an Eng Approach_5Ed_Cengel_IDN/.ipynb_checkpoints/Chapter_1_1-checkpoint.ipynb
msuherma/termodinamika
Example 1-10, Page No.32
import math from scipy.integrate import quad from pylab import * #Constants used g=9.81;#acceleration due to gravity in m/s^2; #Given values p=1040;# density on the water surface in kg/m^3 h1=0.8;# thickness of surface zone H=4;# thickness of gradient zone x0=0.0;# lower limit of integration x1=4.0;# upper limit of ...
_____no_output_____
MIT
Thermodynamics_an Eng Approach_5Ed_Cengel_IDN/.ipynb_checkpoints/Chapter_1_1-checkpoint.ipynb
msuherma/termodinamika
Assignment 1 We are given a 2-dimensional grid with points $(i, j)$, $i, j = 0, \dots, N+1$. In this assignment we want to simulate a discrete diffusion process on the grid. We are starting with a distribution $u_0(i, j)$ of function values on the grid points. The distribution process follows the following recurrence ...
def diffusion_iteration(un): """ Perform one diffusion step for all given grid points. Parameters ---------- un : numpy.ndarray Numpy array of type `float64` and dimension (N + 2, N + 2) that stores the function values at step n. This function returns a Numpy array ...
_____no_output_____
BSD-3-Clause
hpc_lecture_notes/assignment_1.ipynb
skailasa/hpc_lecture_notes
Ejercicio: Spectral clustering para documentosEl clustering espectral es una técnica de agrupamiento basada en la topología de gráficas. Es especialmente útil cuando los datos no son convexos o cuando se trabaja, directamente, con estructuras de grafos.Preparación d elos documentosTrabajaremos con documentos textuales...
#Se importan las librerías necesarias import numpy as np import matplotlib.pyplot as plt from sklearn.decomposition import PCA from gensim.models.doc2vec import Doc2Vec, TaggedDocument
_____no_output_____
MIT
notebooks/04_Ejercicio_spectral_clust.ipynb
medinaalonso/NLP
La librería de Natural Language Toolkit (nltk) proporciona algunos corpus con los que se puede trabajar. Por ejemplo, el cropus Gutenberg (https://web.eecs.umich.edu/~lahiri/gutenberg_dataset.html) del que usaremos algunos datos. Asimismo, obtendremos de esta librería herramientas de preprocesamiento: stemmer y lista d...
import nltk #Descarga del corpus nltk.download('gutenberg') #Descarga de la lista de stopwords nltk.download('stopwords') from nltk.corpus import gutenberg from nltk.corpus import stopwords from nltk.stem import PorterStemmer
[nltk_data] Downloading package gutenberg to /root/nltk_data... [nltk_data] Unzipping corpora/gutenberg.zip. [nltk_data] Downloading package stopwords to /root/nltk_data... [nltk_data] Unzipping corpora/stopwords.zip.
MIT
notebooks/04_Ejercicio_spectral_clust.ipynb
medinaalonso/NLP
Definimos los nombres de los archivos (ids) y la lista de paro
#Obtiene ids de los archivos del corpus gutenberg doc_labels = gutenberg.fileids() #Lista de stopwords para inglés lista_paro = stopwords.words('english')
_____no_output_____
MIT
notebooks/04_Ejercicio_spectral_clust.ipynb
medinaalonso/NLP
Definiremos una función que se encargará de preprocesar los textos. Se eliminan símbolos, se quitan elementos de la lista de stopwords y se pasa todo a minúsculas.
def preprocess(document): #Lista que guarda archivos limpios text = [] for word in document: #Minúsculas word = word.lower() #Elimina stopwords y símbolos if word not in lista_paro and word.isalpha() == True: #Se aplica stemming text.append(PorterStemmer().stem(word)) return text
_____no_output_____
MIT
notebooks/04_Ejercicio_spectral_clust.ipynb
medinaalonso/NLP
Por cada documento, obtenemos la lista de sus palabras (stems) aplicando un preprocesado. Cada documento, entonces, es de la forma $d_i = \{w_1, w_2, ..., w_{N_i}\}$, donde $w_k$ son los stems del documento.
docs = [] for doc in doc_labels: #Lista de palabras del documentos arx = gutenberg.words(doc) #Aplica la función de preprocesado arx_prep = preprocess(arx) docs.append(arx_prep) #Imprime el nombre del documento, su longitud original y su longitud con preproceso print(doc,len(arx), len(arx_prep))
austen-emma.txt 192427 73149 austen-persuasion.txt 98171 38337 austen-sense.txt 141576 53986 bible-kjv.txt 1010654 374945 blake-poems.txt 8354 3805 bryant-stories.txt 55563 21718 burgess-busterbrown.txt 18963 7582 carroll-alice.txt 34110 12240 chesterton-ball.txt 96996 39715 chesterton-brown.txt 86063 35348 chesterton-...
MIT
notebooks/04_Ejercicio_spectral_clust.ipynb
medinaalonso/NLP
Posteriormente, convertiremos cada documento en un vector en $\mathbb{R}^d$. Para esto, utilizaremos el algoritmo Doc2Vec.
#Dimensión de los vectores dim = 300 #tamaño de la ventana de contexto windows_siz = 15 #Indexa los documentos con valores enteros documents = [TaggedDocument(doc_i, [i]) for i, doc_i in enumerate(docs)] #Aplica el modelo de Doc2Vec model = Doc2Vec(documents, vector_size=dim, window=windows_siz, min_count=1) #Matriz ...
[[-0.71790749 0.52590156 0.04665314 ... -1.11765587 0.27269235 0.17521498] [-0.99053538 0.81888688 0.08494744 ... -1.4580884 0.35552233 0.36190808] [-1.1343857 0.89900047 0.07679608 ... -1.67795575 0.4307873 0.40497407] ... [-1.57137489 1.01522303 0.13583013 ... -2.54420257 0.6712212 0.232...
MIT
notebooks/04_Ejercicio_spectral_clust.ipynb
medinaalonso/NLP
Visualización
#Función para plotear def plot_words(Z,ids,color='blue'): #Reduce a dos dimensiones con PCA Z = PCA(n_components=2).fit_transform(Z) r=0 #Plotea las dimensiones plt.scatter(Z[:,0],Z[:,1], marker='o', c=color) for label,x,y in zip(ids, Z[:,0], Z[:,1]): #Agrega las etiquetas plt.an...
_____no_output_____
MIT
notebooks/04_Ejercicio_spectral_clust.ipynb
medinaalonso/NLP
Task 2: Image Enhancement II: Spatial SmoothingIn this task, we will implement average, gaussian, and median spatial filter.
%%bash pip install git+https://github.com/ee604/ee604_plugins # Importing required libraries import cv2 import numpy as np import matplotlib.pyplot as plt from ee604_plugins import download_dataset, cv2_imshow download_dataset(assignment_no=2, task_no=2) # download data for this assignment def avgFilter(img, kernel_s...
_____no_output_____
MIT
assignment_2/Task_2.ipynb
antranx/ee604_assignments
Test---Your observation should compare the different methods for different images. Must include a sentence on which method + kernel size worked best in each case.
# Do not change codes inside this cell # Add your observations in next to next cell # Your observation should compare the different methods for different images lena_orig = cv2.imread('data/lena_gray.jpg', 0) lena_noisy_1 = cv2.imread('data/lena_noisy_1.jpg', 0) lena_noisy_2 = cv2.imread('data/lena_noisy_2.jpg', 0) le...
_____no_output_____
MIT
assignment_2/Task_2.ipynb
antranx/ee604_assignments
Machine Learning Model Building Pipeline: Wrapping up for DeploymentIn the previous lectures, we worked through the typical Machine Learning pipeline to build a regression model that allows us to predict house prices. Briefly, we transformed variables in the dataset to make them suitable for use in a Regression model,...
# to handle datasets import pandas as pd import numpy as np # to divide train and test set from sklearn.model_selection import train_test_split # feature scaling from sklearn.preprocessing import MinMaxScaler # to build the models from sklearn.linear_model import Lasso # to evaluate the models from sklearn.metrics ...
_____no_output_____
BSD-3-Clause
jupyter_notebooks/Section2_MLPipelineOverview/02.10_ML_Pipeline-WrapUp_for_Deployment.ipynb
mtpadilla/deploying-machine-learning-models
Load dataWe need the training data to train our model in the production environment.
data_folder = '/Users/michaelpadilla/projects/udemy_deployment/data/house-prices-advanced-regression-techniques/' # load dataset data = pd.read_csv(os.path.join(data_folder, 'houseprice.csv')) print(data.shape) data.head()
(1460, 81)
BSD-3-Clause
jupyter_notebooks/Section2_MLPipelineOverview/02.10_ML_Pipeline-WrapUp_for_Deployment.ipynb
mtpadilla/deploying-machine-learning-models
Separate dataset into train and testBefore beginning to engineer our features, it is important to separate our data intro training and testing set. This is to avoid over-fitting. There is an element of randomness in dividing the dataset, so remember to set the seed.
# Let's separate into train and test set # Remember to seet the seed (random_state for this sklearn function) X_train, X_test, y_train, y_test = train_test_split(data, data.SalePrice, test_size=0.1, random_state=0) ...
_____no_output_____
BSD-3-Clause
jupyter_notebooks/Section2_MLPipelineOverview/02.10_ML_Pipeline-WrapUp_for_Deployment.ipynb
mtpadilla/deploying-machine-learning-models
Selected featuresRemember that we will deploy our model utilising only a subset of features, the most predictive ones. This is to make simpler models, so that we build simpler code for deployment. We will tell you more about this in coming lectures.
# load selected features features = pd.read_csv(os.path.join(data_folder, 'selected_features.csv'), header=None) # Remember that I added the extra feature, to show you how to put # an additional feature engineering step into production features = [x for x in features[0]] + ['LotFrontage'] print('Number of features: ',...
_____no_output_____
BSD-3-Clause
jupyter_notebooks/Section2_MLPipelineOverview/02.10_ML_Pipeline-WrapUp_for_Deployment.ipynb
mtpadilla/deploying-machine-learning-models
Missing valuesFor categorical variables, we will fill missing information by adding an additional category: "missing"
# make a list of the categorical variables that contain missing values vars_with_na = [var for var in features if X_train[var].isnull().sum()>1 and X_train[var].dtypes=='O'] # print the variable name and the percentage of missing values for var in vars_with_na: print(var, np.round(X_train[var].isnull().mean()*100,...
_____no_output_____
BSD-3-Clause
jupyter_notebooks/Section2_MLPipelineOverview/02.10_ML_Pipeline-WrapUp_for_Deployment.ipynb
mtpadilla/deploying-machine-learning-models
Note that we have much less categorical variables with missing values than in our original dataset. But we still use categorical variables with NA for the final model, so we need to include this piece of feature engineering logic in the deployment pipeline.
# I bring forward the functions used in the feature engineering notebook: # function to replace NA in categorical variables def fill_categorical_na(df, var_list): X = df.copy() X[var_list] = df[var_list].fillna('Missing') return X # replace missing values with new label: "Missing" X_train = fill_categoric...
_____no_output_____
BSD-3-Clause
jupyter_notebooks/Section2_MLPipelineOverview/02.10_ML_Pipeline-WrapUp_for_Deployment.ipynb
mtpadilla/deploying-machine-learning-models
For numerical variables, we are going to add an additional variable capturing the missing information, and then replace the missing information in the original variable by the mode, or most frequent value:
# make a list of the numerical variables that contain missing values vars_with_na = [var for var in features if X_train[var].isnull().sum()>1 and X_train[var].dtypes!='O'] # print the variable name and the percentage of missing values for var in vars_with_na: print(var, np.round(X_train[var].isnull().mean()*100, 2...
LotFrontage 17.73 % missing values
BSD-3-Clause
jupyter_notebooks/Section2_MLPipelineOverview/02.10_ML_Pipeline-WrapUp_for_Deployment.ipynb
mtpadilla/deploying-machine-learning-models
Important: persisting the mean value for NA imputationAs you will see in future sections, one of the key pieces of deploying the model is "Model Validation". Model validation refers to corroborating that the deployed model and the model built during research, are identical. The entire pipeline needs to produce identic...
X_train['LotFrontage'].mode()[0] # replace the missing values mean_var_dict = {} for var in vars_with_na: # calculate the mode mode_val = X_train[var].mode()[0] # we persist the mean in the dictionary mean_var_dict[var] = mode_val # train # note that the additional binary varia...
_____no_output_____
BSD-3-Clause
jupyter_notebooks/Section2_MLPipelineOverview/02.10_ML_Pipeline-WrapUp_for_Deployment.ipynb
mtpadilla/deploying-machine-learning-models
Temporal variablesOne of our temporal variables was selected to be used in the final model: 'YearRemodAdd'So we need to deploy the bit of code that creates it.
# create the temporal var "elapsed years" def elapsed_years(df, var): # capture difference between year variable and year the house was sold df[var] = df['YrSold'] - df[var] return df X_train = elapsed_years(X_train, 'YearRemodAdd') X_test = elapsed_years(X_test, 'YearRemodAdd') for var in ['LotFrontage', '...
_____no_output_____
BSD-3-Clause
jupyter_notebooks/Section2_MLPipelineOverview/02.10_ML_Pipeline-WrapUp_for_Deployment.ipynb
mtpadilla/deploying-machine-learning-models
Categorical variablesWe do have categorical variables in our final model. First, we will remove those categories within variables that are present in less than 1% of the observations:
# let's capture the categorical variables first cat_vars = [var for var in features if X_train[var].dtype == 'O'] cat_vars
_____no_output_____
BSD-3-Clause
jupyter_notebooks/Section2_MLPipelineOverview/02.10_ML_Pipeline-WrapUp_for_Deployment.ipynb
mtpadilla/deploying-machine-learning-models
Important: persisting the frequent labelsAs you will see in future sections, one of the key pieces of deploying the model is "Model Validation". Model validation refers to corroborating that the deployed model and the model built during research, are identical. The entire pipeline needs to produce identical results.Th...
tmp = X_train.groupby(cat_vars[0])['SalePrice'].count() / len(X_train) tmp > 0.01 def find_frequent_labels(df, var, rare_perc): # finds the labels that are shared by more than a certain % of the houses in the dataset df = df.copy() tmp = df.groupby(var)['SalePrice'].count() / len(df) return tmp[tmp>rare...
_____no_output_____
BSD-3-Clause
jupyter_notebooks/Section2_MLPipelineOverview/02.10_ML_Pipeline-WrapUp_for_Deployment.ipynb
mtpadilla/deploying-machine-learning-models
Next, we need to transform the strings of these variables into numbers. We will do it so that we capture the monotonic relationship between the label and the target:
# this function will assign discrete values to the strings of the variables, # so that the smaller value corresponds to the smaller mean of target def replace_categories(train, test, var, target): train = train.copy() test = test.copy() ordered_labels = train.groupby([var])[target].mean().sort_values...
_____no_output_____
BSD-3-Clause
jupyter_notebooks/Section2_MLPipelineOverview/02.10_ML_Pipeline-WrapUp_for_Deployment.ipynb
mtpadilla/deploying-machine-learning-models
Feature ScalingFor use in linear models, features need to be either scaled or normalised. In the next section, I will scale features between the min and max values:
# capture the target y_train = X_train['SalePrice'] y_test = X_test['SalePrice'] # fit scaler scaler = MinMaxScaler() # create an instance scaler.fit(X_train[features]) # fit the scaler to the train set for later use # we persist the model for future use joblib.dump(scaler, os.path.join(data_folder, 'scaler.pkl')) #...
linear train mse: 1087435415.441452 linear train rmse: 32976.28565259362 linear test mse: 1405259552.2596023 linear test rmse: 37486.79170400692 Average house price: 163000.00000000012
BSD-3-Clause
jupyter_notebooks/Section2_MLPipelineOverview/02.10_ML_Pipeline-WrapUp_for_Deployment.ipynb
mtpadilla/deploying-machine-learning-models
Copyright (c) Microsoft Corporation. All rights reserved.Licensed under the MIT License. ![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/automated-machine-learning/classification-credit-card-fraud/auto-ml-classification-credit-card-fraud.png...
import logging from matplotlib import pyplot as plt import pandas as pd import os import azureml.core from azureml.core.experiment import Experiment from azureml.core.workspace import Workspace from azureml.core.dataset import Dataset from azureml.train.automl import AutoMLConfig
_____no_output_____
MIT
how-to-use-azureml/automated-machine-learning/classification-credit-card-fraud/auto-ml-classification-credit-card-fraud.ipynb
tomasro27/MachineLearningNotebooks
This sample notebook may use features that are not available in previous versions of the Azure ML SDK.
print("This notebook was created using version 1.22.0 of the Azure ML SDK") print("You are currently using version", azureml.core.VERSION, "of the Azure ML SDK") ws = Workspace.from_config() # choose a name for experiment experiment_name = 'automl-classification-ccard-remote' experiment=Experiment(ws, experiment_name...
_____no_output_____
MIT
how-to-use-azureml/automated-machine-learning/classification-credit-card-fraud/auto-ml-classification-credit-card-fraud.ipynb
tomasro27/MachineLearningNotebooks
Create or Attach existing AmlComputeA compute target is required to execute the Automated ML run. In this tutorial, you create AmlCompute as your training compute resource. Creation of AmlCompute takes approximately 5 minutes. If the AmlCompute with that name is already in your workspace this code will skip the creati...
from azureml.core.compute import ComputeTarget, AmlCompute from azureml.core.compute_target import ComputeTargetException # Choose a name for your CPU cluster cpu_cluster_name = "cpu-cluster-1" # Verify that cluster does not exist already try: compute_target = ComputeTarget(workspace=ws, name=cpu_cluster_name) ...
_____no_output_____
MIT
how-to-use-azureml/automated-machine-learning/classification-credit-card-fraud/auto-ml-classification-credit-card-fraud.ipynb
tomasro27/MachineLearningNotebooks
Data Load DataLoad the credit card dataset from a csv file containing both training features and labels. The features are inputs to the model, while the training labels represent the expected output of the model. Next, we'll split the data using random_split and extract the training data for the model.
data = "https://automlsamplenotebookdata.blob.core.windows.net/automl-sample-notebook-data/creditcard.csv" dataset = Dataset.Tabular.from_delimited_files(data) training_data, validation_data = dataset.random_split(percentage=0.8, seed=223) label_column_name = 'Class'
_____no_output_____
MIT
how-to-use-azureml/automated-machine-learning/classification-credit-card-fraud/auto-ml-classification-credit-card-fraud.ipynb
tomasro27/MachineLearningNotebooks
TrainInstantiate a AutoMLConfig object. This defines the settings and data used to run the experiment.|Property|Description||-|-||**task**|classification or regression||**primary_metric**|This is the metric that you want to optimize. Classification supports the following primary metrics: accuracyAUC_weightedaverage_pr...
automl_settings = { "n_cross_validations": 3, "primary_metric": 'average_precision_score_weighted', "enable_early_stopping": True, "max_concurrent_iterations": 2, # This is a limit for testing purpose, please increase it as per cluster size "experiment_timeout_hours": 0.25, # This is a time limit fo...
_____no_output_____
MIT
how-to-use-azureml/automated-machine-learning/classification-credit-card-fraud/auto-ml-classification-credit-card-fraud.ipynb
tomasro27/MachineLearningNotebooks
Call the `submit` method on the experiment object and pass the run configuration. Depending on the data and the number of iterations this can run for a while. Validation errors and current status will be shown when setting `show_output=True` and the execution will be synchronous.
remote_run = experiment.submit(automl_config, show_output = False) # If you need to retrieve a run that already started, use the following code #from azureml.train.automl.run import AutoMLRun #remote_run = AutoMLRun(experiment = experiment, run_id = '<replace with your run id>') remote_run
_____no_output_____
MIT
how-to-use-azureml/automated-machine-learning/classification-credit-card-fraud/auto-ml-classification-credit-card-fraud.ipynb
tomasro27/MachineLearningNotebooks
Results Widget for Monitoring RunsThe widget will first report a "loading" status while running the first iteration. After completing the first iteration, an auto-updating graph and table will be shown. The widget will refresh once per minute, so you should see the graph update as child runs complete.**Note:** The wi...
from azureml.widgets import RunDetails RunDetails(remote_run).show() remote_run.wait_for_completion(show_output=False)
_____no_output_____
MIT
how-to-use-azureml/automated-machine-learning/classification-credit-card-fraud/auto-ml-classification-credit-card-fraud.ipynb
tomasro27/MachineLearningNotebooks
Explain modelAutomated ML models can be explained and visualized using the SDK Explainability library. Analyze results Retrieve the Best ModelBelow we select the best pipeline from our iterations. The `get_output` method returns the best run and the fitted model. Overloads on `get_output` allow you to retrieve the ...
best_run, fitted_model = remote_run.get_output() fitted_model
_____no_output_____
MIT
how-to-use-azureml/automated-machine-learning/classification-credit-card-fraud/auto-ml-classification-credit-card-fraud.ipynb
tomasro27/MachineLearningNotebooks