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 |
|---|---|---|---|---|---|
In order to take advantage of the speed increases provided by GPUs, this code has been modified in order to run on Google Colab notebooks. In order to do this, the user needs to set the *google_colab_used* parameter to **True**. For usage on a local machine, this needs to be set to **False**If used on a google colab no... | google_colab_used = True
if google_colab_used == True:
# Load the Drive helper and mount
from google.colab import drive
# This will prompt for authorization.
drive.mount('/content/drive')
data_drive = '/content/drive/My Drive/JA-ML/data'
os.chdir(data_drive)
else:
os.chdir("./data") | Go to this URL in a browser: https://accounts.google.com/o/oauth2/auth?client_id=947318989803-6bn6qk8qdgf4n4g3pfee6491hc0brc4i.apps.googleusercontent.com&redirect_uri=urn%3aietf%3awg%3aoauth%3a2.0%3aoob&response_type=code&scope=email%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdocs.test%20https%3a%2f%2fwww.googleapis.c... | BSD-3-Clause | MAIN-AA2AR.ipynb | SABS-R3-projects/JA-ML |
2. Data Pre-Processing This section imports all the required datasets as pandas dataframes, concatenates them, after which it pre-processes them by eliminating all non-numerical data and columns which contain the same data-values. This script also creates the input dataset and the labeled output dataset. | def data_preprocessing():
'''
This reads all the input datasets, pre-processes them and then generates the input dataset and the labelled dataset.
Args:
None
Returns:
X (ndarray): A 2D array containing the input processed data
y (ndarray): A 1D array containing... | _____no_output_____ | BSD-3-Clause | MAIN-AA2AR.ipynb | SABS-R3-projects/JA-ML |
3. Model Evaluation This section produces the ROC plot, as well as several other performance metrics, including the classifier scores, the log-loss for each classifier, the confusion matrix and the classification report including the f1 score. The f1 score can be interpreted as a weighted average of the precision and ... | def ROC_plotting(title, y_test, y_score):
'''
This function generates the ROC plot for a given model.
Args:
title (string): String represending the name of the model.
y_test (ndarray): 1D array of test dataset
y_score (ndarray): 1D array of model-predicted labels
... | _____no_output_____ | BSD-3-Clause | MAIN-AA2AR.ipynb | SABS-R3-projects/JA-ML |
4. Logistic regression, linear and quadratic discriminant analysis 4.1. Logistic regression Logistic regression (logit regression, log-liner classifier) is a generalized linear model used for classification that uses a log-linear link function to model the outcome of a binary reponse variable $\mathbf{y}$ using a sin... | def LogReg(X_train, y_train, X_test):
"""Classification using logistic regression
Args:
X_train: Predictor or feature values used for training
y_train: Response values used for training
X_test: Predictor or feature values used for predicting the response values using the classifier
... | The average test set score for Logistic Regression is: 0.9956535334584116
The average test log-loss for Logistic Regression is: 0.12960241248550722
The average AUC for Logistic Regression is: 0.998101599065739
| BSD-3-Clause | MAIN-AA2AR.ipynb | SABS-R3-projects/JA-ML |
4.2. Linear discriminant analysis LDA employs Bayes' theorem to fit a Gaussian density to each class of data. The classes are assumed to have the same covariance matrix. This generates a linear decision boundry. | def LDA(X_train, y_train, X_test):
"""Classification using LDA
Args:
X_train: Predictor or feature values used for training
y_train: Response values used for training
X_test: Predictor or feature values used for predicting the response values using the classifier
Returns:
... | The average test set score for Linear Discriminant is: 0.9924015009380863
The average test log-loss for Linear Discriminant is: 0.17820456731990192
The average AUC for Linear Discriminant is: 0.9866419619481748
| BSD-3-Clause | MAIN-AA2AR.ipynb | SABS-R3-projects/JA-ML |
4.3. Quadratic discriminant analysis QDA is similar to LDA, however it employs a quadratic decision boundary, rather than a linear one. | def QDA(X_train, y_train, X_test):
"""Classification using QDA
Args:
X_train: Predictor or feature values used for training
y_train: Response values used for training
X_test: Predictor or feature values used for predicting the response values using the classifier
Returns:
... | The average test set score for Quadratic Discriminant is: 0.015916197623514698
The average test log-loss for Quadratic Discriminant is: 34.05355944460625
The average AUC for Quadratic Discriminant is: 0.5002377555872564
| BSD-3-Clause | MAIN-AA2AR.ipynb | SABS-R3-projects/JA-ML |
5. Decision trees and random forest 5.1. Single decision tree Decision trees are a non-parametric learning method used for both classification and regression. The advantages of decision trees are that they are easy to understand and they can be used for a broad range of data. However, the main disadvantages are that ... | def DecisionTree(X_train, y_train, X_test):
"""Classification using Decision Tree
Args:
X_train: Predictor or feature values used for training
y_train: Response values used for training
X_test: Predictor or feature values used for predicting the response values using the classifie... | The average test set score for Decision Tree is: 0.9939337085678549
The average test log-loss for Decision Tree is: 0.1998053027747743
The average AUC for Decision Tree is: 0.9290531861981515
| BSD-3-Clause | MAIN-AA2AR.ipynb | SABS-R3-projects/JA-ML |
5.2. Random forest Radnom forest explanation... | def RandomForest(X_train, y_train, X_test):
"""Classification using Random Forest
Args:
X_train: Predictor or feature values used for training
y_train: Response values used for training
X_test: Predictor or feature values used for predicting the response values using the classifie... | The average test set score for Random Forest is: 0.9964040025015635
The average test log-loss for Random Forest is: 0.10800117696970293
The average AUC for Random Forest is: 0.9960456053475877
| BSD-3-Clause | MAIN-AA2AR.ipynb | SABS-R3-projects/JA-ML |
6. Neural Network A Neural Network, also known as a multi-layered perceptron, is a supervised learning algorithm that learns a function, which is trained using a set of features and targets. A neural network can learns a non-linear function approximator, allowing classification of data. Between the input and output la... | def neural_network(X_train, X_test, y_train, y_test):
'''
This function takes in the input datasets, creates a neural network, trains and then tests it.
Written by AndreiRoibu
Args:
X_train (ndarray): 2D array of input dataset used for training
X_test (ndarray): 2D array o... | The average test set score for Neural Network is: 0.9978111319574735
The average test log-loss for Neural Network is: 0.08100175783390838
The average AUC for Neural Network is: 0.9996957457235878
| BSD-3-Clause | MAIN-AA2AR.ipynb | SABS-R3-projects/JA-ML |
Lecture 8: p-hacking and Multiple Comparisons[J. Nathan Matias](https://github.com/natematias)[SOC412](https://natematias.com/courses/soc412/), February 2019In Lecture 8, we discussed Stephanie Lee's story about [Brian Wansink](https://www.buzzfeednews.com/article/stephaniemlee/brian-wansink-cornell-p-hacking.btypwrDw... | options("scipen"=9, "digits"=4)
library(dplyr)
library(MASS)
library(ggplot2)
library(rlang)
library(corrplot)
library(Hmisc)
library(tidyverse)
library(viridis)
library(fabricatr)
library(DeclareDesign)
## Installed DeclareDesign 0.13 using the following command:
# install.packages("DeclareDesign", dependencies = TRUE... | _____no_output_____ | MIT | 2019/lecture-code/lecture 8 - Multiple Comparisons.ipynb | notconfusing/design-governance-experiments |
What is a p-value? A p-value (which can be calculated differently for different kinds of statistical tests) is an estimate of the probability of rejecting a null hypothesis. When testing differences in means, we are usually testing the null hypothesis of no difference between the two distributions. In those cases, the... | ### GENERATE n.samples simulations at n.sample.size observations
### using normal distributions at the specified means
### and record the difference in means and the p value of the observations
#
# `@diff.df: the dataframe to pass in
# `@n.sample.size: the sample sizes to draw from a normal distribution
generate.... | [1] "How often is the p-value < 0.05?"
| MIT | 2019/lecture-code/lecture 8 - Multiple Comparisons.ipynb | notconfusing/design-governance-experiments |
Illustrating A Difference in Means (first with a small sample size) | #expand.grid
small.sample.diff.df = data.frame(a.mean = 1, a.sd = 1,
b.mean = 1.2, b.sd = 1,
id=seq(n.samples),
mean.diff = NA,
p.value = NA)
small.sample.diff.df <- generate.n.samples(smal... | [1] "If we published all experiment results, what we would we think the true effect would be?"
| MIT | 2019/lecture-code/lecture 8 - Multiple Comparisons.ipynb | notconfusing/design-governance-experiments |
Illustrating A Difference in Means (with a larger sample size) | #expand.grid
larger.sample.diff.df = data.frame(a.mean = 1, a.sd = 1,
b.mean = 1.2, b.sd = 1,
id=seq(n.samples),
mean.diff = NA,
p.value = NA)
larger.sample.diff.df <- generate.n.samples(la... | [1] "How often is the p-value < 0.05?"
| MIT | 2019/lecture-code/lecture 8 - Multiple Comparisons.ipynb | notconfusing/design-governance-experiments |
Illustrating a Difference in Means (with an adequately large sample size) | adequate.sample.diff.df = data.frame(a.mean = 1, a.sd = 1,
b.mean = 1.2, b.sd = 1,
id=seq(n.samples),
mean.diff = NA,
p.value = NA)
adequate.sample.diff.df <- generate.n.samples(larger.samp... | [1] "If we only published statistically-significant results, what we would we think the true effect would be?"
| MIT | 2019/lecture-code/lecture 8 - Multiple Comparisons.ipynb | notconfusing/design-governance-experiments |
The Problem of Multiple ComparisonsIn the above example, I demonstrated that across 100 samples under the null hypothesis and a decision rule of p = 0.05, roughly 5% of the results are statistically significant. This is similarly true for a single experiment with multiple outcome variables. | ## Generate n normally distributed outcome variables with no difference on average
#
#` @num.samples: sample size for the dataframe
#` @num.columns: how many outcome variables to observe
#` @common.mean: the mean of the outcomes
#` @common.sd: the standard deviation of the outcomes
generate.n.outcomes.null <- functi... | _____no_output_____ | MIT | 2019/lecture-code/lecture 8 - Multiple Comparisons.ipynb | notconfusing/design-governance-experiments |
With 10 outcome variables, if we look for correlations between every outcomes, we expect to see 5% false positives on average under the null hypothesis. | set.seed(487)
## generate the data
null.10.obs <- generate.n.outcomes.null(100, 10, 1, 3)
null.10.obs$id <- NULL
null.correlations <- cor(null.10.obs, method="pearson")
null.pvalues <- cor.mtest(null.10.obs, conf.level = 0.95, method="pearson")$p
corrplot(cor(null.10.obs, method="pearson"), sig.level = 0.05, p.mat = nu... | _____no_output_____ | MIT | 2019/lecture-code/lecture 8 - Multiple Comparisons.ipynb | notconfusing/design-governance-experiments |
With multiple comparisons, increasing the sample size does not make the problem go away. Here, we use a sample of 10000 instead of 100 | null.10.obs.large <- generate.n.outcomes.null(10000, 10, 1, 3)
null.10.obs.large$id <- NULL
null.correlations <- cor(null.10.obs.large, method="pearson")
null.pvalues <- cor.mtest(null.10.obs.large, conf.level = 0.95, method="pearson")$p
corrplot(cor(null.10.obs.large, method="pearson"), sig.level = 0.05, p.mat = null.... | _____no_output_____ | MIT | 2019/lecture-code/lecture 8 - Multiple Comparisons.ipynb | notconfusing/design-governance-experiments |
Power AnalysisA power analysis is a process for deciding what sample size to use based on the chance of observing the minimum effect you are looking for in your study. This power analysis uses [DeclareDesign](http://declaredesign.org/). Another option is the [egap Power Analysis page.](https://egap.org/content/power-a... | mean.a <- 0
effect.b <- 0.1
sample.size <- 500
design <-
declare_population(
N = sample.size
) +
declare_potential_outcomes(
YA_Z_0 = rnorm(n=N, mean = mean.a, sd=1),
YA_Z_1 = rnorm(n=N, mean = mean.a + effect.b, sd=1)
) +
declare_assignment(num_arms = 2,
... | _____no_output_____ | MIT | 2019/lecture-code/lecture 8 - Multiple Comparisons.ipynb | notconfusing/design-governance-experiments |
Part 2 | def test_must_have_double(value):
""" Must have at least one pair of digits """
value = str(value)
for v in set(value):
if "{0}{0}".format(v[0]) in value and "{0}{0}{0}".format(v[0]) not in value:
return True
return False
def test_all_part2(value):
return test_all(value... | _____no_output_____ | MIT | solutions/2019/kws/04.ipynb | kws/AdventOfCode |
ClassificationWe'll take a tour of the methods for classification in sklearn. First let's load a toy dataset to use: | from sklearn.datasets import load_breast_cancer
breast = load_breast_cancer() | _____no_output_____ | MIT | ML1 - Scikit Learn Methods (Complete).ipynb | oskali/SoftwareTools_MBAN21_Python |
Let's take a look | # Convert it to a dataframe for better visuals
df = pd.DataFrame(breast.data)
df.columns = breast.feature_names
df | _____no_output_____ | MIT | ML1 - Scikit Learn Methods (Complete).ipynb | oskali/SoftwareTools_MBAN21_Python |
And now look at the targets | print(breast.target_names)
breast.target | ['malignant' 'benign']
| MIT | ML1 - Scikit Learn Methods (Complete).ipynb | oskali/SoftwareTools_MBAN21_Python |
Classification Trees Using the scikit learn models is basically the same as in Julia's ScikitLearn.jl | from sklearn.tree import DecisionTreeClassifier
cart = DecisionTreeClassifier(max_depth=2, min_samples_leaf=140)
cart.fit(breast.data, breast.target) | _____no_output_____ | MIT | ML1 - Scikit Learn Methods (Complete).ipynb | oskali/SoftwareTools_MBAN21_Python |
Here's a helper function to plot the trees. Installing Graphviz (tedious) Windows1. Download graphviz from https://graphviz.gitlab.io/_pages/Download/Download_windows.html2. Install it by running the .msi file3. Set the pat variable: (a) Go to Control Panel > System and Security > System > Advanced System Settings ... | import graphviz
import sklearn.tree
def visualize_tree(sktree):
dot_data = sklearn.tree.export_graphviz(sktree, out_file=None,
filled=True, rounded=True,
special_characters=False,
feature_names=df.columns)... | _____no_output_____ | MIT | ML1 - Scikit Learn Methods (Complete).ipynb | oskali/SoftwareTools_MBAN21_Python |
We can get the label predictions with the `.predict` method | labels = cart.predict(breast.data)
labels | _____no_output_____ | MIT | ML1 - Scikit Learn Methods (Complete).ipynb | oskali/SoftwareTools_MBAN21_Python |
And similarly the predicted probabilities with `.predict_proba` | probs = cart.predict_proba(breast.data)
probs | _____no_output_____ | MIT | ML1 - Scikit Learn Methods (Complete).ipynb | oskali/SoftwareTools_MBAN21_Python |
Just like in Julia, the probabilities are returned for each class | probs.shape | _____no_output_____ | MIT | ML1 - Scikit Learn Methods (Complete).ipynb | oskali/SoftwareTools_MBAN21_Python |
We can extract the second column of the probs by slicing, just like how we did it in Julia | probs = cart.predict_proba(breast.data)[:,1]
probs | _____no_output_____ | MIT | ML1 - Scikit Learn Methods (Complete).ipynb | oskali/SoftwareTools_MBAN21_Python |
To evaluate the model, we can use functions from `sklearn.metrics` | from sklearn.metrics import roc_auc_score, accuracy_score, confusion_matrix
roc_auc_score(breast.target, probs)
accuracy_score(breast.target, labels)
confusion_matrix(breast.target, labels)
from lazypredict.Supervised import LazyClassifier
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection imp... | C:\Users\omars\AppData\Roaming\Python\Python37\site-packages\sklearn\utils\deprecation.py:143: FutureWarning: The sklearn.utils.testing module is deprecated in version 0.22 and will be removed in version 0.24. The corresponding classes / functions should instead be imported from sklearn.utils. Anything that cannot be ... | MIT | ML1 - Scikit Learn Methods (Complete).ipynb | oskali/SoftwareTools_MBAN21_Python |
Random Forests and BoostingWe use random forests and boosting in the same way as CART | from sklearn.ensemble import RandomForestClassifier
forest = RandomForestClassifier(n_estimators=100)
forest.fit(breast.data, breast.target)
labels = forest.predict(breast.data)
probs = forest.predict_proba(breast.data)[:,1]
print(roc_auc_score(breast.target, probs))
print(accuracy_score(breast.target, labels))
confusi... | 1.0
1.0
| MIT | ML1 - Scikit Learn Methods (Complete).ipynb | oskali/SoftwareTools_MBAN21_Python |
Neural Networks | from sklearn.neural_network import MLPClassifier
mlp = MLPClassifier(max_iter=1000)
mlp.fit(breast.data, breast.target)
labels = mlp.predict(breast.data)
probs = mlp.predict_proba(breast.data)[:,1]
print(roc_auc_score(breast.target, probs))
print(accuracy_score(breast.target, labels))
confusion_matrix(breast.target, la... | Epoch 1/10
29/29 [==============================] - 0s 6ms/step - loss: 36.4088 - accuracy: 0.3516
Epoch 2/10
29/29 [==============================] - 0s 3ms/step - loss: 17.8082 - accuracy: 0.3758
Epoch 3/10
29/29 [==============================] - 0s 4ms/step - loss: 15.4570 - accuracy: 0.4352
Epoch 4/10
29/29 [=====... | MIT | ML1 - Scikit Learn Methods (Complete).ipynb | oskali/SoftwareTools_MBAN21_Python |
Logistic RegressionWe can also access logistic regression from sklearn | from sklearn.linear_model import LogisticRegression
logit = LogisticRegression(solver='liblinear')
logit.fit(breast.data, breast.target)
labels = logit.predict(breast.data)
probs = logit.predict_proba(breast.data)[:,1]
print(roc_auc_score(breast.target, probs))
print(accuracy_score(breast.target, labels))
confusion_mat... | 0.9945298874266688
0.9578207381370826
| MIT | ML1 - Scikit Learn Methods (Complete).ipynb | oskali/SoftwareTools_MBAN21_Python |
The sklearn implementation has options for regularization in logistic regression. You can choose between L1 and L2 regularization:Note... | # No regularization
logit = LogisticRegression(C=1e10, solver='liblinear')
logit.fit(breast.data, breast.target)
labels = logit.predict(breast.data)
probs = logit.predict_proba(breast.data)[:,1]
print(roc_auc_score(breast.target, probs))
print(accuracy_score(breast.target, labels))
confusion_matrix(breast.target, label... | 0.9985201627820939
0.9876977152899824
| MIT | ML1 - Scikit Learn Methods (Complete).ipynb | oskali/SoftwareTools_MBAN21_Python |
RegressionNow let's take a look at regression in sklearn. Again we can start by loading up a dataset. | from sklearn.datasets import load_boston
boston = load_boston()
print(boston.DESCR) | .. _boston_dataset:
Boston house prices dataset
---------------------------
**Data Set Characteristics:**
:Number of Instances: 506
:Number of Attributes: 13 numeric/categorical predictive. Median Value (attribute 14) is usually the target.
:Attribute Information (in order):
- CRIM per c... | MIT | ML1 - Scikit Learn Methods (Complete).ipynb | oskali/SoftwareTools_MBAN21_Python |
Take a look at the X | df = pd.DataFrame(boston.data)
df.columns = boston.feature_names
df
boston.target | _____no_output_____ | MIT | ML1 - Scikit Learn Methods (Complete).ipynb | oskali/SoftwareTools_MBAN21_Python |
Regression TreesWe use regression trees in the same way as classification | from sklearn.tree import DecisionTreeRegressor
cart = DecisionTreeRegressor(max_depth=2, min_samples_leaf=5)
cart.fit(boston.data, boston.target)
visualize_tree(cart) | _____no_output_____ | MIT | ML1 - Scikit Learn Methods (Complete).ipynb | oskali/SoftwareTools_MBAN21_Python |
Like for classification, we get the predicted labels out with the `.predict` method | preds = cart.predict(boston.data)
preds | _____no_output_____ | MIT | ML1 - Scikit Learn Methods (Complete).ipynb | oskali/SoftwareTools_MBAN21_Python |
There are functions provided by `sklearn.metrics` to evaluate the predictions | from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
print(mean_absolute_error(boston.target, preds))
print(mean_squared_error(boston.target, preds))
print(r2_score(boston.target, preds)) | 3.5736909785051676
25.69946745212606
0.695574477973027
| MIT | ML1 - Scikit Learn Methods (Complete).ipynb | oskali/SoftwareTools_MBAN21_Python |
Random Forests and BoostingRandom forests and boosting for regression work the same as in classification, except we use the `Regressor` version rather than `Classifier`. ExerciseTest and compare the (in-sample) performance of random forests and boosting on the Boston data with some sensible parameters. | from sklearn.ensemble import RandomForestRegressor
forest = RandomForestRegressor(n_estimators=100)
forest.fit(boston.data, boston.target)
preds = forest.predict(boston.data)
print(mean_absolute_error(boston.target, preds))
print(mean_squared_error(boston.target, preds))
print(r2_score(boston.target, preds))
from sklea... | 0.026413507235379965
0.0014430003436840648
0.9999829068001611
| MIT | ML1 - Scikit Learn Methods (Complete).ipynb | oskali/SoftwareTools_MBAN21_Python |
Neural Networks | from sklearn.neural_network import MLPRegressor
mlp = MLPRegressor(max_iter=1000)
mlp.fit(boston.data, boston.target)
preds = mlp.predict(boston.data)
print(mean_absolute_error(boston.target, preds))
print(mean_squared_error(boston.target, preds))
print(r2_score(boston.target, preds))
from keras.models import Sequentia... | Epoch 1/10
26/26 [==============================] - 0s 2ms/step - loss: 416.3250
Epoch 2/10
26/26 [==============================] - 0s 4ms/step - loss: 189.9820
Epoch 3/10
26/26 [==============================] - 0s 5ms/step - loss: 147.3391
Epoch 4/10
26/26 [==============================] - 0s 4ms/step - loss: 123.4... | MIT | ML1 - Scikit Learn Methods (Complete).ipynb | oskali/SoftwareTools_MBAN21_Python |
Linear Regression Models There are a large collection of linear regression models in sklearn. Let's start with a simple ordinary linear regression | from sklearn.linear_model import LinearRegression
linear = LinearRegression()
linear.fit(boston.data, boston.target)
preds = linear.predict(boston.data)
print(mean_absolute_error(boston.target, preds))
print(mean_squared_error(boston.target, preds))
print(r2_score(boston.target, preds)) | 3.270862810900317
21.894831181729206
0.7406426641094094
| MIT | ML1 - Scikit Learn Methods (Complete).ipynb | oskali/SoftwareTools_MBAN21_Python |
We can also take a look at the betas: | linear.coef_ | _____no_output_____ | MIT | ML1 - Scikit Learn Methods (Complete).ipynb | oskali/SoftwareTools_MBAN21_Python |
We can use regularized models as well. Here is ridge regression: | from sklearn.linear_model import Ridge
ridge = Ridge(alpha=10)
ridge.fit(boston.data, boston.target)
preds = ridge.predict(boston.data)
print(mean_absolute_error(boston.target, preds))
print(mean_squared_error(boston.target, preds))
print(r2_score(boston.target, preds))
ridge.coef_ | 3.315169248123664
22.660363555639318
0.7315744764907257
| MIT | ML1 - Scikit Learn Methods (Complete).ipynb | oskali/SoftwareTools_MBAN21_Python |
And here is lasso | from sklearn.linear_model import Lasso
lasso = Lasso(alpha=1)
lasso.fit(boston.data, boston.target)
preds = lasso.predict(boston.data)
print(mean_absolute_error(boston.target, preds))
print(mean_squared_error(boston.target, preds))
print(r2_score(boston.target, preds))
lasso.coef_ | 3.6117102456478434
26.79609915726647
0.6825842212709925
| MIT | ML1 - Scikit Learn Methods (Complete).ipynb | oskali/SoftwareTools_MBAN21_Python |
There are many other linear regression models available. See the [linear model documentation](http://scikit-learn.org/stable/modules/linear_model.html) for more. ExerciseThe elastic net is another linear regression method that combines ridge and lasso regularization. Try running it on this dataset, referring to the do... | from sklearn.linear_model import ElasticNet
elastic = ElasticNet(alpha=1, l1_ratio=.7)
elastic.fit(boston.data, boston.target)
preds = elastic.predict(boston.data)
print(mean_absolute_error(boston.target, preds))
print(mean_squared_error(boston.target, preds))
print(r2_score(boston.target, preds))
elastic.coef_
?Decisi... | _____no_output_____ | MIT | ML1 - Scikit Learn Methods (Complete).ipynb | oskali/SoftwareTools_MBAN21_Python |
Multiple Linear Regression with sklearn - Exercise Solution You are given a real estate dataset. Real estate is one of those examples that every regression course goes through as it is extremely easy to understand and there is a (almost always) certain causal relationship to be found.The data is located in the file: '... | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
sns.set()
from sklearn.linear_model import LinearRegression | _____no_output_____ | MIT | Resources/Data-Science/Machine-Learning/Multiple-Linear-Regression/sklearn - Multiple Linear Regression_.ipynb | nate4bs/DataRepo |
Load the data | data = pd.read_csv('real_estate_price_size_year.csv')
data.head()
data.describe() | _____no_output_____ | MIT | Resources/Data-Science/Machine-Learning/Multiple-Linear-Regression/sklearn - Multiple Linear Regression_.ipynb | nate4bs/DataRepo |
Create the regression Declare the dependent and the independent variables | x = data[['size','year']]
y = data['price'] | _____no_output_____ | MIT | Resources/Data-Science/Machine-Learning/Multiple-Linear-Regression/sklearn - Multiple Linear Regression_.ipynb | nate4bs/DataRepo |
Regression | reg = LinearRegression()
reg.fit(x,y) | _____no_output_____ | MIT | Resources/Data-Science/Machine-Learning/Multiple-Linear-Regression/sklearn - Multiple Linear Regression_.ipynb | nate4bs/DataRepo |
Find the intercept | reg.intercept_ | _____no_output_____ | MIT | Resources/Data-Science/Machine-Learning/Multiple-Linear-Regression/sklearn - Multiple Linear Regression_.ipynb | nate4bs/DataRepo |
Find the coefficients | reg.coef_ | _____no_output_____ | MIT | Resources/Data-Science/Machine-Learning/Multiple-Linear-Regression/sklearn - Multiple Linear Regression_.ipynb | nate4bs/DataRepo |
Calculate the R-squared | reg.score(x,y) | _____no_output_____ | MIT | Resources/Data-Science/Machine-Learning/Multiple-Linear-Regression/sklearn - Multiple Linear Regression_.ipynb | nate4bs/DataRepo |
Calculate the Adjusted R-squared | # Let's use the handy function we created
def adj_r2(x,y):
r2 = reg.score(x,y)
n = x.shape[0]
p = x.shape[1]
adjusted_r2 = 1-(1-r2)*(n-1)/(n-p-1)
return adjusted_r2
adj_r2(x,y) | _____no_output_____ | MIT | Resources/Data-Science/Machine-Learning/Multiple-Linear-Regression/sklearn - Multiple Linear Regression_.ipynb | nate4bs/DataRepo |
Compare the R-squared and the Adjusted R-squared It seems the the R-squared is only slightly larger than the Adjusted R-squared, implying that we were not penalized a lot for the inclusion of 2 independent variables. Compare the Adjusted R-squared with the R-squared of the simple linear regression Comparing the Adju... | reg.predict([[750,2009]]) | _____no_output_____ | MIT | Resources/Data-Science/Machine-Learning/Multiple-Linear-Regression/sklearn - Multiple Linear Regression_.ipynb | nate4bs/DataRepo |
Calculate the univariate p-values of the variables | from sklearn.feature_selection import f_regression
f_regression(x,y)
p_values = f_regression(x,y)[1]
p_values
p_values.round(3) | _____no_output_____ | MIT | Resources/Data-Science/Machine-Learning/Multiple-Linear-Regression/sklearn - Multiple Linear Regression_.ipynb | nate4bs/DataRepo |
Create a summary table with your findings | reg_summary = pd.DataFrame(data = x.columns.values, columns=['Features'])
reg_summary ['Coefficients'] = reg.coef_
reg_summary ['p-values'] = p_values.round(3)
reg_summary | _____no_output_____ | MIT | Resources/Data-Science/Machine-Learning/Multiple-Linear-Regression/sklearn - Multiple Linear Regression_.ipynb | nate4bs/DataRepo |
ENGR 1330 Computational Thinking with Data Science Last GitHub Commit Date: 14 February 2021 Lesson 8 The Pandas module - About Pandas- How to install - Anaconda - JupyterHub/Lab (on Linux) - JupyterHub/Lab (on MacOS) - JupyterHub/Lab (on Windoze)- The Dataframe - Primatives - Using Pandas - Creat... | %%html
<!--Script block to left align Markdown Tables-->
<style>
table {margin-left: 0 !important;}
</style> | _____no_output_____ | CC0-1.0 | 1-Lessons/Lesson08/OriginalPowerpoint/ENGR-1330-Lesson8-Dev.ipynb | dustykat/engr-1330-psuedo-course |
--- Objectives1. To understand the **dataframe abstraction** as implemented in the Pandas library(module). 1. To be able to access and manipulate data within a dataframe 2. To be able to obtain basic statistical measures of data within a dataframe2. Read/Write from/to files 1. MS Excel-type files (.xls,.xlsx,.... | import pandas | _____no_output_____ | CC0-1.0 | 1-Lessons/Lesson08/OriginalPowerpoint/ENGR-1330-Lesson8-Dev.ipynb | dustykat/engr-1330-psuedo-course |
If you do get an error, that means that you will have to install using `conda` or `pip`; you are on-your-own here! On the **content server** the process is:1. Open a new terminal from the launcher2. Change to root user `su` then enter the root password3. `sudo -H /opt/jupyterhib/bin/python3 -m pip install pandas`4. Wa... | import numpy
mytabular = numpy.random.randint(1,100,(5,4))
myrowname = ['A','B','C','D','E']
mycolname = ['W','X','Y','Z']
mytable = [['' for jcol in range(len(mycolname)+1)] for irow in range(len(myrowname)+1)] #non-null destination matrix, note the implied loop construction | _____no_output_____ | CC0-1.0 | 1-Lessons/Lesson08/OriginalPowerpoint/ENGR-1330-Lesson8-Dev.ipynb | dustykat/engr-1330-psuedo-course |
The above builds a placeholder named `mytable` for the psuedo-dataframe.Next we populate the table, using a for loop to write the column names in the first row, row names in the first column, and the table fill for the rest of the table. | for irow in range(1,len(myrowname)+1): # write the row names
mytable[irow][0]=myrowname[irow-1]
for jcol in range(1,len(mycolname)+1): # write the column names
mytable[0][jcol]=mycolname[jcol-1]
for irow in range(1,len(myrowname)+1): # fill the table (note the nested loop)
for jcol in range(1,len(mycolnam... | _____no_output_____ | CC0-1.0 | 1-Lessons/Lesson08/OriginalPowerpoint/ENGR-1330-Lesson8-Dev.ipynb | dustykat/engr-1330-psuedo-course |
Now lets print the table out by row and we see we have a very dataframe-like structure | for irow in range(0,len(myrowname)+1):
print(mytable[irow][0:len(mycolname)+1]) | ['', 'W', 'X', 'Y', 'Z']
['A', 25, 43, 34, 7]
['B', 49, 28, 24, 53]
['C', 66, 21, 16, 33]
['D', 71, 6, 21, 63]
['E', 13, 94, 13, 17]
| CC0-1.0 | 1-Lessons/Lesson08/OriginalPowerpoint/ENGR-1330-Lesson8-Dev.ipynb | dustykat/engr-1330-psuedo-course |
We can also query by row | print(mytable[3][0:len(mycolname)+1]) | ['C', 66, 21, 16, 33]
| CC0-1.0 | 1-Lessons/Lesson08/OriginalPowerpoint/ENGR-1330-Lesson8-Dev.ipynb | dustykat/engr-1330-psuedo-course |
Or by column | for irow in range(0,len(myrowname)+1): #cannot use implied loop in a column slice
print(mytable[irow][2]) | X
43
28
21
6
94
| CC0-1.0 | 1-Lessons/Lesson08/OriginalPowerpoint/ENGR-1330-Lesson8-Dev.ipynb | dustykat/engr-1330-psuedo-course |
Or by row+column index; sort of looks like a spreadsheet syntax. | print(' ',mytable[0][3])
print(mytable[3][0],mytable[3][3]) | Y
C 16
| CC0-1.0 | 1-Lessons/Lesson08/OriginalPowerpoint/ENGR-1330-Lesson8-Dev.ipynb | dustykat/engr-1330-psuedo-course |
Now we shall create a proper dataframeWe will now do the same using pandas | mydf = pandas.DataFrame(numpy.random.randint(1,100,(5,4)), ['A','B','C','D','E'], ['W','X','Y','Z'])
mydf | _____no_output_____ | CC0-1.0 | 1-Lessons/Lesson08/OriginalPowerpoint/ENGR-1330-Lesson8-Dev.ipynb | dustykat/engr-1330-psuedo-course |
We can also turn our table into a dataframe, notice how the constructor adds header row and index column | mydf1 = pandas.DataFrame(mytable)
mydf1 | _____no_output_____ | CC0-1.0 | 1-Lessons/Lesson08/OriginalPowerpoint/ENGR-1330-Lesson8-Dev.ipynb | dustykat/engr-1330-psuedo-course |
To get proper behavior, we can just reuse our original objects | mydf2 = pandas.DataFrame(mytabular,myrowname,mycolname)
mydf2 | _____no_output_____ | CC0-1.0 | 1-Lessons/Lesson08/OriginalPowerpoint/ENGR-1330-Lesson8-Dev.ipynb | dustykat/engr-1330-psuedo-course |
Why are `mydf` and `mydf2` different? Getting the shape of dataframesThe shape method, which is available after the dataframe is constructed, will return the row and column rank (count) of a dataframe. | mydf.shape
mydf1.shape
mydf2.shape | _____no_output_____ | CC0-1.0 | 1-Lessons/Lesson08/OriginalPowerpoint/ENGR-1330-Lesson8-Dev.ipynb | dustykat/engr-1330-psuedo-course |
Appending new columnsTo append a column simply assign a value to a new column name to the dataframe | mydf['new']= 'NA'
mydf | _____no_output_____ | CC0-1.0 | 1-Lessons/Lesson08/OriginalPowerpoint/ENGR-1330-Lesson8-Dev.ipynb | dustykat/engr-1330-psuedo-course |
Appending new rowsThis is sometimes a bit trickier but here is one way:- create a copy of a row, give it a new name. - concatenate it back into the dataframe. | newrow = mydf.loc[['E']].rename(index={"E": "X"}) # create a single row, rename the index
newtable = pandas.concat([mydf,newrow]) # concatenate the row to bottom of df - note the syntax
newtable | _____no_output_____ | CC0-1.0 | 1-Lessons/Lesson08/OriginalPowerpoint/ENGR-1330-Lesson8-Dev.ipynb | dustykat/engr-1330-psuedo-course |
Removing Rows and ColumnsTo remove a column is straightforward, we use the drop method | newtable.drop('new', axis=1, inplace = True)
newtable | _____no_output_____ | CC0-1.0 | 1-Lessons/Lesson08/OriginalPowerpoint/ENGR-1330-Lesson8-Dev.ipynb | dustykat/engr-1330-psuedo-course |
To remove a row, you really got to want to, easiest is probablty to create a new dataframe with the row removed | newtable = newtable.loc[['A','B','D','E','X']] # select all rows except C
newtable
# or just use drop with axis specify
newtable.drop('X', axis=0, inplace = True)
newtable | _____no_output_____ | CC0-1.0 | 1-Lessons/Lesson08/OriginalPowerpoint/ENGR-1330-Lesson8-Dev.ipynb | dustykat/engr-1330-psuedo-course |
IndexingWe have already been indexing, but a few examples follow: | newtable['X'] #Selecing a single column
newtable[['X','W']] #Selecing a multiple columns
newtable.loc['E'] #Selecing rows based on label via loc[ ] indexer
newtable
newtable.loc[['E','D','B']] #Selecing multiple rows based on label via loc[ ] indexer
newtable.loc[['B','E','D'],['X','Y']] #Selecting elements via bo... | _____no_output_____ | CC0-1.0 | 1-Lessons/Lesson08/OriginalPowerpoint/ENGR-1330-Lesson8-Dev.ipynb | dustykat/engr-1330-psuedo-course |
Conditional Selection | mydf = pandas.DataFrame({'col1':[1,2,3,4,5,6,7,8],
'col2':[444,555,666,444,666,111,222,222],
'col3':['orange','apple','grape','mango','jackfruit','watermelon','banana','peach']})
mydf
#What fruit corresponds to the number 555 in ‘col2’?
mydf[mydf['col2']==555]['col3']
#What fruit ... | _____no_output_____ | CC0-1.0 | 1-Lessons/Lesson08/OriginalPowerpoint/ENGR-1330-Lesson8-Dev.ipynb | dustykat/engr-1330-psuedo-course |
Descriptor Functions | #Creating a dataframe from a dictionary
mydf = pandas.DataFrame({'col1':[1,2,3,4,5,6,7,8],
'col2':[444,555,666,444,666,111,222,222],
'col3':['orange','apple','grape','mango','jackfruit','watermelon','banana','peach']})
mydf | _____no_output_____ | CC0-1.0 | 1-Lessons/Lesson08/OriginalPowerpoint/ENGR-1330-Lesson8-Dev.ipynb | dustykat/engr-1330-psuedo-course |
`head` methodReturns the first few rows, useful to infer structure | #Returns only the first five rows
mydf.head() | _____no_output_____ | CC0-1.0 | 1-Lessons/Lesson08/OriginalPowerpoint/ENGR-1330-Lesson8-Dev.ipynb | dustykat/engr-1330-psuedo-course |
`info` methodReturns the data model (data column count, names, data types) | #Info about the dataframe
mydf.info() | <class 'pandas.core.frame.DataFrame'>
RangeIndex: 8 entries, 0 to 7
Data columns (total 3 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 col1 8 non-null int64
1 col2 8 non-null int64
2 col3 8 non-null object
dtypes: int64(2), object(1)
memory usage... | CC0-1.0 | 1-Lessons/Lesson08/OriginalPowerpoint/ENGR-1330-Lesson8-Dev.ipynb | dustykat/engr-1330-psuedo-course |
`describe` methodReturns summary statistics of each numeric column. Also returns the minimum and maximum value in each column, and the IQR (Interquartile Range). Again useful to understand structure of the columns. | #Statistics of the dataframe
mydf.describe() | _____no_output_____ | CC0-1.0 | 1-Lessons/Lesson08/OriginalPowerpoint/ENGR-1330-Lesson8-Dev.ipynb | dustykat/engr-1330-psuedo-course |
Counting and Sum methodsThere are also methods for counts and sums by specific columns | mydf['col2'].sum() #Sum of a specified column | _____no_output_____ | CC0-1.0 | 1-Lessons/Lesson08/OriginalPowerpoint/ENGR-1330-Lesson8-Dev.ipynb | dustykat/engr-1330-psuedo-course |
The `unique` method returns a list of unique values (filters out duplicates in the list, underlying dataframe is preserved) | mydf['col2'].unique() #Returns the list of unique values along the indexed column | _____no_output_____ | CC0-1.0 | 1-Lessons/Lesson08/OriginalPowerpoint/ENGR-1330-Lesson8-Dev.ipynb | dustykat/engr-1330-psuedo-course |
The `nunique` method returns a count of unique values | mydf['col2'].nunique() #Returns the total number of unique values along the indexed column | _____no_output_____ | CC0-1.0 | 1-Lessons/Lesson08/OriginalPowerpoint/ENGR-1330-Lesson8-Dev.ipynb | dustykat/engr-1330-psuedo-course |
The `value_counts()` method returns the count of each unique value (kind of like a histogram, but each value is the bin) | mydf['col2'].value_counts() #Returns the number of occurences of each unique value | _____no_output_____ | CC0-1.0 | 1-Lessons/Lesson08/OriginalPowerpoint/ENGR-1330-Lesson8-Dev.ipynb | dustykat/engr-1330-psuedo-course |
Using functions in dataframes - symbolic applyThe power of **Pandas** is an ability to apply a function to each element of a dataframe series (or a whole frame) by a technique called symbolic (or synthetic programming) application of the function.This employs principles of **pattern matching**, **abstraction**, and **... | def times2(x): # A prototype function to scalar multiply an object x by 2
return(x*2)
print(mydf)
print('Apply the times2 function to col2')
mydf['reallynew'] = mydf['col2'].apply(times2) #Symbolic apply the function to each element of column col2, result is another dataframe
mydf | _____no_output_____ | CC0-1.0 | 1-Lessons/Lesson08/OriginalPowerpoint/ENGR-1330-Lesson8-Dev.ipynb | dustykat/engr-1330-psuedo-course |
Sorts | mydf.sort_values('col2', ascending = True) #Sorting based on columns
mydf.sort_values('col3', ascending = True) #Lexiographic sort | _____no_output_____ | CC0-1.0 | 1-Lessons/Lesson08/OriginalPowerpoint/ENGR-1330-Lesson8-Dev.ipynb | dustykat/engr-1330-psuedo-course |
Aggregating (Grouping Values) dataframe contents | #Creating a dataframe from a dictionary
data = {
'key' : ['A', 'B', 'C', 'A', 'B', 'C'],
'data1' : [1, 2, 3, 4, 5, 6],
'data2' : [10, 11, 12, 13, 14, 15],
'data3' : [20, 21, 22, 13, 24, 25]
}
mydf1 = pandas.DataFrame(data)
mydf1
# Grouping and summing values in all the columns based on the column 'key... | _____no_output_____ | CC0-1.0 | 1-Lessons/Lesson08/OriginalPowerpoint/ENGR-1330-Lesson8-Dev.ipynb | dustykat/engr-1330-psuedo-course |
Filtering out missing valuesFiltering and *cleaning* are often used to describe the process where data that does not support a narrative is removed ;typically for maintenance of profit applications, if the data are actually missing that is common situation where cleaning is justified. | #Creating a dataframe from a dictionary
df = pandas.DataFrame({'col1':[1,2,3,4,None,6,7,None],
'col2':[444,555,None,444,666,111,None,222],
'col3':['orange','apple','grape','mango','jackfruit','watermelon','banana','peach']})
df | _____no_output_____ | CC0-1.0 | 1-Lessons/Lesson08/OriginalPowerpoint/ENGR-1330-Lesson8-Dev.ipynb | dustykat/engr-1330-psuedo-course |
Below we drop any row that contains a `NaN` code. | df_dropped = df.dropna()
df_dropped | _____no_output_____ | CC0-1.0 | 1-Lessons/Lesson08/OriginalPowerpoint/ENGR-1330-Lesson8-Dev.ipynb | dustykat/engr-1330-psuedo-course |
Below we replace `NaN` codes with some value, in this case 0 | df_filled1 = df.fillna(0)
df_filled1 | _____no_output_____ | CC0-1.0 | 1-Lessons/Lesson08/OriginalPowerpoint/ENGR-1330-Lesson8-Dev.ipynb | dustykat/engr-1330-psuedo-course |
Below we replace `NaN` codes with some value, in this case the mean value of of the column in which the missing value code resides. | df_filled2 = df.fillna(df.mean())
df_filled2 | _____no_output_____ | CC0-1.0 | 1-Lessons/Lesson08/OriginalPowerpoint/ENGR-1330-Lesson8-Dev.ipynb | dustykat/engr-1330-psuedo-course |
--- Reading a File into a DataframePandas has methods to read common file types, such as `csv`,`xlsx`, and `json`. Ordinary text files are also quite manageable.On a machine you control you can write script to retrieve files from the internet and process them. | readfilecsv = pandas.read_csv('CSV_ReadingFile.csv') #Reading a .csv file
print(readfilecsv) | a b c d
0 0 1 2 3
1 4 5 6 7
2 8 9 10 11
3 12 13 14 15
| CC0-1.0 | 1-Lessons/Lesson08/OriginalPowerpoint/ENGR-1330-Lesson8-Dev.ipynb | dustykat/engr-1330-psuedo-course |
Similar to reading and writing .csv files, you can also read and write .xslx files as below (useful to know this) | readfileexcel = pandas.read_excel('Excel_ReadingFile.xlsx', sheet_name='Sheet1', engine='openpyxl') #Reading a .xlsx file
print(readfileexcel) | Unnamed: 0 a b c d
0 0 0 1 2 3
1 1 4 5 6 7
2 2 8 9 10 11
3 3 12 13 14 15
| CC0-1.0 | 1-Lessons/Lesson08/OriginalPowerpoint/ENGR-1330-Lesson8-Dev.ipynb | dustykat/engr-1330-psuedo-course |
Writing a dataframe to file | #Creating and writing to a .csv file
readfilecsv = pandas.read_csv('CSV_ReadingFile.csv')
readfilecsv.to_csv('CSV_WritingFile1.csv')
readfilecsv = pandas.read_csv('CSV_WritingFile1.csv')
print(readfilecsv)
#Creating and writing to a .csv file by excluding row labels
readfilecsv = pandas.read_csv('CSV_ReadingFile.csv')... | Unnamed: 0 a b c d
0 0 0 1 2 3
1 1 4 5 6 7
2 2 8 9 10 11
3 3 12 13 14 15
| CC0-1.0 | 1-Lessons/Lesson08/OriginalPowerpoint/ENGR-1330-Lesson8-Dev.ipynb | dustykat/engr-1330-psuedo-course |
--- Downloading files from websites (optional)This section shows how to get files from a remote computer. There are several ways to get the files, most importantly you need the FQDN to the file. Method: Get the actual file from a remote web server (unencrypted)> - You know the FQDN to the file it will be in structu... | import requests # Module to process http/https requests | _____no_output_____ | CC0-1.0 | 1-Lessons/Lesson08/OriginalPowerpoint/ENGR-1330-Lesson8-Dev.ipynb | dustykat/engr-1330-psuedo-course |
Now we will generate a ``GET`` request to the remote http server. I chose to do so using a variable to store the remote URL so I can reuse code in future projects. The ``GET`` request (an http/https method) is generated with the requests method ``get`` and assigned to an object named ``rget`` -- the name is arbitrary... | remote_url="http://54.243.252.9/engr-1330-webroot/MyJupyterNotebooks/42-DataScience-EvaporationAnalysis/all_quads_gross_evaporation.csv" # set the url
rget = requests.get(remote_url, allow_redirects=True) # get the remote resource, follow imbedded links
open('all_quads_gross_evaporation.csv','wb').write(rget.content)... | /home/sensei/engr-1330-webroot/1-Lessons/Lesson08/OriginalPowerpoint
total 1080
drwxr-xr-x 4 sensei sensei 4096 Sep 10 21:41 .
drwxr-xr-x 5 sensei sensei 4096 Feb 15 2021 ..
drwxr-xr-x 2 sensei sensei 4096 Sep 10 21:11 .ipynb_checkpoints
-rw-rw-r-- 1 sensei sensei 21150 Feb 16 2021 01-table-dataframe.png
-rw-r... | CC0-1.0 | 1-Lessons/Lesson08/OriginalPowerpoint/ENGR-1330-Lesson8-Dev.ipynb | dustykat/engr-1330-psuedo-course |
Now we can read the file contents and check its structure, before proceeding. | #evapdf = pd.read_csv("all_quads_gross_evaporation.csv",parse_dates=["YYYY-MM"]) # Read the file as a .CSV assign to a dataframe evapdf
evapdf = pd.read_csv("all_quads_gross_evaporation.csv")
evapdf.head() # check structure | _____no_output_____ | CC0-1.0 | 1-Lessons/Lesson08/OriginalPowerpoint/ENGR-1330-Lesson8-Dev.ipynb | dustykat/engr-1330-psuedo-course |
Structure looks like a spreadsheet as expected; lets plot the time series for cell '911' | evapdf.plot.line(x='YYYY-MM',y='911') # Plot quadrant 911 evaporation time series | _____no_output_____ | CC0-1.0 | 1-Lessons/Lesson08/OriginalPowerpoint/ENGR-1330-Lesson8-Dev.ipynb | dustykat/engr-1330-psuedo-course |
Method 3: Get the actual file from an encrypted serverThis section is saved for future semesters Method 1: Get data from a file on a remote server (unencrypted)This section shows how to obtain data files from public URLs. Prerequesites:- You know the FQDN to the file it will be in structure of "http://server-name/..... | #Step 1: import needed modules to interact with the internet
from urllib.request import urlopen # import a method that will connect to a url and read file contents
import pandas #import pandas | _____no_output_____ | CC0-1.0 | 1-Lessons/Lesson08/OriginalPowerpoint/ENGR-1330-Lesson8-Dev.ipynb | dustykat/engr-1330-psuedo-course |
This next code fragment sets a string called ``remote_url``; it is just a variable, name can be anything that honors python naming rules.Then the ``urllib`` function ``urlopen`` with read and decode methods is employed, the result is stored in an object named ``elevationXYZ`` | #Step 2: make the connection to the remote file (actually its implementing "bash curl -O http://fqdn/path ...")
remote_url = 'http://www.rtfmps.com/share_files/pip-corner-sumps.txt' #
elevationXYZ = urlopen(remote_url).read().decode().split() # Gets the file contents as a single vector, comma delimited, file is not re... | _____no_output_____ | CC0-1.0 | 1-Lessons/Lesson08/OriginalPowerpoint/ENGR-1330-Lesson8-Dev.ipynb | dustykat/engr-1330-psuedo-course |
At this point the object exists as a single vector with hundreds of elements. We now need to structure the content. Here using python primatives, and knowing how the data are supposed to look, we prepare variables to recieve the structured results | #Step 3 Python primatives to structure the data, or use fancy modules (probably easy in numpy)
howmany = len(elevationXYZ) # how long is the vector?
nrow = int(howmany/3)
xyz = [[0 for j in range(3)] for j in range(nrow)] # null space to receive data define columnX | _____no_output_____ | CC0-1.0 | 1-Lessons/Lesson08/OriginalPowerpoint/ENGR-1330-Lesson8-Dev.ipynb | dustykat/engr-1330-psuedo-course |
Now that everything is ready, we can extract from the object the values we want into ``xyz`` | #Step4 Now will build xyz as a matrix with 3 columns
index = 0
for irow in range(0,nrow):
xyz[irow][0]=float(elevationXYZ[index])
xyz[irow][1]=float(elevationXYZ[index+1])
xyz[irow][2]=float(elevationXYZ[index+2])
index += 3 #increment the index | _____no_output_____ | CC0-1.0 | 1-Lessons/Lesson08/OriginalPowerpoint/ENGR-1330-Lesson8-Dev.ipynb | dustykat/engr-1330-psuedo-course |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.