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
The score will always be an integer since it is based on upvotes and downvotes. Before converting however, we need to check if there are any null values.
df.isna().sum() df[df.isnull().any(axis=1)].head(20)
_____no_output_____
MIT
python/redditscore.ipynb
AlexHartford/redditscore
There is only a small amount of null values and they appear to be of little use, so removing them seems to be the best bet. Once the null values are removed we can convert score to an integer.
df = df.dropna() df['score'] = df['score'].astype('int') print(df.shape) df.head(10)
(1941086, 3)
MIT
python/redditscore.ipynb
AlexHartford/redditscore
Initial Data AnalysisBefore getting into handling the comment body a better understanding of the score collumn needs to be gained.
df['score'].describe() sns.distplot(df["score"], kde=False)
_____no_output_____
MIT
python/redditscore.ipynb
AlexHartford/redditscore
As seen standard deviation and the distribution plot, there is a large distribution of data which makes the dataset skewed. In order to solve this log sclaling can be applied which might be useful later on.
mask = df["score"] > 0 sns.distplot(np.log1p(df["score"][mask]), kde=False)
_____no_output_____
MIT
python/redditscore.ipynb
AlexHartford/redditscore
The positive scores appear to be skewed with a significant majority of values being equal to 1.
mask = df["score"] < 0 sns.distplot(-np.log1p(-df["score"][mask]), kde=False)
_____no_output_____
MIT
python/redditscore.ipynb
AlexHartford/redditscore
The negative scores also seem a little skewed. Adding another score columnIn order to understand the data better and also create a logistic regression model a seperate column was created with the values of positive, negative or one score. Positive score being anything greater than 1, negative being anything less than ...
df['pn_score'] = "" for i in df['score'].index: if df['score'].at[i] > 1: df['pn_score'].at[i] = 'positive' elif float(df['score'].at[i]) <= 0: df['pn_score'].at[i] = 'negative' else: df['pn_score'].at[i] = 'one' df.head(10) pn_counts = df['pn_score'].value_counts() print(pn_cou...
positive 1053684 one 739088 negative 148314 Name: pn_score, dtype: int64
MIT
python/redditscore.ipynb
AlexHartford/redditscore
Again there is an issue with distribution here. The majority of dataset has positive score values, where negative scores are much less frequent. Logistic Regression ModelThere will be a combination of logistic regression and linear regression models used.The logistic model will be created based on the categorical scor...
log_vect = TfidfVectorizer(max_df = 0.95, min_df = 5, binary=True, stop_words='english') text_features = log_vect.fit_transform(df.body) print(text_features.shape) list(log_vect.vocabulary_)[:10] encoder = LabelEncoder() numerical_labels = encoder.fit_transform(df['pn_score']) training_X, testing_X, training_y, testin...
[2 2 2 ... 0 0 1] Accuracy: 0.5961028042005309 Classes: ['negative' 'one' 'positive'] Confusion Matrix: [[ 0 5712 31367] [ 0 37538 147234] [ 0 11687 251734]]
MIT
python/redditscore.ipynb
AlexHartford/redditscore
Since the data is so skewed a simple random over-sampling was used in order to increase the number of negative scores. The reason for using over-sampling as opposed to under-sampling is because we didn't want to loose any comments that could contribute as predictors. This does run the risk of overfitting the data howev...
count_pos, count_one, count_neg = df['pn_score'].value_counts() df_pos_score = df[df['pn_score'] == 'positive'] df_neg_score = df[df['pn_score'] == 'negative'] df_one_score = df[df['pn_score'] == 'one'] df_neg_score_over = df_neg_score.sample(count_one, replace=True) df_score_over = pd.concat([df_pos_score, df_neg_sc...
Random over-sampling: positive 1053684 one 739088 negative 739088 Name: pn_score, dtype: int64
MIT
python/redditscore.ipynb
AlexHartford/redditscore
Similarily to first model the comments need to be vectorized.
log_vect_over = TfidfVectorizer(max_df = 0.95, min_df = 5, binary=True, stop_words='english') text_features = log_vect_over.fit_transform(df_score_over.body) print(text_features.shape) list(log_vect_over.vocabulary_)[:10]
_____no_output_____
MIT
python/redditscore.ipynb
AlexHartford/redditscore
Now that the comments are turned into vectorized features they can be used in the logistic regression model. In order to achieve better results the random over-sampled data is used.
encoder = LabelEncoder() numerical_labels = encoder.fit_transform(df_score_over['pn_score']) training_X, testing_X, training_y, testing_y = train_test_split(text_features, numerical_labels, str...
[2 1 1 ... 0 2 0] Accuracy: 0.4774545196021897 Classes: ['negative' 'one' 'positive'] Confusion Matrix: [[ 33626 10591 140555] [ 16730 25612 142430] [ 13682 6765 242974]]
MIT
python/redditscore.ipynb
AlexHartford/redditscore
According to the confusion matrix the model struggles with determining a comment that has a score of 1 and usually mistakes it for a positive comment. It seems to perform the best with negative comments which could indicate overfitting of the data. Linear Regression ModelsThere will be two linear regression models, on...
pos_score_df = df[df.pn_score == 'positive'] pos_score_df.head()
_____no_output_____
MIT
python/redditscore.ipynb
AlexHartford/redditscore
Similarily to the logistic regression the comments need to be transformed into a vector of numerical values.
pos_vect = TfidfVectorizer(max_df = 0.95, min_df = 5, binary=True, stop_words='english') text_features = pos_vect.fit_transform(pos_score_df.body) print(text_features.shape) list(pos_vect.vocabulary_)[:10]
_____no_output_____
MIT
python/redditscore.ipynb
AlexHartford/redditscore
Now that the comments are vectorized, the model can be created. In order to eliminate the issue with large distribution noticed during the alaysis, the scores are log scaled.
X_train, X_test, y_train, y_test = train_test_split(text_features, np.log1p(pos_score_df['score'])) pos_linear_regression = SGDRegressor(max_iter=1500) pos_linear_regression.fit(X_train, y_train) test = pos_linear_regression.predict(X_test) mse = mean_squared_error(y_test, test) rmse = np.sqrt(mse) print() print("Posi...
Positive Score Model MSE: 0.8749582956086429 Positive Score Model RMSE: 0.935392054493004
MIT
python/redditscore.ipynb
AlexHartford/redditscore
Based on the rmse the model seems to preform pretty well. Negative ScoresThe second linear regression model will predict the negative scores. Similarily to the first model only the rows with negative scores are necessary and the comment need to be vectorized using those.
neg_score_df = df[df.pn_score == 'negative'] neg_score_df.head() neg_vect = TfidfVectorizer(max_df = 0.95, min_df = 5, binary=True, stop_words='english') text_features = neg_vect.fit_transform(neg_score_df.body) print(text_features.shape) list(neg_vect.vocabulary_)[:10] X_train, X_test, y_train, y_test = train_test_sp...
Negative Score Model MSE: 1.0130192799066775 Negative Score Model RMSE: 1.0064885890593482
MIT
python/redditscore.ipynb
AlexHartford/redditscore
The results are similar to the first model. Combining ModelsFirst the logistic regression model will be used to preditc whether or not the score is negative or positive, then depending on the outcome the appropriate linear regression model will be used to predict the score value
a = (["You sir a simple idiot. Or a Russian bot. Either way not worth an actual sentence on why I didn't vote for that loon."]) logistic_result = logistic_regression_over.predict(log_vect_over.transform(a)) print('Logistic Result: ') print(logistic_result) print() if(logistic_result) == 2: linear_result = pos_lin...
Logistic Result: [0] Linear Result: [-1.09910057]
MIT
python/redditscore.ipynb
AlexHartford/redditscore
Lastly, we want to pickle our models and vectorizers for deployment.
import pickle pickle.dump(logistic_regression_over, open('logreg.pkl', 'wb')) pickle.dump(pos_linear_regression, open('poslinreg.pkl', 'wb')) pickle.dump(neg_linear_regression, open('neglinreg.pkl', 'wb')) pickle.dump(log_vect_over, open('log_vect.pkl', 'wb')) pickle.dump(pos_vect, open('pos_vect.pkl', 'wb')) pickle.du...
_____no_output_____
MIT
python/redditscore.ipynb
AlexHartford/redditscore
`Note:` All assignment should be done inside the notebook (Double tap on each of this text to edit). `Question 1`: IRENE UMOH 17100310866 `Question 2`: What do you understand by natural language processing NLP is a subfield of artificial Intelligence (AI). In simple terms, Natural Language Processing is the ability...
a = ' In the end, he realized he could see sound and hear words. ' b = 'I ate a sock because people on the Internet told me to' c = 'She had a car and she also had a car' d = 'The skeleton had skeletons of his own in the closet' e = 'peered' a1=a.split(' ') b1=b.split(' ') c1=c.split(' ') d1=d.split(' ') e1=e.split('e'...
_____no_output_____
MIT
IRENE UMOH Assignment (Week 1 and 2).ipynb
ireneumoh24/ISM416
contiguous() is to arrange the tensor in a standard layout
a = torch.randn(3, 4, 5) b = a.permute(1, 2, 0) b_cont = b.contiguous() a_cont = a.contiguous() # a has "standard layout" (also known as C layout in numpy) descending strides, and no memory gaps (stride(i-1) == size(i)*stride(i)) print (a.shape, a.stride(), a.data_ptr()) # b has same storage as a (data_ptr), but has th...
_____no_output_____
MIT
mywork/Session 6 - GRU Language Model.ipynb
mingsqtt/textanalytics_ml
class NodoArbol: def __init__(self, dato, hijo_izq = None, hijo_der = None): self.dato = dato self.left = hijo_izq self.right = hijo_der class BinarySearchTree: def __init__(self): self.__root = None def insert(self, value): if self.__root == None: self.__root = NodoArbol(value, None,...
_____no_output_____
MIT
Tarea26.ipynb
Ed-10/Daa_2021_1
window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-59152712-8'); Explicit Runge Kutta methods and their Butcher tables Authors: Brandon Clark & Zach Etienne This tutorial notebook stores known explicit Runge Kutta-like methods as Butche...
# Step 1: Initialize needed Python modules import sympy as sp # SymPy: The Python computer algebra package upon which NRPy+ depends
_____no_output_____
BSD-2-Clause
Tutorial-RK_Butcher_Table_Dictionary.ipynb
stevenrbrandt/nrpytutorial
Step 2: The Family of Explicit Runge-Kutta-Like Schemes (Butcher Tables) [Back to [top](toc)\]$$\label{introbutcher}$$In general, a predictor-corrector method performs an estimate timestep from $n$ to $n+1$, using e.g., a Runge Kutta method, to get a prediction of the solution at timestep $n+1$. This is the "predictor...
# Step 2a: Generating a Dictionary of Butcher Tables for Explicit Runge Kutta Techniques # Initialize the dictionary Butcher_dict Butcher_dict = {}
_____no_output_____
BSD-2-Clause
Tutorial-RK_Butcher_Table_Dictionary.ipynb
stevenrbrandt/nrpytutorial
Step 2.a.i: Euler's Method [Back to [top](toc)\]$$\label{euler}$$[Forward Euler's method](https://en.wikipedia.org/w/index.php?title=Euler_method&oldid=896152463) is a first order Runge Kutta method. Euler's method obtains the solution $y(t)$ at time $t_{n+1}$ from $t_n$ via:$$y_{n+1} = y_{n} + \Delta tf(y_{n}, t_{n}...
# Step 2.a.i: Euler's Method Butcher_dict['Euler'] = ( [[sp.sympify(0)], ["", sp.sympify(1)]] , 1)
_____no_output_____
BSD-2-Clause
Tutorial-RK_Butcher_Table_Dictionary.ipynb
stevenrbrandt/nrpytutorial
Step 2.a.ii: RK2 Heun's Method [Back to [top](toc)\]$$\label{rktwoheun}$$[Heun's method](https://en.wikipedia.org/w/index.php?title=Heun%27s_method&oldid=866896936) is a second-order RK method that obtains the solution $y(t)$ at time $t_{n+1}$ from $t_n$ via:\begin{align}k_1 &= \Delta tf(y_n, t_n), \\k_2 &= \Delta tf(...
# Step 2.a.ii: RK2 Heun's Method Butcher_dict['RK2 Heun'] = ( [[sp.sympify(0)], [sp.sympify(1), sp.sympify(1)], ["", sp.Rational(1,2), sp.Rational(1,2)]] , 2)
_____no_output_____
BSD-2-Clause
Tutorial-RK_Butcher_Table_Dictionary.ipynb
stevenrbrandt/nrpytutorial
Step 2.a.iii: RK2 Midpoint Method [Back to [top](toc)\]$$\label{rk2mp}$$[Midpoint method](https://en.wikipedia.org/w/index.php?title=Midpoint_method&oldid=886630580) is a second-order RK method that obtains the solution $y(t)$ at time $t_{n+1}$ from $t_n$ via:\begin{align}k_1 &= \Delta tf(y_n, t_n), \\k_2 &= \Delta tf...
# Step 2.a.iii: RK2 Midpoint (MP) Method Butcher_dict['RK2 MP'] = ( [[sp.sympify(0)], [sp.Rational(1,2), sp.Rational(1,2)], ["", sp.sympify(0), sp.sympify(1)]] , 2)
_____no_output_____
BSD-2-Clause
Tutorial-RK_Butcher_Table_Dictionary.ipynb
stevenrbrandt/nrpytutorial
Step 2.a.iv: RK2 Ralston's Method [Back to [top](toc)\]$$\label{rk2ralston}$$Ralston's method (see [Ralston (1962)](https://www.ams.org/journals/mcom/1962-16-080/S0025-5718-1962-0150954-0/S0025-5718-1962-0150954-0.pdf), is a second-order RK method that obtains the solution $y(t)$ at time $t_{n+1}$ from $t_n$ via:\begi...
# Step 2.a.iv: RK2 Ralston's Method Butcher_dict['RK2 Ralston'] = ( [[sp.sympify(0)], [sp.Rational(2,3), sp.Rational(2,3)], ["", sp.Rational(1,4), sp.Rational(3,4)]] , 2)
_____no_output_____
BSD-2-Clause
Tutorial-RK_Butcher_Table_Dictionary.ipynb
stevenrbrandt/nrpytutorial
Step 2.a.v: Kutta's Third-order Method [Back to [top](toc)\]$$\label{rk3}$$[Kutta's third-order method](https://en.wikipedia.org/w/index.php?title=List_of_Runge%E2%80%93Kutta_methods&oldid=896594269) obtains the solution $y(t)$ at time $t_{n+1}$ from $t_n$ via:\begin{align}k_1 &= \Delta tf(y_n, t_n), \\k_2 &= \Delta ...
# Step 2.a.v: Kutta's Third-order Method Butcher_dict['RK3'] = ( [[sp.sympify(0)], [sp.Rational(1,2), sp.Rational(1,2)], [sp.sympify(1), sp.sympify(-1), sp.sympify(2)], ["", sp.Rational(1,6), sp.Rational(2,3), sp.Rational(1,6)]] , 3)
_____no_output_____
BSD-2-Clause
Tutorial-RK_Butcher_Table_Dictionary.ipynb
stevenrbrandt/nrpytutorial
Step 2.a.vi: RK3 Heun's Method [Back to [top](toc)\]$$\label{rk3heun}$$[Heun's third-order method](https://en.wikipedia.org/w/index.php?title=List_of_Runge%E2%80%93Kutta_methods&oldid=896594269) obtains the solution $y(t)$ at time $t_{n+1}$ from $t_n$ via:\begin{align}k_1 &= \Delta tf(y_n, t_n), \\k_2 &= \Delta tf(y_n...
# Step 2.a.vi: RK3 Heun's Method Butcher_dict['RK3 Heun'] = ( [[sp.sympify(0)], [sp.Rational(1,3), sp.Rational(1,3)], [sp.Rational(2,3), sp.sympify(0), sp.Rational(2,3)], ["", sp.Rational(1,4), sp.sympify(0), sp.Rational(3,4)]] , 3)
_____no_output_____
BSD-2-Clause
Tutorial-RK_Butcher_Table_Dictionary.ipynb
stevenrbrandt/nrpytutorial
Step 2.a.vii: RK3 Ralton's Method [Back to [top](toc)\]$$\label{rk3ralston}$$Ralston's third-order method (see [Ralston (1962)](https://www.ams.org/journals/mcom/1962-16-080/S0025-5718-1962-0150954-0/S0025-5718-1962-0150954-0.pdf), obtains the solution $y(t)$ at time $t_{n+1}$ from $t_n$ via:\begin{align}k_1 &= \Delta...
# Step 2.a.vii: RK3 Ralton's Method Butcher_dict['RK3 Ralston'] = ( [[0], [sp.Rational(1,2), sp.Rational(1,2)], [sp.Rational(3,4), sp.sympify(0), sp.Rational(3,4)], ["", sp.Rational(2,9), sp.Rational(1,3), sp.Rational(4,9)]] , 3)
_____no_output_____
BSD-2-Clause
Tutorial-RK_Butcher_Table_Dictionary.ipynb
stevenrbrandt/nrpytutorial
Step 2.a.viii: Strong Stability Preserving Runge-Kutta (SSPRK3) Method [Back to [top](toc)\]$\label{ssprk3}$The [Strong Stability Preserving Runge-Kutta (SSPRK3)](https://en.wikipedia.org/wiki/List_of_Runge%E2%80%93Kutta_methodsKutta's_third-order_method) method obtains the solution $y(t)$ at time $t_{n+1}$ from $t_n$...
# Step 2.a.viii: Strong Stability Preserving Runge-Kutta (SSPRK3) Method Butcher_dict['SSPRK3'] = ( [[0], [sp.sympify(1), sp.sympify(1)], [sp.Rational(1,2), sp.Rational(1,4), sp.Rational(1,4)], ["", sp.Rational(1,6), sp.Rational(1,6), sp.Rational(2,3)]] , 3)
_____no_output_____
BSD-2-Clause
Tutorial-RK_Butcher_Table_Dictionary.ipynb
stevenrbrandt/nrpytutorial
Step 2.a.ix: Classic RK4 Method [Back to [top](toc)\]$$\label{rkfour}$$The [classic RK4 method](https://en.wikipedia.org/w/index.php?title=Runge%E2%80%93Kutta_methods&oldid=894771467) obtains the solution $y(t)$ at time $t_{n+1}$ from $t_n$ via:\begin{align}k_1 &= \Delta tf(y_n, t_n), \\k_2 &= \Delta tf(y_n + \frac{1}...
# Step 2.a.vix: Classic RK4 Method Butcher_dict['RK4'] = ( [[sp.sympify(0)], [sp.Rational(1,2), sp.Rational(1,2)], [sp.Rational(1,2), sp.sympify(0), sp.Rational(1,2)], [sp.sympify(1), sp.sympify(0), sp.sympify(0), sp.sympify(1)], ["", sp.Rational(1,6), sp.Rational(1,3), sp.Rational(1,3), sp.Rational(1,6)]] , 4)
_____no_output_____
BSD-2-Clause
Tutorial-RK_Butcher_Table_Dictionary.ipynb
stevenrbrandt/nrpytutorial
Step 2.a.x: RK5 Dormand-Prince Method [Back to [top](toc)\]$$\label{dp5}$$The fifth-order Dormand-Prince (DP) method from the RK5(4) family (see [Dormand, J. R.; Prince, P. J. (1980)](https://www.sciencedirect.com/science/article/pii/0771050X80900133?via%3Dihub)) Butcher table is:$$\begin{array}{c|ccccccc} 0 & \\ ...
# Step 2.a.x: RK5 Dormand-Prince Method Butcher_dict['DP5'] = ( [[0], [sp.Rational(1,5), sp.Rational(1,5)], [sp.Rational(3,10),sp.Rational(3,40), sp.Rational(9,40)], [sp.Rational(4,5), sp.Rational(44,45), sp.Rational(-56,15), sp.Rational(32,9)], [sp.Rational(8,9), sp.Rational(19372,6561), sp.Rational(-25360,2187), sp...
_____no_output_____
BSD-2-Clause
Tutorial-RK_Butcher_Table_Dictionary.ipynb
stevenrbrandt/nrpytutorial
Step 2.a.xi: RK5 Dormand-Prince Method Alternative [Back to [top](toc)\]$$\label{dp5alt}$$The fifth-order Dormand-Prince (DP) method from the RK6(5) family (see [Dormand, J. R.; Prince, P. J. (1981)](https://www.sciencedirect.com/science/article/pii/0771050X81900103)) Butcher table is:$$\begin{array}{c|ccccccc} 0 ...
# Step 2.a.xi: RK5 Dormand-Prince Method Alternative Butcher_dict['DP5alt'] = ( [[0], [sp.Rational(1,10), sp.Rational(1,10)], [sp.Rational(2,9), sp.Rational(-2, 81), sp.Rational(20, 81)], [sp.Rational(3,7), sp.Rational(615, 1372), sp.Rational(-270, 343), sp.Rational(1053, 1372)], [sp.Rational(3,5), sp.Rational(3243, ...
_____no_output_____
BSD-2-Clause
Tutorial-RK_Butcher_Table_Dictionary.ipynb
stevenrbrandt/nrpytutorial
Step 2.a.xii: RK5 Cash-Karp Method [Back to [top](toc)\]$$\label{ck5}$$The fifth-order Cash-Karp Method (see [J. R. Cash, A. H. Karp. (1980)](https://dl.acm.org/citation.cfm?doid=79505.79507)) Butcher table is:$$\begin{array}{c|cccccc} 0 & \\ \frac{1}{5} & \frac{1}{5} & \\ \frac{3}{10} & \frac{3}{40} & \frac{9}{...
# Step 2.a.xii: RK5 Cash-Karp Method Butcher_dict['CK5'] = ( [[0], [sp.Rational(1,5), sp.Rational(1,5)], [sp.Rational(3,10),sp.Rational(3,40), sp.Rational(9,40)], [sp.Rational(3,5), sp.Rational(3,10), sp.Rational(-9,10), sp.Rational(6,5)], [sp.sympify(1), sp.Rational(-11,54), sp.Rational(5,2), sp.Rational(-70,27), sp...
_____no_output_____
BSD-2-Clause
Tutorial-RK_Butcher_Table_Dictionary.ipynb
stevenrbrandt/nrpytutorial
Step 2.a.xiii: RK6 Dormand-Prince Method [Back to [top](toc)\]$$\label{dp6}$$The sixth-order Dormand-Prince method (see [Dormand, J. R.; Prince, P. J. (1981)](https://www.sciencedirect.com/science/article/pii/0771050X81900103)) Butcher Table is$$\begin{array}{c|cccccccc} 0 & \\ \frac{1}{10} & \frac{1}{10} & \\ ...
# Step 2.a.xiii: RK6 Dormand-Prince Method Butcher_dict['DP6'] = ( [[0], [sp.Rational(1,10), sp.Rational(1,10)], [sp.Rational(2,9), sp.Rational(-2, 81), sp.Rational(20, 81)], [sp.Rational(3,7), sp.Rational(615, 1372), sp.Rational(-270, 343), sp.Rational(1053, 1372)], [sp.Rational(3,5), sp.Rational(3243, 5500), sp.Rat...
_____no_output_____
BSD-2-Clause
Tutorial-RK_Butcher_Table_Dictionary.ipynb
stevenrbrandt/nrpytutorial
Step 2.a.xiv: RK6 Luther's Method [Back to [top](toc)\]$$\label{l6}$$Luther's sixth-order method (see [H. A. Luther (1968)](http://www.ams.org/journals/mcom/1968-22-102/S0025-5718-68-99876-1/S0025-5718-68-99876-1.pdf)) Butcher table is:$$\begin{array}{c|ccccccc} 0 & \\ 1 & 1 & \\ \frac{1}{2} & \frac{3}{8} & ...
# Step 2.a.xiv: RK6 Luther's Method q = sp.sqrt(21) Butcher_dict['L6'] = ( [[0], [sp.sympify(1), sp.sympify(1)], [sp.Rational(1,2), sp.Rational(3,8), sp.Rational(1,8)], [sp.Rational(2,3), sp.Rational(8,27), sp.Rational(2,27), sp.Rational(8,27)], [(7 - q)/14, (-21 + 9*q)/392, (-56 + 8*q)/392, (336 -48*q)/392, (-63 + ...
_____no_output_____
BSD-2-Clause
Tutorial-RK_Butcher_Table_Dictionary.ipynb
stevenrbrandt/nrpytutorial
Step 2.a.xv: RK8 Dormand-Prince Method [Back to [top](toc)\]$$\label{dp8}$$The eighth-order Dormand-Prince Method (see [Dormand, J. R.; Prince, P. J. (1981)](https://www.sciencedirect.com/science/article/pii/0771050X81900103)) Butcher table is:$$\begin{array}{c|ccccccccc} 0 & \\ \frac{1}{18} & \frac{1}{18} & \\...
# Step 2.a.xv: RK8 Dormand-Prince Method Butcher_dict['DP8']=( [[0], [sp.Rational(1, 18), sp.Rational(1, 18)], [sp.Rational(1, 12), sp.Rational(1, 48), sp.Rational(1, 16)], [sp.Rational(1, 8), sp.Rational(1, 32), sp.sympify(0), sp.Rational(3, 32)], [sp.Rational(5, 16), sp.Rational(5, 16), sp.sympify(0), sp.Rational(-...
_____no_output_____
BSD-2-Clause
Tutorial-RK_Butcher_Table_Dictionary.ipynb
stevenrbrandt/nrpytutorial
Step 3: Code validation against `MoLtimestepping.RK_Butcher_Table_Dictionary` NRPy+ module [Back to [top](toc)\]$$\label{code_validation}$$As a code validation check, we verify agreement in the dictionary of Butcher tables between1. this tutorial and 2. the NRPy+ [MoLtimestepping.RK_Butcher_Table_Dictionary](../edit/M...
# Step 3: Code validation against MoLtimestepping.RK_Butcher_Table_Dictionary NRPy+ module import sys # Standard Python module for multiplatform OS-level functions from MoLtimestepping.RK_Butcher_Table_Dictionary import Butcher_dict as B_dict valid = True for key, value in Butcher_dict.items(): if Butcher_dict[key...
The dictionaries match!
BSD-2-Clause
Tutorial-RK_Butcher_Table_Dictionary.ipynb
stevenrbrandt/nrpytutorial
Step 4: Output this notebook to $\LaTeX$-formatted PDF file \[Back to [top](toc)\]$$\label{latex_pdf_output}$$The following code cell converts this Jupyter notebook into a proper, clickable $\LaTeX$-formatted PDF file. After the cell is successfully run, the generated PDF may be found in the root NRPy+ tutorial direct...
import cmdline_helper as cmd # NRPy+: Multi-platform Python command-line interface cmd.output_Jupyter_notebook_to_LaTeXed_PDF("Tutorial-RK_Butcher_Table_Dictionary")
Created Tutorial-RK_Butcher_Table_Dictionary.tex, and compiled LaTeX file to PDF file Tutorial-RK_Butcher_Table_Dictionary.pdf
BSD-2-Clause
Tutorial-RK_Butcher_Table_Dictionary.ipynb
stevenrbrandt/nrpytutorial
Load Audio files
al_train = AudioLoader(directory='../data/train') # al_test = AudioLoader(directory="../data/test",tts_file=r'/trsTest.txt') df_train_audio_data = al_train.get_audio_info_with_data() # df_test_audio_data = al_test.get_audio_info_with_data() # rp = ResultPickler() # rp.load_data("../models/LoadedAudioInfo.pkl") # data_...
_____no_output_____
MIT
notebooks/AudioManipulation.ipynb
DePacifier/AMH-STT
Preprocessing the audio Data- change the duration to the same size- convert channels to stereo by duplicating the other channel- standardize the sampling rate to the same one- Data Augmentation- Extract Features Convert Channels to Stereo by duplicating the other channel
am_train.convert_stereo_audio() am_train.get_audio_info() # am_train.get_audio_info().head().loc[0,"TimeSeriesData"].shape num_rows, y_len = am_train.get_audio_info().loc[0,"TimeSeriesData"].shape num_rows,y_len
_____no_output_____
MIT
notebooks/AudioManipulation.ipynb
DePacifier/AMH-STT
Change the duration to the same sizeFrom Our Data Exploration, we found that most frequent audio files has a duration between 2 to 6. And to reduce the bias, we will pad all the audio to make it equal in length with the maximum.
am_train.resize_audio() am_train.get_audio_info() am_train.get_audio_info().loc[0,"TimeSeriesData"].shape
_____no_output_____
MIT
notebooks/AudioManipulation.ipynb
DePacifier/AMH-STT
Standardize Sampling Rate
# count sampling rate frequencies pd.DataFrame({"count": df_train_audio_data.groupby("SamplingRate")["SamplingRate"].count()}) am_train.resample_audio() am_train.get_audio_info()
_____no_output_____
MIT
notebooks/AudioManipulation.ipynb
DePacifier/AMH-STT
Our SamplingRate is the same all around our data but we have resampled it to 44100. Now we have our processed data, we will save the preprocessed files to a folder in a .wav format.
am_train.write_wave_files("../data/train/wav/")
_____no_output_____
MIT
notebooks/AudioManipulation.ipynb
DePacifier/AMH-STT
Augmentation Feature Extraction We can now extract features but first we convert back to mono since the librosa library expects a monochannel audio.
# features = am_train.extract_features() # features.head() # vis.plot_spectrogram(features.loc[0,'Melspectogram']) # vis.plot_spectrogram(features.loc[0,'Melspectogram_db'])
_____no_output_____
MIT
notebooks/AudioManipulation.ipynb
DePacifier/AMH-STT
Fictitious Names Introduction:This time you will create a data again Special thanks to [Chris Albon](http://chrisalbon.com/) for sharing the dataset and materials.All the credits to this exercise belongs to him. In order to understand about it go to [here](https://blog.codinghorror.com/a-visual-explanation-of-sql-jo...
import pandas as pd
_____no_output_____
BSD-3-Clause
05_Merge/Fictitous Names/Exercises_with_solutions.ipynb
ktats/pandas_exercises
Step 2. Create the 3 DataFrames based on the followin raw data
raw_data_1 = { 'subject_id': ['1', '2', '3', '4', '5'], 'first_name': ['Alex', 'Amy', 'Allen', 'Alice', 'Ayoung'], 'last_name': ['Anderson', 'Ackerman', 'Ali', 'Aoni', 'Atiches']} raw_data_2 = { 'subject_id': ['4', '5', '6', '7', '8'], 'first_name': ['Billy', 'Brian', 'Bran', '...
_____no_output_____
BSD-3-Clause
05_Merge/Fictitous Names/Exercises_with_solutions.ipynb
ktats/pandas_exercises
Step 3. Assign each to a variable called data1, data2, data3
data3
_____no_output_____
BSD-3-Clause
05_Merge/Fictitous Names/Exercises_with_solutions.ipynb
ktats/pandas_exercises
Step 4. Join the two dataframes along rows and assign all_data
all_data = pd.concat([data1, data2]) all_data
_____no_output_____
BSD-3-Clause
05_Merge/Fictitous Names/Exercises_with_solutions.ipynb
ktats/pandas_exercises
Step 5. Join the two dataframes along columns and assing to all_data_col
all_data_col = pd.concat([data1, data2], axis = 1) all_data_col
_____no_output_____
BSD-3-Clause
05_Merge/Fictitous Names/Exercises_with_solutions.ipynb
ktats/pandas_exercises
Step 6. Print data3
data3
_____no_output_____
BSD-3-Clause
05_Merge/Fictitous Names/Exercises_with_solutions.ipynb
ktats/pandas_exercises
Step 7. Merge all_data and data3 along the subject_id value
pd.merge(all_data, data3, on='subject_id')
_____no_output_____
BSD-3-Clause
05_Merge/Fictitous Names/Exercises_with_solutions.ipynb
ktats/pandas_exercises
Step 8. Merge only the data that has the same 'subject_id' on both data1 and data2
pd.merge(data1, data2, on='subject_id', how='inner')
_____no_output_____
BSD-3-Clause
05_Merge/Fictitous Names/Exercises_with_solutions.ipynb
ktats/pandas_exercises
Step 9. Merge all values in data1 and data2, with matching records from both sides where available.
pd.merge(data1, data2, on='subject_id', how='outer')
_____no_output_____
BSD-3-Clause
05_Merge/Fictitous Names/Exercises_with_solutions.ipynb
ktats/pandas_exercises
In this example, we will compare development of a pairs trading strategy using backtrader and vectorbt.
import numpy as np import pandas as pd import datetime import collections import math import pytz import scipy.stats as st SYMBOL1 = 'PEP' SYMBOL2 = 'KO' FROMDATE = datetime.datetime(2017, 1, 1, tzinfo=pytz.utc) TODATE = datetime.datetime(2019, 1, 1, tzinfo=pytz.utc) PERIOD = 100 CASH = 100000 COMMPERC = 0.005 # 0.5%...
_____no_output_____
Apache-2.0
examples/PairsTrading.ipynb
zhnagchulan/vectorbt
Data
import vectorbt as vbt start_date = FROMDATE.replace(tzinfo=pytz.utc) end_date = TODATE.replace(tzinfo=pytz.utc) data = vbt.YFData.download([SYMBOL1, SYMBOL2], start=start_date, end=end_date) data = data.loc[(data.wrapper.index >= start_date) & (data.wrapper.index < end_date)] print(data.data[SYMBOL1].iloc[[0, -1]]) p...
Open High Low Close \ Date 2017-01-03 00:00:00+00:00 91.831129 91.962386 91.192316 91.577354 2018-12-31 00:00:00+00:00 102.775161 103.249160 101.604091 102.682220 ...
Apache-2.0
examples/PairsTrading.ipynb
zhnagchulan/vectorbt
backtrader Adapted version of https://github.com/mementum/backtrader/blob/master/contrib/samples/pair-trading/pair-trading.py
import backtrader as bt import backtrader.feeds as btfeeds import backtrader.indicators as btind class CommInfoFloat(bt.CommInfoBase): """Commission schema that keeps size as float.""" params = ( ('stocklike', True), ('commtype', bt.CommInfoBase.COMM_PERC), ('percabs', True), ) ...
1.07 s ± 16.3 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
Apache-2.0
examples/PairsTrading.ipynb
zhnagchulan/vectorbt
vectorbt Using Portfolio.from_orders
from numba import njit @njit def rolling_logret_zscore_nb(a, b, period): """Calculate the log return spread.""" spread = np.full_like(a, np.nan, dtype=np.float_) spread[1:] = np.log(a[1:] / a[:-1]) - np.log(b[1:] / b[:-1]) zscore = np.full_like(a, np.nan, dtype=np.float_) for i in range(a.shape[0])...
3.04 ms ± 5.31 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
Apache-2.0
examples/PairsTrading.ipynb
zhnagchulan/vectorbt
While Portfolio.from_orders is a very convenient and optimized function for simulating portfolios, it requires some prior steps to produce the size array. In the example above, we needed to manually run the calculation of the spread z-score, generate the signals from the z-score, build the size array from the signals, ...
from vectorbt.portfolio import nb as portfolio_nb from vectorbt.base.reshape_fns import flex_select_auto_nb from vectorbt.portfolio.enums import SizeType, Direction from collections import namedtuple Memory = namedtuple("Memory", ('spread', 'zscore', 'status')) Params = namedtuple("Params", ('period', 'upper', 'lower'...
4.44 ms ± 20.3 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
Apache-2.0
examples/PairsTrading.ipynb
zhnagchulan/vectorbt
Numba paradise (or hell?) - fastest
def simulate_nb_from_order_func(): """Simulate using `simulate_nb`.""" # iterate over 502 rows and 2 columns, each element is a potential order target_shape = vbt_close_price.shape # number of columns in the group - exactly two group_lens = np.array([2]) # build default call sequence (...
2.24 ms ± 3.67 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
Apache-2.0
examples/PairsTrading.ipynb
zhnagchulan/vectorbt
As you can see, writing Numba isn't straightforward and requires at least intermediate knowledge of NumPy. That's why Portfolio.from_orders and other class methods based on arrays are usually a good starting point. Multiple parameters Now, why waste all energy to port a strategy to vectorbt? Right, for hyperparameter ...
periods = np.arange(10, 105, 5) uppers = np.arange(1.5, 2.2, 0.1) lowers = -1 * np.arange(1.5, 2.2, 0.1) def simulate_mult_from_order_func(periods, uppers, lowers): """Simulate multiple parameter combinations using `Portfolio.from_order_func`.""" # Build param grid param_product = vbt.utils.params.create_pa...
2.16 s ± 16.3 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
Apache-2.0
examples/PairsTrading.ipynb
zhnagchulan/vectorbt
Predictions
'''preds = reg.predict_proba(X_test) preds_valid = clf.predict_proba(X_valid) print(f"BEST VALID SCORE FOR {dataset_name} : {clf.best_cost}") print(f"FINAL TEST SCORE FOR {dataset_name} : {test_auc}")'''
_____no_output_____
MIT
stock_fit.ipynb
LiziCyber/tabnet
Save and load Model
# save tabnet model saving_path_name = "./tabnet_model_test_1" saved_filepath = reg.save_model(saving_path_name) # define new model with basic parameters and load state dict weights loaded_reg = TabNetRegressor() loaded_reg.load_model(saved_filepath)
_____no_output_____
MIT
stock_fit.ipynb
LiziCyber/tabnet
Global explainability : feat importance summing to 1
reg.feature_importances_
_____no_output_____
MIT
stock_fit.ipynb
LiziCyber/tabnet
Local explainability and masks
explain_matrix, masks = reg.explain(X_valid) fig, axs = plt.subplots(1, 3, figsize=(20,20)) for i in range(3): axs[i].imshow(masks[i][:50]) axs[i].set_title(f"mask {i}")
_____no_output_____
MIT
stock_fit.ipynb
LiziCyber/tabnet
Modeling and Simulation in PythonChapter 1Copyright 2017 Allen DowneyLicense: [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0) JupyterWelcome to Modeling and Simulation, welcome to Python, and welcome to Jupyter.This is a Jupyter notebook, which is a development environmen...
# Configure Jupyter so figures appear in the notebook %matplotlib inline # Configure Jupyter to display the assigned value after an assignment %config InteractiveShell.ast_node_interactivity='last_expr_or_assign' # import functions from the modsim library from modsim import * print('If this cell runs successfully, i...
_____no_output_____
MIT
notebooks/chap01.ipynb
erhardt/ModSimPy
The first time you run this on a new installation of Python, it might produce a warning message in pink. That's probably ok, but if you get a message that says `modsim.py depends on Python 3.7 features`, that means you have an older version of Python, and some features in `modsim.py` won't work correctly.If you need a...
meter = UNITS.meter second = UNITS.second
_____no_output_____
MIT
notebooks/chap01.ipynb
erhardt/ModSimPy
To find out what other units are defined, type `UNITS.` (including the period) in the next cell and then press TAB. You should see a pop-up menu with a list of units. Create a variable named `a` and give it the value of acceleration due to gravity.
a = 9.8 * meter / second**2
_____no_output_____
MIT
notebooks/chap01.ipynb
erhardt/ModSimPy
Create `t` and give it the value 4 seconds.
t = 4 * second
_____no_output_____
MIT
notebooks/chap01.ipynb
erhardt/ModSimPy
Compute the distance a penny would fall after `t` seconds with constant acceleration `a`. Notice that the units of the result are correct.
a * t**2 / 2
_____no_output_____
MIT
notebooks/chap01.ipynb
erhardt/ModSimPy
**Exercise**: Compute the velocity of the penny after `t` seconds. Check that the units of the result are correct.
# Solution goes here
_____no_output_____
MIT
notebooks/chap01.ipynb
erhardt/ModSimPy
**Exercise**: Why would it be nonsensical to add `a` and `t`? What happens if you try?
# Solution goes here
_____no_output_____
MIT
notebooks/chap01.ipynb
erhardt/ModSimPy
The error messages you get from Python are big and scary, but if you read them carefully, they contain a lot of useful information.1. Start from the bottom and read up.2. The last line usually tells you what type of error happened, and sometimes additional information.3. The previous lines are a "traceback" of what ...
h = 381 * meter
_____no_output_____
MIT
notebooks/chap01.ipynb
erhardt/ModSimPy
Compute the time it would take a penny to fall, assuming constant acceleration.$ a t^2 / 2 = h $$ t = \sqrt{2 h / a}$
t = sqrt(2 * h / a)
_____no_output_____
MIT
notebooks/chap01.ipynb
erhardt/ModSimPy
Given `t`, we can compute the velocity of the penny when it lands.$v = a t$
v = a * t
_____no_output_____
MIT
notebooks/chap01.ipynb
erhardt/ModSimPy
We can convert from one set of units to another like this:
mile = UNITS.mile hour= UNITS.hour v.to(mile/hour)
_____no_output_____
MIT
notebooks/chap01.ipynb
erhardt/ModSimPy
**Exercise:** Suppose you bring a 10 foot pole to the top of the Empire State Building and use it to drop the penny from `h` plus 10 feet.Define a variable named `foot` that contains the unit `foot` provided by `UNITS`. Define a variable named `pole_height` and give it the value 10 feet.What happens if you add `h`, wh...
# Solution goes here # Solution goes here
_____no_output_____
MIT
notebooks/chap01.ipynb
erhardt/ModSimPy
**Exercise:** In reality, air resistance limits the velocity of the penny. At about 18 m/s, the force of air resistance equals the force of gravity and the penny stops accelerating.As a simplification, let's assume that the acceleration of the penny is `a` until the penny reaches 18 m/s, and then 0 afterwards. What i...
# Solution goes here # Solution goes here # Solution goes here # Solution goes here # Solution goes here
_____no_output_____
MIT
notebooks/chap01.ipynb
erhardt/ModSimPy
Global Imports
%pylab inline
Populating the interactive namespace from numpy and matplotlib
MIT
Notebooks/HNSCC_Imports.ipynb
theandygross/CancerData
External Package Imports
import os as os import pickle as pickle import pandas as pd
_____no_output_____
MIT
Notebooks/HNSCC_Imports.ipynb
theandygross/CancerData
Module Imports
from Stats.Scipy import * from Stats.Survival import * from Helpers.Pandas import * from Figures.FigureHelpers import * from Figures.Pandas import * from Figures.Boxplots import * from Figures.Survival import draw_survival_curve, survival_and_stats from Figures.Survival import draw_survival_curves from Figures.Surviva...
_____no_output_____
MIT
Notebooks/HNSCC_Imports.ipynb
theandygross/CancerData
Tweaking Display Parameters
pd.set_option('precision', 3) pd.set_option('display.width', 300) plt.rcParams['font.size'] = 12 '''Color schemes for paper taken from http://colorbrewer2.org/''' colors = plt.rcParams['axes.color_cycle'] colors_st = ['#CA0020', '#F4A582', '#92C5DE', '#0571B0'] colors_th = ['#E66101', '#FDB863', '#B2ABD2', '#5E3C99']
_____no_output_____
MIT
Notebooks/HNSCC_Imports.ipynb
theandygross/CancerData
Function to Pull a Firehose Run Container
def get_run(firehose_dir, version='Latest'): ''' Helper to get a run from the file-system. ''' path = '{}/ucsd_analyses'.format(firehose_dir) if version is 'Latest': version = sorted(os.listdir(path))[-1] run = pickle.load(open('{}/{}/RunObject.p'.format(path, version), 'rb')) retur...
_____no_output_____
MIT
Notebooks/HNSCC_Imports.ipynb
theandygross/CancerData
Read In Data Here we read in the pre-processed data that we downloaded and initialized in the [download_data notebook](download_data.ipynb).
print 'populating namespace with data' OUT_PATH = '/cellar/users/agross/TCGA_Code/CancerData/Data' RUN_DATE = '2014_07_15' VERSION = 'all' CANCER = 'HNSC' FIGDIR = '../Figures/' if not os.path.isdir(FIGDIR): os.makedirs(FIGDIR) run_path = '{}/Firehose__{}/'.format(OUT_PATH, RUN_DATE) run = get_run(run_path, 'Run_'...
_____no_output_____
MIT
Notebooks/HNSCC_Imports.ipynb
theandygross/CancerData
Update Clinical Data
from Processing.ProcessClinicalDataPortal import update_clinical_object p = '/cellar/users/agross/TCGA_Code/TCGA/Data' path = p + '/Followup_R9/HNSC/' clinical = update_clinical_object(clinical, path) clinical.clinical.shape #hpv = clinical.hpv surv = clinical.survival.survival_5y age = clinical.clinical.age.astype(f...
_____no_output_____
MIT
Notebooks/HNSCC_Imports.ipynb
theandygross/CancerData
HPV Data
p = '/cellar/users/agross/TCGA_Code/TCGA/' hpv_all = pd.read_csv(p + '/Extra_Data/hpv_summary_3_20_13_distribute.csv', index_col=0) hpv = hpv_all.Molecular_HPV.map({0:'HPV-', 1:'HPV+'}) hpv.name = 'HPV' hpv_seq = hpv status = clinical.clinical[['hpvstatusbyishtesting','hpvstatusbyp16testing']] status = status.replace('...
_____no_output_____
MIT
Notebooks/HNSCC_Imports.ipynb
theandygross/CancerData
این دفترچه تنها جهت تمرین در کنار مطالعه‌ی درس‌نامه اضافه شده است.
import numpy as np i = np.identity(3) b = i == 0 print(i[b].shape) x = np.full((3, 3), 8) print(np.dot(i, x))
[[8. 8. 8.] [8. 8. 8.] [8. 8. 8.]]
MIT
quera/13609/46444/solution.ipynb
TheMn/Quera-College-ML-Course
3 - Displaying Histograms and Crossplots Created by: Andy McDonald The following tutorial illustrates how to display well data from a LAS file on histograms and crossplots. Loading Well Data from CSV The following cells load data in from a CSV file and replace the null values (-999.25) with Not a Number (NaN) values....
import os import pandas as pd import numpy as np import matplotlib.pyplot as plt root = '/users/kai/desktop/data_science/data/dongara' well_name = 'dongara_20' file_format = '.csv' well = pd.read_csv(os.path.join(root,well_name+file_format), header=0) well.replace(-999.25, np.nan, inplace=True) cols = well.columns[well...
_____no_output_____
MIT
03 - Displaying Histograms and Crossplots.ipynb
will6309/Petrophysics-Python-Series
Displaying data on a histogram Displaying a simple histogram can be done by calling the .hist function on the well dataframe and specifying the column.
well.hist(column="GR")
_____no_output_____
MIT
03 - Displaying Histograms and Crossplots.ipynb
will6309/Petrophysics-Python-Series
The number of bins can be controled by the bins parameter:
well.hist(column="GR", bins = 30)
_____no_output_____
MIT
03 - Displaying Histograms and Crossplots.ipynb
will6309/Petrophysics-Python-Series
We can also change the opacity of the bars by using the alpha parameter:
well.hist(column="GR", bins = 30, alpha = 0.5)
_____no_output_____
MIT
03 - Displaying Histograms and Crossplots.ipynb
will6309/Petrophysics-Python-Series
Plotting multiple histograms on one plot It can be more efficient to loop over the columns (curves) within the dataframe and create a plot with multiple histograms, rather than duplicating the previous line multiple times. First we need to create a list of our curve names.
cols_to_plot = list(well)
_____no_output_____
MIT
03 - Displaying Histograms and Crossplots.ipynb
will6309/Petrophysics-Python-Series
We can remove the depth curve from our list and focus on our curves. The same line can be applied to other curves that need removing.
cols_to_plot.remove("DEPT") #Setup the number of rows and columns for our plot rows = 5 cols = 2 fig=plt.figure(figsize=(10,10)) for i, feature in enumerate(cols_to_plot): ax=fig.add_subplot(rows,cols,i+1) well[feature].hist(bins=20,ax=ax,facecolor='green', alpha=0.6) ax.set_title(feature+" Distribution")...
_____no_output_____
MIT
03 - Displaying Histograms and Crossplots.ipynb
will6309/Petrophysics-Python-Series
Displaying data on a crossplot (Scatterplot) As seen in the first notebook, we can display a crossplot by simply doing the following. using the c argument we can add a third curve to colour the data.
well.plot(kind="scatter", x="NPHI", y="RHOB", c="GR", colormap="YlOrRd_r", ylim=(3,2))
_____no_output_____
MIT
03 - Displaying Histograms and Crossplots.ipynb
will6309/Petrophysics-Python-Series
We can take the above crossplot and create a 3D version. First we need to make sure the Jupyter notbook is setup for displaying interactive 3D plots using the following command.
%matplotlib inline from mpl_toolkits.mplot3d import Axes3D fig = plt.figure(figsize=(5,5)) ax = fig.add_subplot(111, projection="3d") ax.scatter(well["NPHI"], well["RHOB"], well["GR"], alpha= 0.3, c="r")
_____no_output_____
MIT
03 - Displaying Histograms and Crossplots.ipynb
will6309/Petrophysics-Python-Series
If we want to have multiple crossplots on view, we can do this by:
fig, ax = plt.subplots(figsize=(10,10)) ax1 = plt.subplot2grid((2,2), (0,0), rowspan=1, colspan=1) ax2 = plt.subplot2grid((2,2), (0,1), rowspan=1, colspan=1) ax3 = plt.subplot2grid((2,2), (1,0), rowspan=1, colspan=1) ax4 = plt.subplot2grid((2,2), (1,1), rowspan=1, colspan=1) ax1.scatter(x= "NPHI", y= "RHOB", data= we...
_____no_output_____
MIT
03 - Displaying Histograms and Crossplots.ipynb
will6309/Petrophysics-Python-Series
Ranking multiple systemsIn this notebook, we consider the situation where we have scores from multiple different automated scoring systems, each with different levels of performance. We evaluate these systems against the same as well as different pairs of raters and show that:1. When using the same pair of raters to ...
import itertools import json import pandas as pd import numpy as np import seaborn as sns from matplotlib import pyplot as plt from pathlib import Path from rsmtool.utils.prmse import prmse_true from simulation.dataset import Dataset from simulation.utils import (compute_agreement_one_system_one_rater_pair, ...
_____no_output_____
MIT
notebooks/ranking_multiple_systems.ipynb
EducationalTestingService/prmse-simulations
Step 1: SetupTo set up the experiment, we first load the dataset we have already created and saved in the `making_a_dataset.ipynb` notebook and use that for this experiment.For convenience and replicability, we have pre-defined many of the parameters that are used in our notebooks and saved them in the file `settings....
# load the dataset file dataset = Dataset.from_file('../data/default.dataset') # let's remind ourselves what the dataset looks like print(dataset) # load the experimental settings file experiment_settings = json.load(open('settings.json', 'r')) # now get the data frames for our loaded dataset df_scores, df_rater_metad...
_____no_output_____
MIT
notebooks/ranking_multiple_systems.ipynb
EducationalTestingService/prmse-simulations
Step 2: Evaluate all systems against same pair of ratersFirst, we evaluate the scores assigned by all our simulated systems in the dataset against the same pair of simulated human raters from the dataset. To simulate the more usual scenario, we sample two raters from the "average" rater category.
# define our pre-selected rater category chosen_rater_category = "average" # get the list of rater IDs in this category rater_ids = df_rater_metadata[df_rater_metadata['rater_category'] == chosen_rater_category]['rater_id'] # choose 2 rater IDs randomly from these chosen_rater_pair = rater_id1, rater_id2 = rater_ids....
we chose the rater pair: ['h_107', 'h_101']
MIT
notebooks/ranking_multiple_systems.ipynb
EducationalTestingService/prmse-simulations
Now, we compute the agreement metrics as well as the PRMSE values for all of the simulated systems in our dataset against our pre-selected rater pair.
# initialize some lists that will hold our metric and PRMSE values for each category metric_dfs = [] prmse_series = [] # iterate over each system category for system_category in dataset.system_categories: # get the system IDs that belong to this system category system_ids_for_category = df_system_metadata...
_____no_output_____
MIT
notebooks/ranking_multiple_systems.ipynb
EducationalTestingService/prmse-simulations
Now, we need to use each metric to compute the ranks of each of the systems based on the values.
# compute the ranks given the metric values df_ranks_same_rater_pair = compute_ranks_from_metrics(df_metrics_same_rater_pair_with_categories) # now compute a longer verssion of this rank data frame that is more amenable to plotting df_ranks_same_rater_pair_long = df_ranks_same_rater_pair.melt(id_vars=['system_category...
_____no_output_____
MIT
notebooks/ranking_multiple_systems.ipynb
EducationalTestingService/prmse-simulations