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
|
---|---|---|---|---|---|
Implementation: Data ExplorationA cursory investigation of the dataset will determine how many individuals fit into either group, and will tell us about the percentage of these individuals making more than \$50,000. In the code cell below, you will need to compute the following:- The total number of records, `'n_records'`- The number of individuals making more than \$50,000 annually, `'n_greater_50k'`.- The number of individuals making at most \$50,000 annually, `'n_at_most_50k'`.- The percentage of individuals making more than \$50,000 annually, `'greater_percent'`.**Hint:** You may need to look at the table above to understand how the `'income'` entries are formatted. | # Total number of records
n_records = data.shape[0]
# Number of records where individual's income is more than $50,000
n_greater_50k = data[data['income'] == '>50K'].shape[0]
# Number of records where individual's income is at most $50,000
n_at_most_50k = data[data['income'] == '<=50K'].shape[0]
# Percentage of individuals whose income is more than $50,000
greater_percent = n_greater_50k / (n_records / 100.0)
# Print the results
print "Total number of records: {}".format(n_records)
print "Individuals making more than $50,000: {}".format(n_greater_50k)
print "Individuals making at most $50,000: {}".format(n_at_most_50k)
print "Percentage of individuals making more than $50,000: {:.2f}%".format(greater_percent) | Total number of records: 45222
Individuals making more than $50,000: 11208
Individuals making at most $50,000: 34014
Percentage of individuals making more than $50,000: 24.78%
| Apache-2.0 | p2_sl_finding_donors/p2_sl_finding_donors.ipynb | superkley/udacity-mlnd |
---- Preparing the DataBefore data can be used as input for machine learning algorithms, it often must be cleaned, formatted, and restructured — this is typically known as **preprocessing**. Fortunately, for this dataset, there are no invalid or missing entries we must deal with, however, there are some qualities about certain features that must be adjusted. This preprocessing can help tremendously with the outcome and predictive power of nearly all learning algorithms. Transforming Skewed Continuous FeaturesA dataset may sometimes contain at least one feature whose values tend to lie near a single number, but will also have a non-trivial number of vastly larger or smaller values than that single number. Algorithms can be sensitive to such distributions of values and can underperform if the range is not properly normalized. With the census dataset two features fit this description: '`capital-gain'` and `'capital-loss'`. Run the code cell below to plot a histogram of these two features. Note the range of the values present and how they are distributed. | # Split the data into features and target label
income_raw = data['income']
features_raw = data.drop('income', axis = 1)
# Visualize skewed continuous features of original data
vs.distribution(data) | _____no_output_____ | Apache-2.0 | p2_sl_finding_donors/p2_sl_finding_donors.ipynb | superkley/udacity-mlnd |
For highly-skewed feature distributions such as `'capital-gain'` and `'capital-loss'`, it is common practice to apply a logarithmic transformation on the data so that the very large and very small values do not negatively affect the performance of a learning algorithm. Using a logarithmic transformation significantly reduces the range of values caused by outliers. Care must be taken when applying this transformation however: The logarithm of `0` is undefined, so we must translate the values by a small amount above `0` to apply the the logarithm successfully.Run the code cell below to perform a transformation on the data and visualize the results. Again, note the range of values and how they are distributed. | # Log-transform the skewed features
skewed = ['capital-gain', 'capital-loss']
features_raw[skewed] = data[skewed].apply(lambda x: np.log(x + 1))
# Visualize the new log distributions
vs.distribution(features_raw, transformed = True) | _____no_output_____ | Apache-2.0 | p2_sl_finding_donors/p2_sl_finding_donors.ipynb | superkley/udacity-mlnd |
Normalizing Numerical FeaturesIn addition to performing transformations on features that are highly skewed, it is often good practice to perform some type of scaling on numerical features. Applying a scaling to the data does not change the shape of each feature's distribution (such as `'capital-gain'` or `'capital-loss'` above); however, normalization ensures that each feature is treated equally when applying supervised learners. Note that once scaling is applied, observing the data in its raw form will no longer have the same original meaning, as exampled below.Run the code cell below to normalize each numerical feature. We will use [`sklearn.preprocessing.MinMaxScaler`](http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.MinMaxScaler.html) for this. | # Import sklearn.preprocessing.StandardScaler
from sklearn.preprocessing import MinMaxScaler
# Initialize a scaler, then apply it to the features
scaler = MinMaxScaler()
numerical = ['age', 'education-num', 'capital-gain', 'capital-loss', 'hours-per-week']
features_raw[numerical] = scaler.fit_transform(data[numerical])
# Show an example of a record with scaling applied
display(features_raw.head(n = 1)) | _____no_output_____ | Apache-2.0 | p2_sl_finding_donors/p2_sl_finding_donors.ipynb | superkley/udacity-mlnd |
Implementation: Data PreprocessingFrom the table in **Exploring the Data** above, we can see there are several features for each record that are non-numeric. Typically, learning algorithms expect input to be numeric, which requires that non-numeric features (called *categorical variables*) be converted. One popular way to convert categorical variables is by using the **one-hot encoding** scheme. One-hot encoding creates a _"dummy"_ variable for each possible category of each non-numeric feature. For example, assume `someFeature` has three possible entries: `A`, `B`, or `C`. We then encode this feature into `someFeature_A`, `someFeature_B` and `someFeature_C`.| | someFeature | | someFeature_A | someFeature_B | someFeature_C || :-: | :-: | | :-: | :-: | :-: || 0 | B | | 0 | 1 | 0 || 1 | C | ----> one-hot encode ----> | 0 | 0 | 1 || 2 | A | | 1 | 0 | 0 |Additionally, as with the non-numeric features, we need to convert the non-numeric target label, `'income'` to numerical values for the learning algorithm to work. Since there are only two possible categories for this label ("50K"), we can avoid using one-hot encoding and simply encode these two categories as `0` and `1`, respectively. In code cell below, you will need to implement the following: - Use [`pandas.get_dummies()`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.get_dummies.html?highlight=get_dummiespandas.get_dummies) to perform one-hot encoding on the `'features_raw'` data. - Convert the target label `'income_raw'` to numerical entries. - Set records with "50K" to `1`. | # One-hot encode the 'features_raw' data using pandas.get_dummies()
features = pd.get_dummies(features_raw)
# Encode the 'income_raw' data to numerical values
income = income_raw.apply(lambda x: 1 if x == '>50K' else 0)
# Print the number of features after one-hot encoding
encoded = list(features.columns)
print "{} total features after one-hot encoding.".format(len(encoded))
# Uncomment the following line to see the encoded feature names
print encoded | 103 total features after one-hot encoding.
['age', 'education-num', 'capital-gain', 'capital-loss', 'hours-per-week', 'workclass_ Federal-gov', 'workclass_ Local-gov', 'workclass_ Private', 'workclass_ Self-emp-inc', 'workclass_ Self-emp-not-inc', 'workclass_ State-gov', 'workclass_ Without-pay', 'education_level_ 10th', 'education_level_ 11th', 'education_level_ 12th', 'education_level_ 1st-4th', 'education_level_ 5th-6th', 'education_level_ 7th-8th', 'education_level_ 9th', 'education_level_ Assoc-acdm', 'education_level_ Assoc-voc', 'education_level_ Bachelors', 'education_level_ Doctorate', 'education_level_ HS-grad', 'education_level_ Masters', 'education_level_ Preschool', 'education_level_ Prof-school', 'education_level_ Some-college', 'marital-status_ Divorced', 'marital-status_ Married-AF-spouse', 'marital-status_ Married-civ-spouse', 'marital-status_ Married-spouse-absent', 'marital-status_ Never-married', 'marital-status_ Separated', 'marital-status_ Widowed', 'occupation_ Adm-clerical', 'occupation_ Armed-Forces', 'occupation_ Craft-repair', 'occupation_ Exec-managerial', 'occupation_ Farming-fishing', 'occupation_ Handlers-cleaners', 'occupation_ Machine-op-inspct', 'occupation_ Other-service', 'occupation_ Priv-house-serv', 'occupation_ Prof-specialty', 'occupation_ Protective-serv', 'occupation_ Sales', 'occupation_ Tech-support', 'occupation_ Transport-moving', 'relationship_ Husband', 'relationship_ Not-in-family', 'relationship_ Other-relative', 'relationship_ Own-child', 'relationship_ Unmarried', 'relationship_ Wife', 'race_ Amer-Indian-Eskimo', 'race_ Asian-Pac-Islander', 'race_ Black', 'race_ Other', 'race_ White', 'sex_ Female', 'sex_ Male', 'native-country_ Cambodia', 'native-country_ Canada', 'native-country_ China', 'native-country_ Columbia', 'native-country_ Cuba', 'native-country_ Dominican-Republic', 'native-country_ Ecuador', 'native-country_ El-Salvador', 'native-country_ England', 'native-country_ France', 'native-country_ Germany', 'native-country_ Greece', 'native-country_ Guatemala', 'native-country_ Haiti', 'native-country_ Holand-Netherlands', 'native-country_ Honduras', 'native-country_ Hong', 'native-country_ Hungary', 'native-country_ India', 'native-country_ Iran', 'native-country_ Ireland', 'native-country_ Italy', 'native-country_ Jamaica', 'native-country_ Japan', 'native-country_ Laos', 'native-country_ Mexico', 'native-country_ Nicaragua', 'native-country_ Outlying-US(Guam-USVI-etc)', 'native-country_ Peru', 'native-country_ Philippines', 'native-country_ Poland', 'native-country_ Portugal', 'native-country_ Puerto-Rico', 'native-country_ Scotland', 'native-country_ South', 'native-country_ Taiwan', 'native-country_ Thailand', 'native-country_ Trinadad&Tobago', 'native-country_ United-States', 'native-country_ Vietnam', 'native-country_ Yugoslavia']
| Apache-2.0 | p2_sl_finding_donors/p2_sl_finding_donors.ipynb | superkley/udacity-mlnd |
Shuffle and Split DataNow all _categorical variables_ have been converted into numerical features, and all numerical features have been normalized. As always, we will now split the data (both features and their labels) into training and test sets. 80% of the data will be used for training and 20% for testing.Run the code cell below to perform this split. | # Import train_test_split
from sklearn.cross_validation import train_test_split
# Split the 'features' and 'income' data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(features, income, test_size = 0.2, random_state = 0)
# Show the results of the split
print "Training set has {} samples.".format(X_train.shape[0])
print "Testing set has {} samples.".format(X_test.shape[0]) | Training set has 36177 samples.
Testing set has 9045 samples.
| Apache-2.0 | p2_sl_finding_donors/p2_sl_finding_donors.ipynb | superkley/udacity-mlnd |
---- Evaluating Model PerformanceIn this section, we will investigate four different algorithms, and determine which is best at modeling the data. Three of these algorithms will be supervised learners of your choice, and the fourth algorithm is known as a *naive predictor*. Metrics and the Naive Predictor*CharityML*, equipped with their research, knows individuals that make more than \$50,000 are most likely to donate to their charity. Because of this, *CharityML* is particularly interested in predicting who makes more than \$50,000 accurately. It would seem that using **accuracy** as a metric for evaluating a particular model's performace would be appropriate. Additionally, identifying someone that *does not* make more than \$50,000 as someone who does would be detrimental to *CharityML*, since they are looking to find individuals willing to donate. Therefore, a model's ability to precisely predict those that make more than \$50,000 is *more important* than the model's ability to **recall** those individuals. We can use **F-beta score** as a metric that considers both precision and recall:$$ F_{\beta} = (1 + \beta^2) \cdot \frac{precision \cdot recall}{\left( \beta^2 \cdot precision \right) + recall} $$In particular, when $\beta = 0.5$, more emphasis is placed on precision. This is called the **F$_{0.5}$ score** (or F-score for simplicity).Looking at the distribution of classes (those who make at most \$50,000, and those who make more), it's clear most individuals do not make more than \$50,000. This can greatly affect **accuracy**, since we could simply say *"this person does not make more than \$50,000"* and generally be right, without ever looking at the data! Making such a statement would be called **naive**, since we have not considered any information to substantiate the claim. It is always important to consider the *naive prediction* for your data, to help establish a benchmark for whether a model is performing well. That been said, using that prediction would be pointless: If we predicted all people made less than \$50,000, *CharityML* would identify no one as donors. Question 1 - Naive Predictor Performace*If we chose a model that always predicted an individual made more than \$50,000, what would that model's accuracy and F-score be on this dataset?* **Note:** You must use the code cell below and assign your results to `'accuracy'` and `'fscore'` to be used later. | # Calculate accuracy
accuracy = 1.0 * n_greater_50k / n_records
# Calculate F-score using the formula above for beta = 0.5
recall = 1.0
fscore = (
(1 + 0.5**2) * accuracy * recall
) / (
0.5**2 * accuracy + recall
)
# Print the results
print "Naive Predictor: [Accuracy score: {:.4f}, F-score: {:.4f}]".format(accuracy, fscore) | Naive Predictor: [Accuracy score: 0.2478, F-score: 0.2917]
| Apache-2.0 | p2_sl_finding_donors/p2_sl_finding_donors.ipynb | superkley/udacity-mlnd |
Supervised Learning Models**The following supervised learning models are currently available in** [`scikit-learn`](http://scikit-learn.org/stable/supervised_learning.html) **that you may choose from:**- Gaussian Naive Bayes (GaussianNB)- Decision Trees- Ensemble Methods (Bagging, AdaBoost, Random Forest, Gradient Boosting)- K-Nearest Neighbors (KNeighbors)- Stochastic Gradient Descent Classifier (SGDC)- Support Vector Machines (SVM)- Logistic Regression Question 2 - Model ApplicationList three of the supervised learning models above that are appropriate for this problem that you will test on the census data. For each model chosen- *Describe one real-world application in industry where the model can be applied.* (You may need to do research for this — give references!)- *What are the strengths of the model; when does it perform well?*- *What are the weaknesses of the model; when does it perform poorly?*- *What makes this model a good candidate for the problem, given what you know about the data?* **Answer: **Total number of records: 45222The algorithms we're searching here is for a supervised classification problem predicting a category using labeled data with less than 100K samples.* **Support Vector Machine** (SVM): * Real-world application: classifying proteins, protein-protein interaction * References: [Bioinformatics - Semi-Supervised Multi-Task Learning for Predicting Interactions between HIV-1 and Human Proteins](https://static.googleusercontent.com/media/research.google.com/de//pubs/archive/35765.pdf) * Strengths of the model: * effective in high dimensional spaces and with nonlinear relationships * robust to noise (because margins maximized and theoretical bounds on overfitting) * Weaknesses of the model: * requires to select a good kernel function and a number of hyperparameters such as the regularization parameter and the number of iterations * sensitive to feature scaling * model parameters are difficult to interpret * requires significant memory and processing power * tuning the regularization parameters required to avoid overfitting * Reasoning: *Linear SVC* is the optimal estimator following the [Scikit-Learn - Choosing the right estimator](http://scikit-learn.org/stable/tutorial/machine_learning_map/) when using less than 100K samples to solve to classification problem.* **Logistic Regression**: * Real-world application: media and advertising campaigns optimization and decision making * References: [Evaluating Online Ad Campaigns in a Pipeline: Causal Models At Scale](https://static.googleusercontent.com/media/research.google.com/de//pubs/archive/36552.pdf) * Strengths of the model: * simple, no user-defined parameters to experiment with unless you regularize, β is intuitive * fast to train and to predict * easy to interpret: output can be interpreted as a probability * pretty robust to noise with low variance and less prone to over-fitting * lots of ways to regularize the model * Weaknesses of the model: * unstable when one predictor could almost explain the response variable * often less accurate than the newer methods * Interpreting θ isn't straightforward * Reasoning: It's similar to *linear SVC*, is widely used and can be easyly implemented.* **K-Nearest Neighbors (KNeighbors)**: * Real-world application: image and video content classification * References: [Clustering billions of images with large scale nearest neighbor search](https://static.googleusercontent.com/media/research.google.com/de//pubs/archive/32616.pdf) * Strengths of the model: * simple and powerful * easy to explain * no training involved ("lazy") * naturally handles multiclass classification and regression * learns nonlinear boundaries * Weaknesses of the model: * expensive and slow to predict new instances ("lazy") * must define a meaningful distance function (preference bias) * need to decide on a good distance metric * performs poorly on high-dimensionality datasets (curse of high dimensionality) * Reasoning: *KNeighbors* classifier is the next option suggested on the machine learning map when *linear SVC* does work poor. Since our dataset is low-dimensional and it should generate reasonable results. Implementation - Creating a Training and Predicting PipelineTo properly evaluate the performance of each model you've chosen, it's important that you create a training and predicting pipeline that allows you to quickly and effectively train models using various sizes of training data and perform predictions on the testing data. Your implementation here will be used in the following section.In the code block below, you will need to implement the following: - Import `fbeta_score` and `accuracy_score` from [`sklearn.metrics`](http://scikit-learn.org/stable/modules/classes.htmlsklearn-metrics-metrics). - Fit the learner to the sampled training data and record the training time. - Perform predictions on the test data `X_test`, and also on the first 300 training points `X_train[:300]`. - Record the total prediction time. - Calculate the accuracy score for both the training subset and testing set. - Calculate the F-score for both the training subset and testing set. - Make sure that you set the `beta` parameter! | # Import two metrics from sklearn - fbeta_score and accuracy_score
from sklearn.metrics import fbeta_score, accuracy_score
def train_predict(learner, sample_size, X_train, y_train, X_test, y_test):
'''
inputs:
- learner: the learning algorithm to be trained and predicted on
- sample_size: the size of samples (number) to be drawn from training set
- X_train: features training set
- y_train: income training set
- X_test: features testing set
- y_test: income testing set
'''
results = {}
# Fit the learner to the training data using slicing with 'sample_size'
start = time() # Get start time
learner = learner.fit(X_train[:sample_size], y_train[:sample_size])
end = time() # Get end time
# Calculate the training time
results['train_time'] = end - start
# Get the predictions on the test set,
# then get predictions on the first 300 training samples
start = time() # Get start time
predictions_test = learner.predict(X_test)
predictions_train = learner.predict(X_train[:300])
end = time() # Get end time
# Calculate the total prediction time
results['pred_time'] = end - start
# Compute accuracy on the first 300 training samples
results['acc_train'] = accuracy_score(y_train[:300], predictions_train)
# Compute accuracy on test set
results['acc_test'] = accuracy_score(y_test, predictions_test)
# Compute F-score on the the first 300 training samples
results['f_train'] = fbeta_score(y_train[:300], predictions_train, beta=.5)
# Compute F-score on the test set
results['f_test'] = fbeta_score(y_test, predictions_test, beta=.5)
# Success
print "{} trained on {} samples.".format(learner.__class__.__name__, sample_size)
# Return the results
return results | _____no_output_____ | Apache-2.0 | p2_sl_finding_donors/p2_sl_finding_donors.ipynb | superkley/udacity-mlnd |
Implementation: Initial Model EvaluationIn the code cell, you will need to implement the following:- Import the three supervised learning models you've discussed in the previous section.- Initialize the three models and store them in `'clf_A'`, `'clf_B'`, and `'clf_C'`. - Use a `'random_state'` for each model you use, if provided. - **Note:** Use the default settings for each model — you will tune one specific model in a later section.- Calculate the number of records equal to 1%, 10%, and 100% of the training data. - Store those values in `'samples_1'`, `'samples_10'`, and `'samples_100'` respectively.**Note:** Depending on which algorithms you chose, the following implementation may take some time to run! | # Import the three supervised learning models from sklearn
from sklearn.svm import LinearSVC
from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import KNeighborsClassifier
# Initialize the three models
clf_A = LinearSVC(random_state=42)
clf_B = LogisticRegression(random_state=42)
clf_C = KNeighborsClassifier()
# Calculate the number of samples for 1%, 10%, and 100% of the training data
n = len(y_train)
samples_1 = int(round(n / 100.0))
samples_10 = int(round(n / 10.0))
samples_100 = n
# Collect results on the learners
results = {}
for clf in [clf_A, clf_B, clf_C]:
clf_name = clf.__class__.__name__
results[clf_name] = {}
for i, samples in enumerate([samples_1, samples_10, samples_100]):
results[clf_name][i] = \
train_predict(clf, samples, X_train, y_train, X_test, y_test)
# Run metrics visualization for the three supervised learning models chosen
vs.evaluate(results, accuracy, fscore) | LinearSVC trained on 362 samples.
LinearSVC trained on 3618 samples.
LinearSVC trained on 36177 samples.
LogisticRegression trained on 362 samples.
LogisticRegression trained on 3618 samples.
LogisticRegression trained on 36177 samples.
KNeighborsClassifier trained on 362 samples.
KNeighborsClassifier trained on 3618 samples.
KNeighborsClassifier trained on 36177 samples.
| Apache-2.0 | p2_sl_finding_donors/p2_sl_finding_donors.ipynb | superkley/udacity-mlnd |
---- Improving ResultsIn this final section, you will choose from the three supervised learning models the *best* model to use on the student data. You will then perform a grid search optimization for the model over the entire training set (`X_train` and `y_train`) by tuning at least one parameter to improve upon the untuned model's F-score. Question 3 - Choosing the Best Model*Based on the evaluation you performed earlier, in one to two paragraphs, explain to *CharityML* which of the three models you believe to be most appropriate for the task of identifying individuals that make more than \$50,000.* **Hint:** Your answer should include discussion of the metrics, prediction/training time, and the algorithm's suitability for the data. **Answer: **| | training time | predicting time | training set scores | testing set scores ||----------------------|----------------------------|-----------------|----------------|| **LinearSVC** | ++ | +++ | +++ | **+++** || LogisticRegression | +++ | +++ | ++ | ++ || KNeighborsClassifier | + | --- | +++ | + |Based on the evaluation the *linear SVC* model is the most appropriate for the task. Compared to the other two models in testing, it's both fast and has the highest scores. While *linear SVC* and *logistic regression* have almost the same accuracy, its *f-score* is slightly higher indicating that *linear SVC* has more correct positive predictions on actual positive observations.Although *logistic regression* has a shorter training time, it has worse *f-score* when applied to the testing set. In a real-world setting the testing scores are the metrics that do matter. The moderate longer training time can be ignored. *K-neighbors* outperforms the other two only when predicting the training scores. But with an even poorer testing score it actually shows that the model has an overfitting problem. Question 4 - Describing the Model in Layman's Terms*In one to two paragraphs, explain to *CharityML*, in layman's terms, how the final model chosen is supposed to work. Be sure that you are describing the major qualities of the model, such as how the model is trained and how the model makes a prediction. Avoid using advanced mathematical or technical jargon, such as describing equations or discussing the algorithm implementation.* **Answer: ** As the final model we used a classifier called *linear SVC* which assumes that the underlying data are linearly separable. In a simplified 2-dimensional space this technique attemps to find the best line that separates the two classes of points with the largest margin. In higher dimensional space, the algorithm searches for the best hyperplane following the same principle by maximizing the margin (e.g. a plane in 3-dimensional space).In our case, in the training phase the algorithm calculates the best model to separate the different classes in the training data by a maximum margin. And with the trained model the algorithm is able to predict the unseen examples. Implementation: Model TuningFine tune the chosen model. Use grid search (`GridSearchCV`) with at least one important parameter tuned with at least 3 different values. You will need to use the entire training set for this. In the code cell below, you will need to implement the following:- Import [`sklearn.grid_search.GridSearchCV`](http://scikit-learn.org/0.17/modules/generated/sklearn.grid_search.GridSearchCV.html) and [`sklearn.metrics.make_scorer`](http://scikit-learn.org/stable/modules/generated/sklearn.metrics.make_scorer.html).- Initialize the classifier you've chosen and store it in `clf`. - Set a `random_state` if one is available to the same state you set before.- Create a dictionary of parameters you wish to tune for the chosen model. - Example: `parameters = {'parameter' : [list of values]}`. - **Note:** Avoid tuning the `max_features` parameter of your learner if that parameter is available!- Use `make_scorer` to create an `fbeta_score` scoring object (with $\beta = 0.5$).- Perform grid search on the classifier `clf` using the `'scorer'`, and store it in `grid_obj`.- Fit the grid search object to the training data (`X_train`, `y_train`), and store it in `grid_fit`.**Note:** Depending on the algorithm chosen and the parameter list, the following implementation may take some time to run! | # Import 'GridSearchCV', 'make_scorer', and any other necessary libraries
from sklearn.grid_search import GridSearchCV
from sklearn.metrics import make_scorer
# Initialize the classifier
clf = LinearSVC(random_state=42)
# Create the parameters list you wish to tune
parameters = {
'C': [.1, .5, 1.0, 5.0, 10.0],
'loss': ['hinge', 'squared_hinge'],
'tol': [1e-3, 1e-4, 1e-5],
'random_state': [0, 42, 10000]
}
# Make an fbeta_score scoring object
scorer = make_scorer(fbeta_score, beta=.5)
# Perform grid search on the classifier using 'scorer' as the scoring method
grid_obj = GridSearchCV(clf, parameters, scoring=scorer)
# Fit the grid search object to the training data and find the optimal parameters
grid_fit = grid_obj.fit(X_train, y_train)
# Get the estimator
best_clf = grid_fit.best_estimator_
# Make predictions using the unoptimized and model
predictions = (clf.fit(X_train, y_train)).predict(X_test)
best_predictions = best_clf.predict(X_test)
# Report the before-and-afterscores
print "Unoptimized model\n------"
print "Accuracy score on testing data: {:.4f}".format(accuracy_score(y_test, predictions))
print "F-score on testing data: {:.4f}".format(fbeta_score(y_test, predictions, beta = 0.5))
print "\nOptimized Model\n------"
print "Final accuracy score on the testing data: {:.4f}".format(accuracy_score(y_test, best_predictions))
print "Final F-score on the testing data: {:.4f}".format(fbeta_score(y_test, best_predictions, beta = 0.5))
# print optimized parameters
print("Optimized params for Linear SVM: {}".format(
grid_fit.best_params_
)) | Optimized params for Linear SVM: {'loss': 'squared_hinge', 'C': 10.0, 'random_state': 0, 'tol': 0.001}
| Apache-2.0 | p2_sl_finding_donors/p2_sl_finding_donors.ipynb | superkley/udacity-mlnd |
Question 5 - Final Model Evaluation_What is your optimized model's accuracy and F-score on the testing data? Are these scores better or worse than the unoptimized model? How do the results from your optimized model compare to the naive predictor benchmarks you found earlier in **Question 1**?_ **Note:** Fill in the table below with your results, and then provide discussion in the **Answer** box. Results:| Metric | Benchmark Predictor | Unoptimized Model | Optimized Model || :------------: | :-----------------: | :---------------: | :-------------: | | Accuracy Score | .2478 | .8507 | .8514 || F-score | .2917 | .7054 | .7063 | **Answer: **The scores of the *optimized model* are a bit better than the *unoptimized model* showing that the defaults were actually very good in the first place. Compared to the *benchmark predictor*, the optimized model is by manifold better with larger accuracy and f-scores. ---- Feature ImportanceAn important task when performing supervised learning on a dataset like the census data we study here is determining which features provide the most predictive power. By focusing on the relationship between only a few crucial features and the target label we simplify our understanding of the phenomenon, which is most always a useful thing to do. In the case of this project, that means we wish to identify a small number of features that most strongly predict whether an individual makes at most or more than \$50,000.Choose a scikit-learn classifier (e.g., adaboost, random forests) that has a `feature_importance_` attribute, which is a function that ranks the importance of features according to the chosen classifier. In the next python cell fit this classifier to training set and use this attribute to determine the top 5 most important features for the census dataset. Question 6 - Feature Relevance ObservationWhen **Exploring the Data**, it was shown there are thirteen available features for each individual on record in the census data. _Of these thirteen records, which five features do you believe to be most important for prediction, and in what order would you rank them and why?_ **Answer:**Of the thirteen available features we believe that the following five features are the most important for prediction and ordered them by their importance with the most important at top. From looking at the data and following the rules of our society:* *occupation*: different occupations have usually different salary ranges* *capital-gain*: the rich get richer. Capital gain is an indicator of the personal wealth.* *education-level*: when employed, people with higher education gets better paid* *hours-per-week*: part time jobs are often less paid* *age*: older people tends to earn more Implementation - Extracting Feature ImportanceChoose a `scikit-learn` supervised learning algorithm that has a `feature_importance_` attribute availble for it. This attribute is a function that ranks the importance of each feature when making predictions based on the chosen algorithm.In the code cell below, you will need to implement the following: - Import a supervised learning model from sklearn if it is different from the three used earlier. - Train the supervised model on the entire training set. - Extract the feature importances using `'.feature_importances_'`. | # Import a supervised learning model that has 'feature_importances_'
from sklearn.ensemble import AdaBoostClassifier
# Train the supervised model on the training set
model = AdaBoostClassifier(random_state=42).fit(X_train, y_train)
# Extract the feature importances
importances = model.feature_importances_
# Plot
vs.feature_plot(importances, X_train, y_train) | _____no_output_____ | Apache-2.0 | p2_sl_finding_donors/p2_sl_finding_donors.ipynb | superkley/udacity-mlnd |
Question 7 - Extracting Feature ImportanceObserve the visualization created above which displays the five most relevant features for predicting if an individual makes at most or above \$50,000. _How do these five features compare to the five features you discussed in **Question 6**? If you were close to the same answer, how does this visualization confirm your thoughts? If you were not close, why do you think these features are more relevant?_ | # print top 10 features importances
def rank_features(features, scores, descending=True, n=10):
"""
sorts and cuts features by scores.
:return: array of [feature name, score] tuples
"""
return sorted(
[[f, s] for f, s in zip(features, scores) if s],
key=lambda x: x[1],
reverse=descending
)[:n]
rank_features(
features.columns,
importances
)
# capital-loss and income have a positive correlation
features['capital-loss'].corr(income) | _____no_output_____ | Apache-2.0 | p2_sl_finding_donors/p2_sl_finding_donors.ipynb | superkley/udacity-mlnd |
**Answer:**From the top 5 features selected by *AdaBoostClassifier* we got 4 hits (*age*, *capital-gain*, *hours-per-week* and *education-level*). That *capital-loss* has a such big influence is really surprising and by looking at the cell above, *income* and *capital-loss* are even positively correlated. Our top one guess *occupation* hasn't made into top 10 in the feature importances.The visualization of the feature importances confirms our guess that our observation in the society is actually true that older and higher educated people with money (big *capital-loss* or *capital-gain*) would have higher salaries. These thoughts are now quantified and explained by the classfier. Feature SelectionHow does a model perform if we only use a subset of all the available features in the data? With less features required to train, the expectation is that training and prediction time is much lower — at the cost of performance metrics. From the visualization above, we see that the top five most important features contribute more than half of the importance of **all** features present in the data. This hints that we can attempt to *reduce the feature space* and simplify the information required for the model to learn. The code cell below will use the same optimized model you found earlier, and train it on the same training set *with only the top five important features*. | # Import functionality for cloning a model
from sklearn.base import clone
# Reduce the feature space
X_train_reduced = X_train[X_train.columns.values[(np.argsort(importances)[::-1])[:5]]]
X_test_reduced = X_test[X_test.columns.values[(np.argsort(importances)[::-1])[:5]]]
# Train on the "best" model found from grid search earlier
start = time()
clf = (clone(best_clf)).fit(X_train_reduced, y_train)
training_time_reduced = time() - start
# Make new predictions
reduced_predictions = clf.predict(X_test_reduced)
# Report scores from the final model using both versions of data
print "Final Model trained on full data\n------"
print "Accuracy on testing data: {:.4f}".format(accuracy_score(y_test, best_predictions))
print "F-score on testing data: {:.4f}".format(fbeta_score(y_test, best_predictions, beta = 0.5))
print "\nFinal Model trained on reduced data\n------"
print "Accuracy on testing data: {:.4f}".format(accuracy_score(y_test, reduced_predictions))
print "F-score on testing data: {:.4f}".format(fbeta_score(y_test, reduced_predictions, beta = 0.5))
# compare scores
def relative_diff_pct(x, y):
"""
returns the relative difference between x and y in percent.
"""
return 100 * ((y - x) / x)
print('Relative Diff. of accuracy-scores: {0:.2f}%'.format(
relative_diff_pct(.8514, .8096)
))
print('Relative Diff. of f-scores: {0:.2f}%'.format(
relative_diff_pct(.7063, .5983)
))
# Train with full data
start = time()
clf = (clone(best_clf)).fit(X_train, y_train)
training_time_full = time() - start
print('Relative Diff. of training times: {0:.2f}%'.format(
relative_diff_pct(training_time_reduced, training_time_full)
)) | Relative Diff. of training times: 94.68%
| Apache-2.0 | p2_sl_finding_donors/p2_sl_finding_donors.ipynb | superkley/udacity-mlnd |
Question 8 - Effects of Feature Selection*How does the final model's F-score and accuracy score on the reduced data using only five features compare to those same scores when all features are used?* *If training time was a factor, would you consider using the reduced data as your training set?* **Answer:** Both the accuracy and f-scores dropped down when using only the top 5 features. The f-scores have an **over 15% difference**, while the difference between the accuracy scores is at about 5%.The training time with reduced data was more than **2 times faster** than the training time of the full data set. In some other scenarios when the training time or the computation power if of high priority, we would consider to use the reduced data. But since the difference between the f-scores are considerably large we would use the full training set for this problem. References* [Udacity - Machine Learning](https://classroom.udacity.com/courses/ud262)* [Laurad Hamilton - ML Cheat Sheet](http://www.lauradhamilton.com/machine-learning-algorithm-cheat-sheet)* [Scikit-Learn - ML Modules](http://scikit-learn.org/stable/modules/sgd.html)* [Scikit-Learn - AdaBoostClassifier](http://scikit-learn.org/stable/modules/generated/sklearn.ensemble.AdaBoostClassifier.html)* [rcompton - Supervised Learning Superstitions](https://github.com/rcompton/ml_cheat_sheet)* [Wikipedia - Support Vector Machine](https://en.wikipedia.org/wiki/Support_vector_machineDefinition)* [Quora - SVM in layman's terms](https://www.quora.com/What-does-support-vector-machine-SVM-mean-in-laymans-terms) Reproduction Environment | import IPython
print IPython.sys_info()
!pip freeze | alabaster==0.7.9
anaconda-client==1.6.0
anaconda-navigator==1.4.3
argcomplete==1.0.0
astroid==1.4.9
astropy==1.3
Babel==2.3.4
backports-abc==0.5
backports.shutil-get-terminal-size==1.0.0
backports.ssl-match-hostname==3.4.0.2
beautifulsoup4==4.5.3
bitarray==0.8.1
blaze==0.10.1
bokeh==0.12.4
boto==2.45.0
Bottleneck==1.2.0
cdecimal==2.3
cffi==1.9.1
chardet==2.3.0
chest==0.2.3
click==6.7
cloudpickle==0.2.2
clyent==1.2.2
colorama==0.3.7
comtypes==1.1.2
conda==4.3.16
configobj==5.0.6
configparser==3.5.0
contextlib2==0.5.4
cookies==2.2.1
cryptography==1.7.1
cycler==0.10.0
Cython==0.25.2
cytoolz==0.8.2
dask==0.13.0
datashape==0.5.4
decorator==4.0.11
dill==0.2.5
docutils==0.13.1
enum34==1.1.6
et-xmlfile==1.0.1
fastcache==1.0.2
Flask==0.12
Flask-Cors==3.0.2
funcsigs==1.0.2
functools32==3.2.3.post2
futures==3.0.5
gevent==1.2.1
glueviz==0.9.1
greenlet==0.4.11
grin==1.2.1
h5py==2.6.0
HeapDict==1.0.0
idna==2.2
imagesize==0.7.1
ipaddress==1.0.18
ipykernel==4.5.2
ipython==5.1.0
ipython-genutils==0.1.0
ipywidgets==5.2.2
isort==4.2.5
itsdangerous==0.24
jdcal==1.3
jedi==0.9.0
Jinja2==2.9.4
jsonschema==2.5.1
jupyter==1.0.0
jupyter-client==4.4.0
jupyter-console==5.0.0
jupyter-core==4.2.1
lazy-object-proxy==1.2.2
llvmlite==0.15.0
locket==0.2.0
lxml==3.7.2
MarkupSafe==0.23
matplotlib==2.0.0
menuinst==1.4.4
mistune==0.7.3
mpmath==0.19
multipledispatch==0.4.9
nbconvert==4.2.0
nbformat==4.2.0
networkx==1.11
nltk==3.2.2
nose==1.3.7
notebook==4.4.1
numba==0.30.1+0.g8c1033f.dirty
numexpr==2.6.1
numpy==1.11.3
numpydoc==0.6.0
odo==0.5.0
openpyxl==2.4.1
pandas==0.19.2
partd==0.3.7
path.py==0.0.0
pathlib2==2.2.0
patsy==0.4.1
pep8==1.7.0
pickleshare==0.7.4
Pillow==4.0.0
ply==3.9
prompt-toolkit==1.0.9
psutil==5.0.1
py==1.4.32
pyasn1==0.1.9
pycosat==0.6.1
pycparser==2.17
pycrypto==2.6.1
pycurl==7.43.0
pyflakes==1.5.0
pygame==1.9.3
Pygments==2.1.3
pylint==1.6.4
pymongo==3.3.0
pyOpenSSL==16.2.0
pyparsing==2.1.4
pytest==3.0.5
python-dateutil==2.6.0
pytz==2016.10
pywin32==220
PyYAML==3.12
pyzmq==16.0.2
QtAwesome==0.4.3
qtconsole==4.2.1
QtPy==1.2.1
requests==2.12.4
requests-file==1.4.1
responses==0.5.1
rope==0.9.4
scandir==1.4
scikit-image==0.12.3
scikit-learn==0.18.1
scipy==0.18.1
seaborn==0.7.1
simplegeneric==0.8.1
singledispatch==3.4.0.3
six==1.10.0
snowballstemmer==1.2.1
sockjs-tornado==1.0.3
sphinx==1.5.1
spyder==3.1.2
SQLAlchemy==1.1.5
statsmodels==0.6.1
subprocess32==3.2.7
sympy==1.0
tables==3.2.2
toolz==0.8.2
tornado==4.4.2
traitlets==4.3.1
unicodecsv==0.14.1
wcwidth==0.1.7
Werkzeug==0.11.15
widgetsnbextension==1.2.6
win-unicode-console==0.5
wrapt==1.10.8
xlrd==1.0.0
XlsxWriter==0.9.6
xlwings==0.10.2
xlwt==1.2.0
| Apache-2.0 | p2_sl_finding_donors/p2_sl_finding_donors.ipynb | superkley/udacity-mlnd |
Describing continuous variables using Probability Density Functions | import numpy as np
import matplotlib.pyplot as plt
data = np.random.normal(0.5, 0.1, 1000)
histogram = plt.hist(data, bins=10, range=(0.1, 1.5))
histogram = plt.hist(data, bins=20, range=(0.1, 1.5), density=True)
height = histogram[0][6].round(4)
x1 = histogram[1][6].round(4)
x2 = histogram[1][7].round(4)
3.24 * 0.07 | _____no_output_____ | MIT | module_9_statistics_probability/probability_density_function_test.ipynb | wiplane/foundations-of-datascience-ml |
__General basic approach for applying Data Science.__- Collect Data.- Extract features.- Extract the target(label).- Select the Estimator for learning.- Tune the parameters.- Fit the train data set. - Test against testing_data_set.- Check accuracy.- Deploy to production.- Write unit test cases for model.- write live notification for model.- Keep trainig the model with new data(fresh data). __Seaborn is a Python data visualization library based on matplotlib. It provides a high-level interface for drawing attractive and informative statistical graphics.__ | #Import Seaborn
import seaborn as sns | _____no_output_____ | Apache-2.0 | Iris/Iris.ipynb | sachin032/Supervised-Machin-Learning |
__Seaborn comes with the iris data set , all we need is to load it. After loading we can do some spy things over data__ | #Load iris data set from Sea born
iris = sns.load_dataset("iris")
iris.head(4)
%matplotlib inline
import seaborn as sns;
sns.set()
sns.pairplot(iris, hue='species', size=3.5); | _____no_output_____ | Apache-2.0 | Iris/Iris.ipynb | sachin032/Supervised-Machin-Learning |
__Drop 'Species' feature from feature matrix, and look at the shape.__ | iris.shape
#Perform basic EDA
iris.describe()
#Spy over how many outcomes are present in the Dataset
iris.species.unique() | _____no_output_____ | Apache-2.0 | Iris/Iris.ipynb | sachin032/Supervised-Machin-Learning |
__Time to split the iris dataset into Training:Tesing datset. Remember there is no standard approach fro this dividation even though we divide, Based on suggestions from ML/Data science leaders 70:30 approach is good.__ | #Import train_test_split
from sklearn.model_selection import train_test_split
#Split iris dataset into training and testing datset
trainIris , testIris = train_test_split(iris,test_size = 0.3)
#Look over training set
trainIris.head()
#Look over testing set
testIris.head() | _____no_output_____ | Apache-2.0 | Iris/Iris.ipynb | sachin032/Supervised-Machin-Learning |
__Testing dataset must not hold the target variable/outcomes, so that we can predict the outcome using our trained regression model from trainig datset__ | #Drop Species from testing dataset
testIris = testIris.drop(['species'],axis=1)
#Test set after dropping target/outcome column
testIris.head() | _____no_output_____ | Apache-2.0 | Iris/Iris.ipynb | sachin032/Supervised-Machin-Learning |
Structural Transformation NotesBelow some brief notes on general equilibrium modeling of structural transformation. Some of the presentation illustrates and expands upon this short useful survey:> Matsuyama, K., 2008. Structural change. in Durlauf and Blume eds. *The new Palgrave dictionary of economics* 2, pp.The note is organized around the following sections:- Market Clearing Neo-Classical Models - Push out of agriculture vs. Pull into Manufacturing - Pull in an Open Economy Model - Push in Closed Economy with Non-homothetic preferences- Productivity growth caused by structural change- Impediments to structural change- Spillovers, Complementarities, and Multiple Equilibria --- Market Clearing Neo-Classical ModelsHere we seek to explain structural transformation and the accompanying movement of labor out of agriculture and into other sectors in a market-clearing neo-classical model with no market failures. In these model the marginal value product of labor is the same in both agriculture and manufacturing, hence there is no 'dualism' due to market frictions of one kind or another.Matsuyama builds a very simple neo-classical model with two sectors (in effect a specific factors model). **Production**Sector $j \in (1,2)$ is given by $Y_j = A_j \cdot F_j(n_j)$. Let $j=1$ be the primary (agricultural) sector and $j=2$ the secondary (manufacturing) sector, where $A_j$ represents Total Factor Productivity (TFP) in each sector. We normalize the size of the population to 1. Then, if $n$ is the share (and total) labor used in sector 1 then $1-n$ is the amount left to be in sector two. Matsuyama refers to $F$ only as a generic increasing concave function, but for purposes of the graph examples, let's specify:$$A_1 F_1(n) = A_1 n^\alpha \\A_2 F_2(1-n) = A_2 (1-n)^\nu $$ Competitive markets will insure that labor is efficiently allocated across sectors such that the marginal value product of labor be equalized in each sector: $$A_1 F_1^\prime (n) = p A_2 F_2^\prime (1-n)$$ where $p=P_2/P_1$ is the relative price of sector 2 goods. We can trace out a production possibility frontier (PPF) by simply plotting $\left( A_1 F_1(n), A F_2(1-n) \right)$ as we vary $n$ from 0 to 1. Below we draw two PPFs. One with $A_1=A_2=1$ and another afteragricultural TFP has improved to $A_1=1.2$ (we are setting $\alpha=\nu=1/2$) | import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import fsolve
def F(n, a):
return n ** a
def Fprime(n, a):
return a* n ** (a-1)
def PPF(A1=1, A2=1, a1=0.5, a2=0.5, ax=None):
if ax is None:
ax = plt.gca()
n = np.linspace(0,1,50)
plt.plot( A1*F(n, a1), A2*F(1-n, a2) )
plt.xlabel(r'$Y_1$'), plt.ylabel(r'$Y_2$')
fig, ax = plt.subplots(1)
PPF(A1=1, A2=1, ax=ax)
PPF(A1=1.3, A2=1, ax=ax)
ax.set_xlim(left=0), ax.set_ylim(bottom=0)
ax.set_aspect('equal') | _____no_output_____ | MIT | notebooks/StructuralT1.ipynb | jhconning/DevII |
Push and/or PullThe large literature on structural transformation often distinguishes between forces that 'Push' or 'Pull' labor out of agriculture. 'Pull' could come about, for example, via an increase over time of the relative price of manufactures $p$, or an increase in relative TFP $A_2/A_1$. These have the effect of shifting out the demand for labor (the marginal value product or labor curve $p A_2 F_2^\prime (1-n)$ relative to that in agriculture, leading to an incipient rise in the manufacturing wage that transforms the economy by attracting labor to that sector.As demonstrated below, it's easy to illustrate Pull effects in this economy with standard homothetic preferences in either the open or closed economy.The 'Push' argument is associated the idea that rises in agricultural productivity $A_1$ will mean that more food can be produced with fewer workers and therefore that labor can be 'released' from agriculture to other sectors. A related prevalent view is than an 'agricultural revolution' is often a prior and necessary condition for an industrial revolution. It turns out one has to be a bit harder to get this effect to emerge in this standard neo-classical model because, as we've just argued, raising the relative productivity in a sector tends *increase* demand for labor unless the relative price of the good happens to simultaneously fall by enough to reverse that effect. As we'll show one way to engineer such an effect is to assume non-homothetic preferences to rise to a form of Engel's law or that manufactures have a higher income elasticity of demand, such that the agricultural terms of trade deteriorate against agriculture as incomes expand. The Open Economy with Homothetic PreferencesIn the open-economy version of this model, the relative price of manufactured goods $p$ is set and fixed on world markets and hence does not change during the period of analysis. We can focus on the optimum production allocation without worrying about preferences, because agents first maximize the value of income at world prices and then choose optimum consumption baskets.We can plot labor demand in each sector and solve for the equilibrium labor allocation $n^*$ that solves:$$A_1 F_1^\prime (n) = p A_2 F_2^\prime (1-n)$$ | def weq(A1=1, A2=1, a1=0.5, a2=0.5, p=1):
def foc(n):
return p * A2 * Fprime(1-n, a2) - A1 * Fprime(n, a1)
n = 0.75 # guess
ne = fsolve(foc, n)[0]
we = A1 * Fprime(ne, a1)
return ne, we
def sfm(A1=1, A2=1, a1=0.5, a2=0.5, p=1, ax=None):
if ax is None:
ax = plt.gca()
nn = np.linspace(0.01, 0.99, 100)
ax.plot(nn, A1 * Fprime(nn, a1))
ax.plot(nn, p * A2 * Fprime(1-nn, a2))
ne, we = weq(A1, A2, a1, a2, p)
ax.scatter(ne, we)
ax.axhline(we, linestyle =':')
ax.vlines(x = ne, ymin=0, ymax=we, linestyle =':')
ax.set_ylim(0,2)
ax.set_xlim(0,1)
ax.set_xlabel(r'$n$')
ax.text(0.8, 0.9*A1 *Fprime(1,a1), r'$L_1^d$')
ax.text(0.1, 0.9*p*A2 *Fprime(0.999, a2), r'$L_2^d$') | _____no_output_____ | MIT | notebooks/StructuralT1.ipynb | jhconning/DevII |
**Pull: Impact of increase in relative price of manufactures in open Economy**Exactly like a specific factors model diagram. A very similar diagram would depict effect of increase in sector 2 relative TFP $A_2/A_1$ | sfm(p=1)
sfm(p=1.5) | _____no_output_____ | MIT | notebooks/StructuralT1.ipynb | jhconning/DevII |
Exogenously driven increases in the relative productivity of manufactures drives this 'pull' effect. As Matsuyama explains, this is the sort of mechanism envisioned by Lewis (1954) although the Lewis model also has a form of dualism not captured here. In particular, we can see (from the diagram above) that in these models the expansion of one sector can be choked off by a rising wage. Lewis' assumption of "unlimited supplies of labor" in agriculture amounts to saying that there will be a very elastic supply of labor aso wages will not be fast to rise. Non-homothetic preferences In a closed economy the relative price $p$ is determined endogenously by a tangency between the PPF and the representative indifference curve. As mentioned above, we'll need non-homothetic preferences in order to get the kind of 'Push' effect used in Gollin et al (2002):The consumer has Stone-Geary preferences of the form:$$U(C_1, C_2) = \beta \cdot \log(C_1 - \gamma) + \log(C_2)$$If $\gamma=0$ these would be standard homothetic preferences with linear income expansion paths (i.e. consumers maintain consumption ratio $C_2/C_1$ as income expands). When $\gamma>0$ preferences are non-homothetic. We interpret $\gamma$ as a minimum agricultural (food) consumption requirement. At low levels of income, all income is devoted to satisfying the requirement, but once that level is reached, remaining income will be spent in constant expenditure shares: $$C_1 - \gamma = \frac{\beta}{1+\beta} \frac{Y}{P_1} \\C_2 = \frac{1}{1+\beta} \frac{Y}{P_2}$$ Define $p=P_2/P_1$ as the relative price of good 2, then $C_1$ and $C_2$ will be consumed proportional to each other following: $$C_1 =\gamma + (\beta p) C_2$$ Below is a plot of the optimum $C_2/C_1$ ratio for homothetic (blue, $\gamma=0$) and non-homothetic (orange, $\gamma=1$) preferences. In the latter case, after income reaches the level at which subsistence food needs are satisfied, the $C_2/C_1$ ratio (think of a ray from origin to a point on orange line) increases as incomes expand. | c1 = np.linspace(0,4,100)
def c2(c1, gam, beta, p):
return (c1 - gam)/(beta * p)
plt.plot(c1, c2(c1, 0, 0.5, 1))
plt.plot(c1, c2(c1, 1, 0.5, 1))
plt.ylim(0, 4), plt.xlim(0, 4)
plt.xlabel(r'$C_1$'), plt.ylabel(r'$C_2$')
plt.grid()
plt.gca().set_aspect('equal') | _____no_output_____ | MIT | notebooks/StructuralT1.ipynb | jhconning/DevII |
Closed Economy We're looking for a tangency between the PPF and the representative agent's indifference curve, equal to the common price ratio. This $MRS = p= MPT$ condition can be written:$$\frac{1}{\beta} \frac{C_1 - \gamma}{C_2} = p = \frac{A_1 F_1^\prime (n)}{A_2 F_2^\prime (1-n)} $$Using the fact that a closed economy must produce what it consumes we can substitute $C_1 = A_1 F_1(n)$ and $C_2 = A_2 F_2(1-n)$ and manipulate to obtain condition (2) in Matsuyama:$$F_1(n) - \frac{\beta F_2(1-n) F_1 ^\prime (n)}{F_2 ^\prime (1-n)} = \frac{\gamma}{A_1}$$ This implicitly defines $n$ as a decreasing function of $A_1$. Two things are striking here (both partly consequences of the Cobb-Douglas):1) $A_2$ plays no role. As $A_2$ rises $p$ falls by just enough to offset, leaving relative demand for labor unchanged.2) At any $\gamma >0$ the agricultural labor share $n$ will fall with $A_1$. This is the Push effect.In the plot below we plot this left hand side in red. The dashed line represents a value of $\frac{\gamma}{A_1}$. We can see that if $A_1$ rises (the dashed line moves down) the new equilibrium will involve less agricultural labor $n$. | def lhs(n, a1, a2, beta):
F1 = F(n, a1)
dF1 = Fprime(n, a1)
F2 = F(1-n, a2)
dF2 = Fprime(1-n, a2)
return F1 - (beta*F2*dF1)/dF2
n = np.linspace(0.2,0.7,50)
plt.plot(n, lhs(n, 0.5, 0.5, 0.5), color='r')
plt.axhline(0);
plt.axhline(0.5, linestyle='--')
plt.xlabel(r'$n$'); | _____no_output_____ | MIT | notebooks/StructuralT1.ipynb | jhconning/DevII |
We can solve for the closed economy equilibrium and plot things on a PPF diagram. | def neq(A1=1, a1=0.5, a2=0.5, beta=0.5, gamma= 0.5):
'''Closed economy eqn from MRS=MPT'''
def foc(n):
return lhs(n, a1, a2, beta) - gamma/A1
n = 0.7 # guess
ne = fsolve(foc, n)[0]
return ne
def plot_opt(A1, A2, a1, a2, beta, gamma):
ne = neq(A1, a1, a2, beta, gamma)
Y1 = A1 * F(ne, a1)
Y2 = A2 * F(1-ne, a2)
p = (1/beta) * (Y1-gamma)/Y2
print(f'A1={A1}, n={ne:0.2f}, p={p:0.2f}')
plt.scatter(Y1, Y2)
ax =plt.gca()
PPF(A1=A1, A2=A2, a1=a1, a2=a2, ax=ax) | _____no_output_____ | MIT | notebooks/StructuralT1.ipynb | jhconning/DevII |
Here we see structural transformation and a rise in the relative price of manufactures as TFP in agriculture increases: | plot_opt(1, 1, 0.5, 0.75, 1, 0.4)
plot_opt(2, 1, 0.5, 0.75, 1, 0.4)
plt.xlim(left=0)
plt.ylim(bottom=0); | A1=1, n=0.58, p=0.70
A1=2, n=0.48, p=1.63
| MIT | notebooks/StructuralT1.ipynb | jhconning/DevII |
Feature ExtractionIn machine learning, feature extraction aims to compute values (features) from images, intended to be informative and non-redundant, facilitating the subsequent learning and generalization steps, and in some cases leading to better human interpretations. These features may be handcrafted (manually computed features based on a-priori information ) or convolutional features (detect patterns within the data without the prior definition of features or characteristics): Handcrafted: - Histogram features: Statistical moments extracted from the histogram describe image characteristics and provide a quantitative analysis of the image intensity distribution (entropy, intensity mean, standard deviation, skewness, kurtosis, and values at 0, 10, 50 (median) and 90 percentiles).- The gradient examines directional changes in the image gray level, and can extract relevant information (such as edges) within an image. Moments extracted from the image gradient are more robust to acquisition conditions, such as contrast variation, and properties of the acquisition equipment . Ten features were extracted from the gray level and morphological gradients (five from each): intensity mean, standard deviation, skewness, kurtosis and percentage of non-zero values.- Local binary pattern (LBP) is a texture spectrum model that may be used to identify patterns in an image. The LBP histogram comprises the frequency of occurrence of different patterns within an image. Ten features were extracted from the LBP by using a 10-bin LBP histogram.- The Haar wavelet is a multi-resolution technique that transforms images into a domain where both spatial and frequency information is present. Features separately extracted from each sub-image present desired scale-dependent properties. When considering two decomposition levels, eight sub-images are generated. The mean value within each sub-image were computed and used as features (total of eight features). Convolutional featuresComputed by using a very deep convolutional network (VGG16) with pre-trained imagenet weights. For each MR volume, the convolutional features were computed in the central 2D axial, sagittal and coronal slices. For each of these three views, 25,088 convolutional features were computed and combined. Besides the image and patient information (MR vendor, magnetic field, age, gender), a total of 75,300 features were extracted and combined for each image: 8 features from the image histogram, 10 features from the image gradient, 10 features from the LBP histogra, 8 features from the Haar wavelet subimages and 75,264 convolutional features. Reading the data file containing patients information and features | ## data: vendor; magnetic field; age; gender; feats (65300)
# vendor: ge -> 10; philips -> 11; siemens -> 12
# gender: female -> 10; male -> 11
# feats: fs1 - histogram (8); fs2 - gradient (10); fs3 - lbp (10); fs4 - haar (8); fs5 - convolutional (75264)
import numpy as np
data = np.load('../Data/feats_cc359.npy.zip')['feats_cc359']
print '#samples, #info: ',data.shape
print 'patients age:', data[:,2] | #samples, #info: (359, 75304)
patients age: [ 55. 56. 63. 67. 62. 63. 62. 60. 69. 69. 49. 43. 66. 62. 44.
55. 50. 41. 57. 65. 48. 43. 43. 65. 51. 65. 41. 63. 51. 42.
65. 44. 67. 43. 49. 49. 41. 41. 41. 55. 61. 67. 58. 36. 49.
42. 54. 53. 43. 45. 44. 51. 39. 46. 44. 39. 61. 64. 55. 29.
55. 52. 53. 49. 42. 46. 57. 49. 56. 80. 56. 31. 49. 53. 41.
44. 43. 42. 47. 55. 67. 64. 66. 46. 71. 42. 42. 51. 46. 37.
51. 60. 60. 45. 43. 36. 45. 48. 51. 60. 52. 50. 56. 34. 52.
41. 38. 51. 57. 44. 51. 60. 45. 60. 49. 50. 49. 49. 53. 58.
61. 53. 58. 57. 65. 54. 58. 54. 54. 57. 41. 71. 64. 54. 52.
64. 65. 56. 56. 57. 53. 59. 55. 43. 62. 38. 58. 58. 53. 47.
71. 51. 52. 55. 57. 55. 54. 53. 54. 57. 55. 39. 64. 54. 44.
39. 55. 38. 44. 55. 51. 52. 51. 41. 50. 45. 57. 55. 53. 39.
36. 60. 58. 60. 52. 62. 63. 55. 66. 63. 59. 51. 64. 67. 55.
48. 54. 59. 64. 37. 58. 54. 56. 49. 64. 58. 58. 56. 57. 60.
65. 67. 65. 51. 46. 56. 45. 61. 49. 61. 61. 56. 56. 62. 47.
64. 58. 66. 55. 60. 56. 56. 52. 57. 61. 50. 59. 58. 56. 60.
60. 55. 58. 56. 48. 60. 53. 51. 58. 60. 41. 44. 58. 57. 57.
42. 57. 55. 56. 51. 59. 54. 51. 59. 56. 57. 60. 57. 59. 59.
60. 44. 56. 47. 50. 52. 42. 61. 49. 57. 56. 57. 44. 41. 56.
55. 53. 56. 59. 56. 48. 60. 50. 51. 55. 57. 57. 58. 37. 58.
53. 56. 53. 57. 59. 52. 57. 52. 42. 51. 50. 49. 34. 54. 59.
57. 45. 52. 45. 57. 51. 59. 56. 56. 55. 55. 50. 56. 58. 57.
61. 53. 41. 45. 54. 53. 59. 51. 59. 49. 60. 50. 54. 43. 53.
43. 52. 60. 60. 62. 52. 55. 58. 61. 55. 61. 55. 52. 58.]
| MIT | JNotebooks/feats-CC-hand-conv.ipynb | rmsouza01/ML101 |
Imports | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn import ensemble
from sklearn import metrics
from io import StringIO
from csv import writer | _____no_output_____ | MIT | jupyter notebook/Dota2 new data.ipynb | alykkehoy/Dota-2-winning-team-predictor |
Read in csv files | matches = pd.read_csv('../csv/matches.csv')
players = pd.read_csv('../csv/players.csv')
hero_names = pd.read_json('../json/heroes.json')
cluster_regions = pd.read_csv('./Data/cluster_regions.csv')
matches
players.head()
hero_names.head() | _____no_output_____ | MIT | jupyter notebook/Dota2 new data.ipynb | alykkehoy/Dota-2-winning-team-predictor |
Data info Hero InfoMost and least popular heroes | num_heroes = len(hero_names)
plt.hist(players['hero_id'], num_heroes)
plt.show()
hero_counts = players['hero_id'].value_counts().rename_axis('hero_id').reset_index(name='num_matches')
pd.merge(hero_counts, hero_names, left_on='hero_id', right_on='id') | _____no_output_____ | MIT | jupyter notebook/Dota2 new data.ipynb | alykkehoy/Dota-2-winning-team-predictor |
Server InfoWhere the most and least games are played | plt.hist(matches['cluster'], bins=np.arange(matches['cluster'].min(), matches['cluster'].max()+1))
plt.show()
cluster_counts = matches['cluster'].value_counts().rename_axis('cluster').reset_index(name='num_matches')
pd.merge(cluster_counts, cluster_regions, on='cluster')
short_players = players.iloc[:, :11]
short_players.insert(short_players.shape[1], 'win', value=False)
short_players
# short_matches = matches.iloc[:1000]
for index, row in matches.iterrows():
offset = 10 * index
short_players.at[0 + offset, 'win'] = row.radiant_win
short_players.at[1 + offset, 'win'] = row.radiant_win
short_players.at[2 + offset, 'win'] = row.radiant_win
short_players.at[3 + offset, 'win'] = row.radiant_win
short_players.at[4 + offset, 'win'] = row.radiant_win
short_players.at[5 + offset, 'win'] = not row.radiant_win
short_players.at[6 + offset, 'win'] = not row.radiant_win
short_players.at[7 + offset, 'win'] = not row.radiant_win
short_players.at[8 + offset, 'win'] = not row.radiant_win
short_players.at[9 + offset, 'win'] = not row.radiant_win
# print(index)
short_players.head(20)
short_players.tail()
hero_match_wins = short_players.groupby(by='hero_id').sum()['win']
hero_match_count = players['hero_id'].value_counts().rename_axis('hero_id').reset_index(name='total_matches')
hero_match_count = hero_match_count.merge(hero_match_wins, on='hero_id')
hero_match_count
hero_match_count['win_percent'] = hero_match_count['win'] / hero_match_count['total_matches'] * 100
hero_match_count
hero_match_count = pd.merge(hero_match_count, hero_names, left_on='hero_id', right_on='id')
hero_match_count
fig_size = plt.rcParams["figure.figsize"]
fig_size[0] = 10
fig_size[1] = 8
plt.rcParams["figure.figsize"] = fig_size
x = hero_match_count['total_matches']
y = hero_match_count['win_percent']
labels = hero_match_count['localized_name']
plt.scatter(x, y)
plt.title('Win Percent vs Number of Games Played', fontsize=18)
plt.xlabel('Number of Games Played', fontsize=18)
plt.ylabel('Percent Won', fontsize=18)
for i, label in enumerate(labels):
plt.annotate(label, (x[i], y[i])) | _____no_output_____ | MIT | jupyter notebook/Dota2 new data.ipynb | alykkehoy/Dota-2-winning-team-predictor |
Data cleaningWe start with an empty list of DataFrams and add to it as we create DataFrames of bad match ids. In the end we combine all the DataFrames and remove their match ids from the Matches DataFrame. | dfs_bad_matches = [] | _____no_output_____ | MIT | jupyter notebook/Dota2 new data.ipynb | alykkehoy/Dota-2-winning-team-predictor |
Abandonsremove games were a player has abandoned the match | abandoned_matches = players[players.leaver_status > 1][['match_id']]
abandoned_matches = abandoned_matches.drop_duplicates().reset_index(drop=True)
dfs_bad_matches.append(abandoned_matches)
abandoned_matches | _____no_output_____ | MIT | jupyter notebook/Dota2 new data.ipynb | alykkehoy/Dota-2-winning-team-predictor |
Missing Hero idremove games where a player is not assigned a hero id, but didnt get flaged for an abandon | player_no_hero = players[players.hero_id == 0][['match_id']].reset_index(drop=True)
dfs_bad_matches.append(player_no_hero)
player_no_hero | _____no_output_____ | MIT | jupyter notebook/Dota2 new data.ipynb | alykkehoy/Dota-2-winning-team-predictor |
Wrong Game Moderemove games not played in "Ranked All Pick" (22) | wrong_mode = matches[matches.game_mode != 22].reset_index()[['match_id']]
dfs_bad_matches.append(wrong_mode)
wrong_mode | _____no_output_____ | MIT | jupyter notebook/Dota2 new data.ipynb | alykkehoy/Dota-2-winning-team-predictor |
Game length (short)remove games we deem too short (< 15 min) | short_length = 15 * 60
short_matches = matches[matches.duration < short_length].reset_index()[['match_id']]
dfs_bad_matches.append(short_matches)
short_matches | _____no_output_____ | MIT | jupyter notebook/Dota2 new data.ipynb | alykkehoy/Dota-2-winning-team-predictor |
Game length (long)Next we want to get matches with a too long duration (>90 min) | long_length = 90 * 60
long_matches = matches[matches.duration > long_length].reset_index()[['match_id']]
dfs_bad_matches.append(long_matches)
long_matches | _____no_output_____ | MIT | jupyter notebook/Dota2 new data.ipynb | alykkehoy/Dota-2-winning-team-predictor |
Combine all our lists of bad matchescombine matches and create a filtered match dataframe with only good matches | bad_match_ids = pd.concat(dfs_bad_matches, ignore_index=True).drop_duplicates()
bad_match_ids | _____no_output_____ | MIT | jupyter notebook/Dota2 new data.ipynb | alykkehoy/Dota-2-winning-team-predictor |
Remove bad matches | filtered_matches = matches[~matches['match_id'].isin(bad_match_ids['match_id'])]
filtered_matches.info() | <class 'pandas.core.frame.DataFrame'>
Int64Index: 115823 entries, 0 to 145324
Data columns (total 22 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 radiant_win 115823 non-null bool
1 duration 115823 non-null int64
2 pre_game_duration 115823 non-null int64
3 start_time 115823 non-null int64
4 match_id 115823 non-null int64
5 match_seq_num 115823 non-null int64
6 tower_status_radiant 115823 non-null int64
7 tower_status_dire 115823 non-null int64
8 barracks_status_radiant 115823 non-null int64
9 barracks_status_dire 115823 non-null int64
10 cluster 115823 non-null int64
11 first_blood_time 115823 non-null int64
12 lobby_type 115823 non-null int64
13 human_players 115823 non-null int64
14 leagueid 115823 non-null int64
15 positive_votes 115823 non-null int64
16 negative_votes 115823 non-null int64
17 game_mode 115823 non-null int64
18 flags 115823 non-null int64
19 engine 115823 non-null int64
20 radiant_score 115823 non-null int64
21 dire_score 115823 non-null int64
dtypes: bool(1), int64(21)
memory usage: 19.6 MB
| MIT | jupyter notebook/Dota2 new data.ipynb | alykkehoy/Dota-2-winning-team-predictor |
Remove duplicate matches | filtered_matches = filtered_matches.drop_duplicates(subset=['match_id'])
filtered_matches.info()
filtered_players = players[~players['match_id'].isin(bad_match_ids['match_id'])]
filtered_players.info()
filtered_players = filtered_players.drop_duplicates(subset=['match_id', 'player_slot'])
filtered_players.info()
filtered_players.to_csv('../csv/players_filtered.csv', index=False)
filtered_matches.to_csv('../csv/matches_filtered.csv', index=False) | _____no_output_____ | MIT | jupyter notebook/Dota2 new data.ipynb | alykkehoy/Dota-2-winning-team-predictor |
Convert our match listConvert our match list to the form of :r_1, r_2, r_3, r_4, r_5, d_1, d_2, d_3, d_4, d_5, r_win | r_names = []
d_names = []
for slot in range(1, 6):
r_name = 'r_' + str(slot)
d_name = 'd_' + str(slot)
r_names.append(r_name)
d_names.append(d_name)
columns = (r_names + d_names + ['r_win'])
new_row = [-1] * (5 + 5 + 1)
# test_players = players.iloc[:500, :]
# test_matches = matches.iloc[:50, :]
columns = (r_names + d_names + ['r_win'])
new_match_list = pd.DataFrame(data=None, columns=columns)
output = StringIO()
csv_writer = writer(output)
for index, row in filtered_matches.iterrows():
match_players = players.loc[players['match_id'] == row['match_id']]
if match_players.shape[0] == 10:
new_row[0] = match_players[match_players['player_slot'] == 0].iloc[0]['hero_id']
new_row[1] = match_players[match_players['player_slot'] == 1].iloc[0]['hero_id']
new_row[2] = match_players[match_players['player_slot'] == 2].iloc[0]['hero_id']
new_row[3] = match_players[match_players['player_slot'] == 3].iloc[0]['hero_id']
new_row[4] = match_players[match_players['player_slot'] == 4].iloc[0]['hero_id']
new_row[5] = match_players[match_players['player_slot'] == 128].iloc[0]['hero_id']
new_row[6] = match_players[match_players['player_slot'] == 129].iloc[0]['hero_id']
new_row[7] = match_players[match_players['player_slot'] == 130].iloc[0]['hero_id']
new_row[8] = match_players[match_players['player_slot'] == 131].iloc[0]['hero_id']
new_row[9] = match_players[match_players['player_slot'] == 132].iloc[0]['hero_id']
# add if radiant win
new_row[10] = row['radiant_win']
# append new row onto match list
csv_writer.writerow(new_row)
# gives us some idea about how far into the data we are
if index % 1000 == 0:
print(index / 1000)
output.seek(0)
new_match_list = pd.read_csv(output, names=columns)
new_match_list.to_csv('./Data_new/new_match_list_filtered_ids.csv', index=False) | _____no_output_____ | MIT | jupyter notebook/Dota2 new data.ipynb | alykkehoy/Dota-2-winning-team-predictor |
Stats | players
player_stats = players.drop(columns=['account_id', 'match_id', 'leaver_status'])
player_stats_short = player_stats.drop(columns=['item_0','item_1','item_2','item_3','item_4','item_5','backpack_0','backpack_1','backpack_2','item_neutral', 'player_slot']).groupby(['hero_id']).mean()
player_stats_short
player_stats_short.reset_index().to_json('../json/hero_stats.json', orient='records', indent=4)
player_items = player_stats.melt(id_vars=['hero_id'], value_vars=['item_0', 'item_1', 'item_2', 'item_3', 'item_4', 'item_5'], var_name='item_slot', value_name='item_id')
player_items
item_counts = player_items.groupby(['hero_id']).item_id.value_counts().reset_index(name="count")
item_counts
j = (item_counts.groupby(['hero_id'], as_index=True)
.apply(lambda x: x[['item_id','count']].to_dict('r'))
.reset_index()
.rename(columns={0:'item_data'})
.to_json('../json/item_stats.json', orient='records', indent=4)) | _____no_output_____ | MIT | jupyter notebook/Dota2 new data.ipynb | alykkehoy/Dota-2-winning-team-predictor |
K-NN regression 알고리즘 | from sklearn.neighbors import KNeighborsRegressor
regressor = KNeighborsRegressor(n_neighbors = 10, weights = "distance")
regressor.fit(X_train.drop(columns='player_name'), y_train)
y_pred = regressor.predict(X_test.drop(columns='player_name'))
y_pred_train = regressor.predict(X_train.drop(columns='player_name'))
result = []
for i in range(len(y_pred)):
if y_test[i] < y_pred[i]:
result.append("overpaid")
else:
result.append("underpaid")
result
len(y_pred)
# X_train = X_train.reset_index().drop(columns='index')
X_test = X_test.reset_index().drop(columns='index')
X_train
X_test
X_test.loc[1]['player_name']
underpaid = []
for i in range(len(y_pred)):
if result[i] == 'underpaid':
underpaid.append(X_test.loc[i]['player_name'])
len(underpaid)
underpaid | _____no_output_____ | MIT | 0.Project/3. Machine Learning Practice/2. Football/2. K-NN Regression parctice.ipynb | jskim0406/Study |
K-NN regression 알고리즘 -> 전체를 다 학습시킴.. | from sklearn.neighbors import KNeighborsRegressor
regressor = KNeighborsRegressor(n_neighbors = 10, weights = "distance")
regressor.fit(data.drop(columns=['player_name','value']), data.value)
y_pred = regressor.predict(data.drop(columns=['player_name','value']))
result = []
for i in range(len(y_pred)):
if data.value[i] < y_pred[i]:
result.append("underpaid")
else:
result.append("overpaid")
data.value[1]
y_pred[1]
result
len(y_pred)
# X_train = X_train.reset_index().drop(columns='index')
X_test = X_test.reset_index().drop(columns='index')
X_train
X_test
X_test.loc[1]['player_name']
underpaid = []
for i in range(len(y_pred)):
if result[i] == 'underpaid':
underpaid.append(X_test.loc[i]['player_name'])
len(underpaid)
X_test | _____no_output_____ | MIT | 0.Project/3. Machine Learning Practice/2. Football/2. K-NN Regression parctice.ipynb | jskim0406/Study |
Lambda School Data Science*Unit 2, Sprint 3, Module 1*--- Define ML problemsYou will use your portfolio project dataset for all assignments this sprint. AssignmentComplete these tasks for your project, and document your decisions.- [x] Choose your target. Which column in your tabular dataset will you predict?- [x] Is your problem regression or classification?- [x] How is your target distributed? - Classification: How many classes? Are the classes imbalanced? - Regression: Is the target right-skewed? If so, you may want to log transform the target.- [x] Choose which observations you will use to train, validate, and test your model. - Are some observations outliers? Will you exclude them? - Will you do a random split or a time-based split?- [x] Choose your evaluation metric(s). - Classification: Is your majority class frequency > 50% and < 70% ? If so, you can just use accuracy if you want. Outside that range, accuracy could be misleading. What evaluation metric will you choose, in addition to or instead of accuracy?- [ ] Begin to clean and explore your data.- [ ] Begin to choose which features, if any, to exclude. Would some features "leak" future information? | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
url = 'https://raw.githubusercontent.com/Skantastico/DS-Unit-2-Applied-Modeling/master/data/Anime.csv'
df = pd.read_csv(url) | _____no_output_____ | MIT | LS_DSPT3_231_Updated_assignment_applied_modeling_1.ipynb | Skantastico/DS-Unit-2-Applied-Modeling |
My DatasetAnime Ratings from the 'iMDB" of Anime, called myanimelist.net | df.head(7) | _____no_output_____ | MIT | LS_DSPT3_231_Updated_assignment_applied_modeling_1.ipynb | Skantastico/DS-Unit-2-Applied-Modeling |
Summary of numeric and non-numeric columns at a glance | df.describe().T
df.describe(exclude='number').T
col_list = df.columns.values.tolist()
col_list | _____no_output_____ | MIT | LS_DSPT3_231_Updated_assignment_applied_modeling_1.ipynb | Skantastico/DS-Unit-2-Applied-Modeling |
I was running into trouble during data exploration, there seems to be a space after every column | ## I found this piece of code on medium that seems like a catch-all for fixing columns
df.columns = df.columns.str.strip().str.lower().str.replace(' ', '_').str.replace('(', '').str.replace(')', '')
df
col_list = df.columns.values.tolist()
col_list
df.columns
df.columns.map(lambda x: x.strip())
df.columns
df.genre.value_counts() | _____no_output_____ | MIT | LS_DSPT3_231_Updated_assignment_applied_modeling_1.ipynb | Skantastico/DS-Unit-2-Applied-Modeling |
Ok that seems to have fixed it.There seem to be at least around 900 'adult themed' anime which I will probably remove from the dataset, or at least from any public portions just to be safe.If it affects the model accuracy at all or is relevant, I will include it for calculations and just make a note. Choose Your Target | # My Target will be involving the 'score' column
df.score.value_counts(ascending=False) | _____no_output_____ | MIT | LS_DSPT3_231_Updated_assignment_applied_modeling_1.ipynb | Skantastico/DS-Unit-2-Applied-Modeling |
As I will be using the entire spectrum of score, this will be a regression. How is my target distributed? | # The mean seems to be around 6.3, with only 25% of the dataset above a 7.05
df.score.describe()
df['mean'] = df['score'] >= 6.2845
df['mean'].value_counts(normalize=True) | _____no_output_____ | MIT | LS_DSPT3_231_Updated_assignment_applied_modeling_1.ipynb | Skantastico/DS-Unit-2-Applied-Modeling |
So there are about 51% anime that are above average (before cleaning) Which Observations will I use to train? There's lots of options, but at the very least these look interesting:Numeric:* Episodes* Airing*Aired*Duration*Score*Popularity*RankNon-numeric:* Type*Source*Producer*Genre*Studio*Rating On my old dataset, it was a lot less complete than this one, and I was already thinking of making my own features similar to "popularity" and " of episodes". I was also going to try and figure out how to scrape and match air dates, but someone other magical person already has! Hooray. I will continue to clean the dataset on a new notebook | _____no_output_____ | MIT | LS_DSPT3_231_Updated_assignment_applied_modeling_1.ipynb | Skantastico/DS-Unit-2-Applied-Modeling |
|
Day 5: Optimal Mind ControlWelcome to Day 6! Now that we can simulate a model network of conductance-based neurons, we discuss the limitations of our approach and attempts to work around these issues. Memory ManagementUsing Python and TensorFlow allowed us to write code that is readable, parallizable and scalable across a variety of computational devices. However, our implementation is very memory intensive. The iterators in TensorFlow do not follow the normal process of memory allocation and garbage collection. Since, TensorFlow is designed to work on diverse hardware like GPUs, TPUs and distributed platforms, memory allocation is done adaptively during the TensorFlow session and not cleared until the Python kernel has stopped execution. The memory used increases linearly with time as the state matrix is computed recursively by the tf.scan function. The maximum memory used by the computational graph is 2 times the total state matrix size at the point when the computation finishes and copies the final data into the memory. The larger the network and longer the simulation, the larger the solution matrix. Each run is limited by the total available memory. For a system with a limited memory of K bytes, The length of a given simulation (L timesteps) of a given network (N differential equations) with 64-bit floating-point precision will follow:$$2\times64\times L\times N=K$$ That is, for any given network, our maximum simulation length is limited. One way to improve our maximum length is to divide the simulation into smaller batches. There will be a small queuing time between batches, which will slow down our code by a small amount but we will be able to simulate longer times. Thus, if we split the simulation into K sequential batches, the maximum memory for the simulation becomes $(1+\frac{1}{K})$ times the total matrix size. Thus the memory relation becomes: $$\Big(1+\frac{1}{K}\Big)\times64\times L\times N=K$$ This way, we can maximize the length of out simulation that we can run in a single python kernel.Let us implement this batch system for our 3 neuron feed-forward model. Implementing the ModelTo improve the readability of our code we separate the integrator into a independent import module. The integrator code was placed in a file called tf integrator.py. The file must be present in the same directory as the implementation of the model.Note: If you are using Jupyter Notebook, remember to remove the %matplotlib inline command as it is specific to jupyter. Importing tf_integrator and other requirementsOnce the Integrator is saved in tf_integrator.py in the same directory as the Notebook, we can start importing the essentials including the integrator. | import numpy as np
import tf_integrator as tf_int
import matplotlib.pyplot as plt
import seaborn as sns
import tensorflow as tf
## OR ##
# import tensorflow.compat.v1 as tf
# tf.disable_v2_behavior() | _____no_output_____ | MIT | Tutorial/Supplementary: Jupyter Notebooks/Day 5: Optimal Mind Control/.ipynb_checkpoints/Day 5-checkpoint.ipynb | matpalm/PSST |
Recall the ModelFor implementing a Batch system, we do not need to change how we construct our model only how we execute it. Step 1: Initialize Parameters and Dynamical Equations; Define Input | n_n = 3 # number of simultaneous neurons to simulate
sim_res = 0.01 # Time Resolution of the Simulation
sim_time = 700 # Length of the Simulation
t = np.arange(0,sim_time,sim_res)
# Acetylcholine
ach_mat = np.zeros((n_n,n_n)) # Ach Synapse Connectivity Matrix
ach_mat[1,0]=1
## PARAMETERS FOR ACETYLCHLOLINE SYNAPSES ##
n_ach = int(np.sum(ach_mat)) # Number of Acetylcholine (Ach) Synapses
alp_ach = [10.0]*n_ach # Alpha for Ach Synapse
bet_ach = [0.2]*n_ach # Beta for Ach Synapse
t_max = 0.3 # Maximum Time for Synapse
t_delay = 0 # Axonal Transmission Delay
A = [0.5]*n_n # Synaptic Response Strength
g_ach = [0.35]*n_n # Ach Conductance
E_ach = [0.0]*n_n # Ach Potential
# GABAa
gaba_mat = np.zeros((n_n,n_n)) # GABAa Synapse Connectivity Matrix
gaba_mat[2,1] = 1
## PARAMETERS FOR GABAa SYNAPSES ##
n_gaba = int(np.sum(gaba_mat)) # Number of GABAa Synapses
alp_gaba = [10.0]*n_gaba # Alpha for GABAa Synapse
bet_gaba = [0.16]*n_gaba # Beta for GABAa Synapse
V0 = [-20.0]*n_n # Decay Potential
sigma = [1.5]*n_n # Decay Time Constant
g_gaba = [0.8]*n_n # fGABA Conductance
E_gaba = [-70.0]*n_n # fGABA Potential
## Storing Firing Thresholds ##
F_b = [0.0]*n_n # Fire threshold
def I_inj_t(t):
return tf.constant(current_input.T,dtype=tf.float64)[tf.to_int32(t/sim_res)] # Turn indices to integer and extract from matrix
## Acetylcholine Synaptic Current ##
def I_ach(o,V):
o_ = tf.Variable([0.0]*n_n**2,dtype=tf.float64)
ind = tf.boolean_mask(tf.range(n_n**2),ach_mat.reshape(-1) == 1)
o_ = tf.scatter_update(o_,ind,o)
o_ = tf.transpose(tf.reshape(o_,(n_n,n_n)))
return tf.reduce_sum(tf.transpose((o_*(V-E_ach))*g_ach),1)
## GABAa Synaptic Current ##
def I_gaba(o,V):
o_ = tf.Variable([0.0]*n_n**2,dtype=tf.float64)
ind = tf.boolean_mask(tf.range(n_n**2),gaba_mat.reshape(-1) == 1)
o_ = tf.scatter_update(o_,ind,o)
o_ = tf.transpose(tf.reshape(o_,(n_n,n_n)))
return tf.reduce_sum(tf.transpose((o_*(V-E_gaba))*g_gaba),1)
## Other Currents ##
def I_K(V, n):
return g_K * n**4 * (V - E_K)
def I_Na(V, m, h):
return g_Na * m**3 * h * (V - E_Na)
def I_L(V):
return g_L * (V - E_L)
def dXdt(X, t):
V = X[:1*n_n] # First n_n values are Membrane Voltage
m = X[1*n_n:2*n_n] # Next n_n values are Sodium Activation Gating Variables
h = X[2*n_n:3*n_n] # Next n_n values are Sodium Inactivation Gating Variables
n = X[3*n_n:4*n_n] # Next n_n values are Potassium Gating Variables
o_ach = X[4*n_n : 4*n_n + n_ach] # Next n_ach values are Acetylcholine Synapse Open Fractions
o_gaba = X[4*n_n + n_ach : 4*n_n + n_ach + n_gaba] # Next n_ach values are GABAa Synapse Open Fractions
fire_t = X[-n_n:] # Last n_n values are the last fire times as updated by the modified integrator
dVdt = (I_inj_t(t) - I_Na(V, m, h) - I_K(V, n) - I_L(V) - I_ach(o_ach,V) - I_gaba(o_gaba,V)) / C_m
## Updation for gating variables ##
m0,tm,h0,th = Na_prop(V)
n0,tn = K_prop(V)
dmdt = - (1.0/tm)*(m-m0)
dhdt = - (1.0/th)*(h-h0)
dndt = - (1.0/tn)*(n-n0)
## Updation for o_ach ##
A_ = tf.constant(A,dtype=tf.float64)
Z_ = tf.zeros(tf.shape(A_),dtype=tf.float64)
T_ach = tf.where(tf.logical_and(tf.greater(t,fire_t+t_delay),tf.less(t,fire_t+t_max+t_delay)),A_,Z_)
T_ach = tf.multiply(tf.constant(ach_mat,dtype=tf.float64),T_ach)
T_ach = tf.boolean_mask(tf.reshape(T_ach,(-1,)),ach_mat.reshape(-1) == 1)
do_achdt = alp_ach*(1.0-o_ach)*T_ach - bet_ach*o_ach
## Updation for o_gaba ##
T_gaba = 1.0/(1.0+tf.exp(-(V-V0)/sigma))
T_gaba = tf.multiply(tf.constant(gaba_mat,dtype=tf.float64),T_gaba)
T_gaba = tf.boolean_mask(tf.reshape(T_gaba,(-1,)),gaba_mat.reshape(-1) == 1)
do_gabadt = alp_gaba*(1.0-o_gaba)*T_gaba - bet_gaba*o_gaba
## Updation for fire times ##
dfdt = tf.zeros(tf.shape(fire_t),dtype=fire_t.dtype) # zero change in fire_t
out = tf.concat([dVdt,dmdt,dhdt,dndt,do_achdt,do_gabadt,dfdt],0)
return out
def K_prop(V):
T = 22
phi = 3.0**((T-36.0)/10)
V_ = V-(-50)
alpha_n = 0.02*(15.0 - V_)/(tf.exp((15.0 - V_)/5.0) - 1.0)
beta_n = 0.5*tf.exp((10.0 - V_)/40.0)
t_n = 1.0/((alpha_n+beta_n)*phi)
n_0 = alpha_n/(alpha_n+beta_n)
return n_0, t_n
def Na_prop(V):
T = 22
phi = 3.0**((T-36)/10)
V_ = V-(-50)
alpha_m = 0.32*(13.0 - V_)/(tf.exp((13.0 - V_)/4.0) - 1.0)
beta_m = 0.28*(V_ - 40.0)/(tf.exp((V_ - 40.0)/5.0) - 1.0)
alpha_h = 0.128*tf.exp((17.0 - V_)/18.0)
beta_h = 4.0/(tf.exp((40.0 - V_)/5.0) + 1.0)
t_m = 1.0/((alpha_m+beta_m)*phi)
t_h = 1.0/((alpha_h+beta_h)*phi)
m_0 = alpha_m/(alpha_m+beta_m)
h_0 = alpha_h/(alpha_h+beta_h)
return m_0, t_m, h_0, t_h
# Initializing the Parameters
C_m = [1.0]*n_n
g_K = [10.0]*n_n
E_K = [-95.0]*n_n
g_Na = [100]*n_n
E_Na = [50]*n_n
g_L = [0.15]*n_n
E_L = [-55.0]*n_n
# Creating the Current Input
current_input= np.zeros((n_n,t.shape[0]))
current_input[0,int(100/sim_res):int(200/sim_res)] = 2.5
current_input[0,int(300/sim_res):int(400/sim_res)] = 5.0
current_input[0,int(500/sim_res):int(600/sim_res)] = 7.5 | _____no_output_____ | MIT | Tutorial/Supplementary: Jupyter Notebooks/Day 5: Optimal Mind Control/.ipynb_checkpoints/Day 5-checkpoint.ipynb | matpalm/PSST |
Step 2: Define the Initial Condition of the Network and Add some Noise to the initial conditions | # Initializing the State Vector and adding 1% noise
state_vector = [-71]*n_n+[0,0,0]*n_n+[0]*n_ach+[0]*n_gaba+[-9999999]*n_n
state_vector = np.array(state_vector)
state_vector = state_vector + 0.01*state_vector*np.random.normal(size=state_vector.shape) | _____no_output_____ | MIT | Tutorial/Supplementary: Jupyter Notebooks/Day 5: Optimal Mind Control/.ipynb_checkpoints/Day 5-checkpoint.ipynb | matpalm/PSST |
Step 3: Splitting Time Series into independent batches and Run Each Batch SequentiallySince we will be dividing the computation into batches, we have to split the time array such that for each new call, the final state vector of the last batch will be the initial condition for the current batch. The function $np.array\_split()$ splits the array into non-overlapping vectors. Therefore, we append the last time of the previous batch to the beginning of the current time array batch. | # Define the Number of Batches
n_batch = 2
# Split t array into batches using numpy
t_batch = np.array_split(t,n_batch)
# Iterate over the batches of time array
for n,i in enumerate(t_batch):
# Inform start of Batch Computation
print("Batch",(n+1),"Running...",end="")
# In np.array_split(), the split edges are present in only one array and since
# our initial vector to successive calls is corresposnding to the last output
# our first element in the later time array should be the last element of the
# previous output series, Thus, we append the last time to the beginning of
# the current time array batch.
if n>0:
i = np.append(i[0]-sim_res,i)
# Set state_vector as the initial condition
init_state = tf.constant(state_vector, dtype=tf.float64)
# Create the Integrator computation graph over the current batch of t array
tensor_state = tf_int.odeint(dXdt, init_state, i, n_n, F_b)
# Initialize variables and run session
with tf.Session() as sess:
tf.global_variables_initializer().run()
state = sess.run(tensor_state)
sess.close()
# Reset state_vector as the last element of output
state_vector = state[-1,:]
# Save the output of the simulation to a binary file
np.save("part_"+str(n+1),state)
# Clear output
state=None
print("Finished") | Batch 1 Running...Finished
Batch 2 Running...Finished
| MIT | Tutorial/Supplementary: Jupyter Notebooks/Day 5: Optimal Mind Control/.ipynb_checkpoints/Day 5-checkpoint.ipynb | matpalm/PSST |
Putting the Output TogetherThe output from our batch implementation is a set of binary files that store parts of our total simulation. To get the overall output we have to stitch them back together. | overall_state = []
# Iterate over the generated output files
for n,i in enumerate(["part_"+str(n+1)+".npy" for n in range(n_batch)]):
# Since the first element in the series was the last output, we remove them
if n>0:
overall_state.append(np.load(i)[1:,:])
else:
overall_state.append(np.load(i))
# Concatenate all the matrix to get a single state matrix
overall_state = np.concatenate(overall_state) | _____no_output_____ | MIT | Tutorial/Supplementary: Jupyter Notebooks/Day 5: Optimal Mind Control/.ipynb_checkpoints/Day 5-checkpoint.ipynb | matpalm/PSST |
Visualizing the Overall DataFinally, we plot the voltage traces of the 3 neurons as a Voltage vs Time heatmap. | plt.figure(figsize=(12,6))
sns.heatmap(overall_state[::100,:3].T,xticklabels=100,yticklabels=5,cmap='RdBu_r')
plt.xlabel("Time (in ms)")
plt.ylabel("Neuron Number")
plt.title("Voltage vs Time Heatmap for Projection Neurons (PNs)")
plt.tight_layout()
plt.show() | _____no_output_____ | MIT | Tutorial/Supplementary: Jupyter Notebooks/Day 5: Optimal Mind Control/.ipynb_checkpoints/Day 5-checkpoint.ipynb | matpalm/PSST |
By this method, we have maximized the usage of our available memory but we can go further and develop a method to allow indefinitely long simulation. The issue behind this entire algorithm is that the memory is not cleared until the python kernel finishes. One way to overcome this is to save the parameters of the model (such as connectivity matrix) and the state vector in a file, and start a new python kernel from a python script to compute successive batches. This way after each large batch, the memory gets cleaned. By combining the previous batch implementation and this system, we can maximize our computability. Implementing a Runner and a CallerFirstly, we have to create an implementation of the model that takes in previous input as current parameters. Thus, we create a file, which we call "run.py" that takes an argument ie. the current batch number. The implementation for "run.py" is mostly same as the above model but there is a small difference.When the batch number is 0, we initialize all variable parameters and save them, but otherwise we use the saved values. The parameters we save include: Acetylcholine Matrix, GABAa Matrix and Final/Initial State Vector. It will also save the files with both batch number and sub-batch number listed.The time series will be created and split initially by the caller, which we call "call.py", and stored in a file. Each execution of the Runner will extract its relevant time series and compute on it. Implementing the Caller codeThe caller will create the time series, split it and use python subprocess module to call "run.py" with appropriate arguments. The code for "call.py" is given below. | from subprocess import call
import numpy as np
total_time = 700
n_splits = 2
time = np.split(np.arange(0,total_time,0.01),n_splits)
# Append the last time point to the beginning of the next batch
for n,i in enumerate(time):
if n>0:
time[n] = np.append(i[0]-0.01,i)
np.save("time",time)
# call successive batches with a new python subprocess and pass the batch number
for i in range(n_splits):
call(['python','run.py',str(i)])
print("Simulation Completed.") | _____no_output_____ | MIT | Tutorial/Supplementary: Jupyter Notebooks/Day 5: Optimal Mind Control/.ipynb_checkpoints/Day 5-checkpoint.ipynb | matpalm/PSST |
Implementing the Runner code"run.py" is essentially identical to the batch-implemented model we developed above with the changes described below: | # Additional Imports #
import sys
# Duration of Simulation #
# t = np.arange(0,sim_time,sim_res)
t = np.load("time.npy")[int(sys.argv[1])] # get first argument to run.py
# Connectivity Matrix Definitions #
if sys.argv[1] == '0':
ach_mat = np.zeros((n_n,n_n)) # Ach Synapse Connectivity Matrix
ach_mat[1,0]=1 # If connectivity is random, once initialized it will be the same.
np.save("ach_mat",ach_mat)
else:
ach_mat = np.load("ach_mat.npy")
if sys.argv[1] == '0':
gaba_mat = np.zeros((n_n,n_n)) # GABAa Synapse Connectivity Matrix
gaba_mat[2,1] = 1 # If connectivity is random, once initialized it will be the same.
np.save("gaba_mat",gaba_mat)
else:
gaba_mat = np.load("gaba_mat.npy")
# Current Input Definition #
if sys.argv[1] == '0':
current_input= np.zeros((n_n,int(sim_time/sim_res)))
current_input[0,int(100/sim_res):int(200/sim_res)] = 2.5
current_input[0,int(300/sim_res):int(400/sim_res)] = 5.0
current_input[0,int(500/sim_res):int(600/sim_res)] = 7.5
np.save("current_input",current_input)
else:
current_input = np.load("current_input.npy")
# State Vector Definition #
if sys.argv[1] == '0':
sstate_vector = [-71]*n_n+[0,0,0]*n_n+[0]*n_ach+[0]*n_gaba+[-9999999]*n_n
state_vector = np.array(state_vector)
state_vector = state_vector + 0.01*state_vector*np.random.normal(size=state_vector.shape)
np.save("state_vector",state_vector)
else:
state_vector = np.load("state_vector.npy")
# Saving of Output #
# np.save("part_"+str(n+1),state)
np.save("batch"+str(int(sys.argv[1])+1)+"_part_"+str(n+1),state) | _____no_output_____ | MIT | Tutorial/Supplementary: Jupyter Notebooks/Day 5: Optimal Mind Control/.ipynb_checkpoints/Day 5-checkpoint.ipynb | matpalm/PSST |
Combining all DataJust like we merged all the batches, we merge all the sub-batches and batches. | overall_state = []
# Iterate over the generated output files
for n,i in enumerate(["batch"+str(x+1) for x in range(n_splits)]):
for m,j in enumerate(["_part_"+str(x+1)+".npy" for x in range(n_batch)]):
# Since the first element in the series was the last output, we remove them
if n>0 and m>0:
overall_state.append(np.load(i+j)[1:,:])
else:
overall_state.append(np.load(i+j))
# Concatenate all the matrix to get a single state matrix
overall_state = np.concatenate(overall_state)
plt.figure(figsize=(12,6))
sns.heatmap(overall_state[::100,:3].T,xticklabels=100,yticklabels=5,cmap='RdBu_r')
plt.xlabel("Time (in ms)")
plt.ylabel("Neuron Number")
plt.title("Voltage vs Time Heatmap for Projection Neurons (PNs)")
plt.tight_layout()
plt.show() | _____no_output_____ | MIT | Tutorial/Supplementary: Jupyter Notebooks/Day 5: Optimal Mind Control/.ipynb_checkpoints/Day 5-checkpoint.ipynb | matpalm/PSST |
Using $L_0$ regularization in predicting genetic risk====================================The main aim of this document is to outline the code and theory of using the $L_0$ norm in a regularized regression with the objective to predict disease risk from genetic data.This document contains my thought process and understanding of the implementation of $L_0$.I will aim to integrate the code into existing tools so it can be easily used.Ideally I will also compare the performance again $L_1$ as well as $L_2$ norm (aka Lasso and Ridge regression) in predicting simulated data. Literature usedI made use of the following papers:- Learning Sparse Neural Networks through $L_0$ Regularization [link](http://arxiv.org/abs/1712.01312)- The Variational Garrote [link](http://link.springer.com/10.1007/s10994-013-5427-7) IntroductionLet $\mathcal{D}$ the dataset consisting of $N$ input-output pairs $\{(x_1, y_1), \ldots, (x_N, y_N)\}$ and consider the regularized minimization procedure with $L_p$ regularization of the parameters $\omega$$$\mathcal{R}(\theta) = \frac{1}{N} ( \sum^N_{i=1} \mathcal{L}(h(x_i; \theta), y_i)) + \lambda ||\theta||_p$$with $\theta^* = arg \min_{\theta}\{\mathcal{R}(\theta)\}$.While $L_1$ and $L_2$ are well defined the definition of $L_0$ varies.Hence I will define it as:$$||\theta||_0 = \sum^{|\theta|}_{j=1} I[\theta_j \neq 0]$$Here it is important that, in contrast to $L_1$ and $L_2$, the $L_0$ norm does not shrink the parameters value but sets it wither to 0 or not 0.This effect might be desirable in genetic data due to high correlations among SNPs. | import numpy as np
import matplotlib.pyplot as plt
plt.style.use('fivethirtyeight')
def l0(x):
return(np.sum(x!=0))
def l1(x):
return(np.sum(np.abs(x)))
def l2(x):
return(np.sum(np.power(x, 2)))
x = np.linspace(-2, 2, 50)
x = np.append(x, 0)
x = np.sort(x)
fig, (axs0, axs1, axs2) = plt.subplots(1, 3, sharex='all', sharey='all')
fig.set_size_inches((10, 3))
axs0.set_title('L0 norm')
axs1.set_title('L1 norm')
axs2.set_title('L2 norm')
[k.set_xlabel(r'$\theta$') for k in [axs0, axs1, axs2]]
[k.set_ylabel('Penalty') for k in [axs0, axs1, axs2]]
axs0.plot(x, [l0(k) for k in x])
axs1.plot(x, [l1(k) for k in x])
axs2.plot(x, [l2(k) for k in x]) | _____no_output_____ | MIT | notebooks/L0_norm.ipynb | rmporsch/ML_genetic_risk |
The plot above demonstrates nicely the penalty for different norms.As one can see both $p=1$ and $p=2$ allow shrinkage for large values of $\theta$, while $p=0$ the penalty is constant. Minimizing $L_0$ norm for parametric modelsOptimization under the $L_0$ penalty is computational difficult due to the non-differentiability as well as the comninatorial nature of $2^{|\theta|}$ (the number of possible states of the $L_0$ penalty function).Hence @Author relaxed the discrete nature of $L_0$ to allow for efficient computations.Here I will outline their approach first in order to understand it better.The first step is to reformulate the $L_0$ norm under the parameters $\theta$.Hence let,$$\begin{matrix}\theta_j = \tilde{\theta_j}z_j, & z_j \in \{0, 1\}, & \tilde{\theta}_j \neq 0, & ||\theta||_0 = \sum^{|\theta|}_{j=1} z_j\end{matrix}$$Therefore $z_j$ can be considered as binary gates, and the $L_0$ norm can be seen as the amount of gates being turned on.Then we can reformulate the minimization from Eq. 1 by letting $q(z_j|\pi_j) = Bern(\pi_j)$$$\mathcal{R}(\tilde{\theta}, \pi) = \mathbb{E}_{q(z|\pi)} [\frac{1}{N} ( \sum^N_{i=1} \mathcal{L}(h(x_i; \tilde{\theta} \otimes z), y_i)] + \lambda \sum^{|\theta|}_{j=1} \pi_j \\\quad \textrm{with} \quad \theta^*, \pi^* = arg \min_{\tilde{\theta}, \pi} \{\mathcal{R}(\tilde{\theta}, \pi)\}$$Here we encounter the problem of non-differentiability of the left hand side of the previous equation size z is discrete (the penalty term is straight forward to minimize).It seems there are methods to optimize this functions but they are supposed to suffer from high variance and biased gradients.Therefore @Author used an alternative to smooth the objective function for efficient gradient based optimization.Let $s$ be a continuous random variable with distribution $q(s)$ that has the parameter $\phi$ we can then let $z$ be given a hard sigmoid function:$$s \sim q(s|\phi) \\z = min(1, max(0, s))$$This allows the gate to still be $0$ as well as the computation of the probability of non-zero parameters (number of active gates) with a simple cdf ($Q(\cdot)$ of s:$$q(z\neq 0 | \phi) = 1 - Q(s \leq 0 | \phi)$$Then we can reformulate the previous equation as$$\mathcal{R}(\tilde{\theta}, \phi) = \mathbb{E}_{q(s|\phi)} [\frac{1}{N} ( \sum^N_{i=1} \mathcal{L}(h(x_i; \tilde{\theta} \otimes g(s)), y_i)] + \lambda \sum^{|\theta|}_{j=1} (1 - Q(s_j \leq 0 | \phi_j)) \\\quad \textrm{with} \quad \theta^*, \phi^* = arg \min_{\tilde{\theta}, \phi} \{\mathcal{R}(\tilde{\theta}, \phi)\},\quad g(\cdot) = min(1, max(0, \cdot))$$However, it is still necessary to define the distribution for $s$.Here it is suggested to use a hard concrete distribution. The hard concrete distributionLets assume that $s$ is a random variable distributed in the (0, 1) interval with probability density $q_s(s|\phi)$ and cdf $Q_s(s|\phi)$.The parameters of the distribution are $\phi = (\log \alpha, \beta)$, where $\log\alpha$ is the mean and $\beta$ the temperature (???).We can then stretch this distribution to the $(\gamma, \delta$) interval with $\gamma 1$:$$u\sim U(0, 1), \quads = Sigmoid((\log u - \log(1 - u) + \log\alpha) / \beta), \quad\bar{s} = s(\delta - \gamma) + \gamma, \quadz = \min(1, \max(0, \bar{s})$$Since these formulas are a bit difficult to visualize I have plotted them below to gain a better understanding of that they are doing and how these functions behave. | def hard_sigmoid(x):
return np.min([1, np.max([0, x])])
def sigmoid(x):
return 1 / (1 + np.exp(-x))
def hard_concrete_dist(loc, temp, gamma, zeta):
u = np.random.random()
s = sigmoid((np.log(u) - np.log(1 - u) + np.log(loc)) / temp)
shat = s*(zeta - gamma) + gamma
return hard_sigmoid(shat)
def plot_hard_concreate(loc, temp, gamma, zeta, num=10000, bins=100, **kwargs):
plt.hist([hard_concrete_dist(loc, temp, gamma, zeta) for _ in range(num)], bins=bins, density=True, **kwargs)
x = np.arange(-6, 6, 0.1)
y1 = sigmoid(x)
y2 = [hard_sigmoid(k) for k in x]
fig, axs = plt.subplots(1, 2)
fig.set_size_inches((10, 3))
axs[0].set_title('Comparision of Sigmoids')
axs[1].set_title('Hard Concreate Distribution')
axs[0].plot(x, y1, label='Sigmoid')
axs[0].plot(x, y2, label='Hard-Sigmoid')
handles, labels = axs[0].get_legend_handles_labels()
axs[0].legend(handles, labels)
values = [hard_concrete_dist(loc=1, temp=0.5, gamma=-0.1, zeta=1.1) for _ in range(1000)]
n, bins, patches = axs[1].hist(values, bins=100, density=True)
#fig.show()
fig, axs = plt.subplots()
fig.set_size_inches((10, 8))
axs.set_title('Comparision of Sigmoids')
axs.plot(x, y1, label='Sigmoid')
axs.plot(x, y2, label='Hard-Sigmoid')
handles, labels = axs.get_legend_handles_labels()
axs.legend(handles, labels)
fig, axs = plt.subplots()
fig.set_size_inches((10, 5))
axs.set_title('Hard Concreate Distribution')
values = [hard_concrete_dist(loc=1, temp=0.5, gamma=-0.1, zeta=1.1) for _ in range(5000)]
n, bins, patches = axs.hist(values, bins=100, density=True) | _____no_output_____ | MIT | notebooks/L0_norm.ipynb | rmporsch/ML_genetic_risk |
Implementation of the $L_0$ normThe next step is to implement the theory into practice.I will therefore make use of Google's tensorflow to implement the $L_0$ norm.Here its good to know that this has been implemented before in PyTorch.I will compare my and their implementation to assure I have done it correctly.The reason why I am not directly using PyTorch is that I don't want to learn yet again another library.Furthermore, implementing $L_0$ into tensorflow gives me hopefully a better understanding of the library itself as well as the $L_0$ norm.In addition, tensorflow can compute the derivatives for me, so I don't have to take care of this.The data I am going to use was simulated by Tim.This includes non-linear effects, binary and continous phenotypes.I will first compute only penalized linear models (that is $L_0$ to $L_2$ norm) with tensorflow and validate the results (of $L_1$ and $L_2$ with already implemented libraries (sklearn).The main objective is to improve prediction accuracy. | import tensorflow as tf
from sklearn.model_selection import train_test_split
from pyplink import PyPlink
import sys
import os
DATAFOLDER = os.path.realpath(filename='../data')
PLINKDATA = '1kgb'
FILEPATH = os.path.join(DATAFOLDER, PLINKDATA)
def count_lines(filepath, header=False):
"""Count the number of rows in a file"""
with open(filepath, 'r') as f:
count = sum(1 for line in f)
if header:
count -= 1
return count
print('Number of subjects:', count_lines(os.path.join(FILEPATH, '.fam'), True))
print('Number of SNPs:', count_lines(os.path.join(FILEPATH, '.bim'), False))
def get_matrix(pfile, max_block):
"""Extract a genotype matrix from plink file."""
with PyPlink(pfile) as bed:
bim = bed.get_bim()
fam = bed.get_fam()
n = fam.shape[0]
p = bim.shape[0]
assert(max_block <= p)
genotypemat = np.zeros((n, max_block), dtype=np.int64)
u = 0
for loci_name, genotypes in bed:
genotypemat[:, u] = np.array(genotypes)
u += 1
if u >= max_block:
break
return genotypemat
# define size of training, validation and testing data
sample_fractions = (0.8, 0.15, 0.05)
assert sum(sample_fractions) == 1.0
training_size, validation_size, testing_size = sample_fractions
data_training, data_testing, label_training, label_testing = train_test_split(pheno, genotypemat, train_size=training_size)
data_validataion, data_testing, label_validation, label_testing = train_test_split(data_testing, label_testing, train_size=2/3)
print("Samples in training:", len(label_training))
print("Samples in validation:", len(label_validation))
print("Samples in testing:", len(label_testing)) | _____no_output_____ | MIT | notebooks/L0_norm.ipynb | rmporsch/ML_genetic_risk |
Regular ExpressionsRegular expressions are `text matching patterns` described with a formal syntax. You'll often hear regular expressions referred to as 'regex' or 'regexp' in conversation. Regular expressions can include a variety of rules, for finding repetition, to text-matching, and much more. As you advance in Python you'll see that a lot of your parsing problems can be solved with regular expressions (they're also a common interview question!). Searching for Patterns in TextOne of the most common uses for the re module is for finding patterns in text. Let's do a quick example of using the search method in the re module to find some text: | import re
# List of patterns to search for
patterns = [ 'term1', 'term2' ]
# Text to parse
text = 'This is a string with term1, but it does not have the other term.'
for p in patterns:
print ('Searching for "%s" in Sentence: \n"%s"' % (p, text))
#Check for match
if re.search(p, text):
print ('Match was found. \n')
else:
print ('No Match was found. \n') | Searching for "term1" in Sentence:
"This is a string with term1, but it does not have the other term."
Match was found.
Searching for "term2" in Sentence:
"This is a string with term1, but it does not have the other term."
No Match was found.
| MIT | Regular Expression/PY0101EN-Regular Expressions.ipynb | reddyprasade/PYTHON-BASIC-FOR-ALL |
Now we've seen that re.search() will take the pattern, scan the text, and then returns a **Match** object. If no pattern is found, a **None** is returned. To give a clearer picture of this match object, check out the cell below: | # List of patterns to search for
pattern = 'term1'
# Text to parse
text = 'This is a string with term1, but it does not have the other term.'
match = re.search(pattern, text)
type(match)
match | _____no_output_____ | MIT | Regular Expression/PY0101EN-Regular Expressions.ipynb | reddyprasade/PYTHON-BASIC-FOR-ALL |
This **Match** object returned by the search() method is more than just a Boolean or None, it contains information about the match, including the original input string, the regular expression that was used, and the location of the match. Let's see the methods we can use on the match object: | # Show start of match
match.start()
# Show end
match.end()
s = "abassabacdReddyceaabadjfvababaReddy"
r = re.compile("Reddy")
r
l = re.findall(r,s)
print(l)
import re
s = "abcdefg1234"
r = re.compile("^[a-z][0-9]$")
l = re.findall(r,s)
print(l)
s = "ABCDE1234a"
r = re.compile(r"^[A-Z]{5}[0-9]{4}[a-z]$")
l = re.findall(r,s)
print(l)
s = "+917123456789"
s1 = "07123456789"
s2 = "7123456789"
r = re.compile(r"[6-9][0-9]{9}")
l = re.findall(r,s)
print(l)
l = re.findall(r,s1)
print(l)
l = re.findall(r,s2)
print(l)
s = "+917234567891"
s1 = "07123456789"
s2 = "7123456789"
r = re.compile(r"^(\+91)?[0]?([6-9][0-9]{9})$")
m = re.search(r,s1)
if m:
print(m.group())
else:
print("Invalid string")
for _ in range(int(input("No of Test Cases:"))):
line = input("Mobile Number")
if re.match(r"^[789]{1}\d{9}$", line):
print("YES")
else:
print("NO")
#Named groups
s = "12-02-2017" # DD-MM-YYYY
# dd-mm-yyyy
r = re.compile(r"^(?P<day>\d{2})-(?P<month>[0-9]{2})-(?P<year>[0-9]{4})")
m = re.search(r,s)
if m:
print(m.group('year'))
print(m.group('month'))
print(m.group('day')) | _____no_output_____ | MIT | Regular Expression/PY0101EN-Regular Expressions.ipynb | reddyprasade/PYTHON-BASIC-FOR-ALL |
Split with regular expressionsLet's see how we can split with the re syntax. This should look similar to how you used the split() method with strings. | # Term to split on
split_term = '@'
phrase = 'What is the domain name of someone with the email: [email protected]'
# Split the phrase
re.split(split_term,phrase) | _____no_output_____ | MIT | Regular Expression/PY0101EN-Regular Expressions.ipynb | reddyprasade/PYTHON-BASIC-FOR-ALL |
Note how re.split() returns a list with the term to spit on removed and the terms in the list are a split up version of the string. Create a couple of more examples for yourself to make sure you understand! Finding all instances of a patternYou can use re.findall() to find all the instances of a pattern in a string. For example: | # Returns a list of all matches
re.findall('is','test phrase match is in middle')
a = " a list with the term to spit on removed and the terms in the list are a split up version of the string. Create a couple of more examples for yourself to make sure you understand!"
copy = re.findall("to",a)
copy
len(copy) | _____no_output_____ | MIT | Regular Expression/PY0101EN-Regular Expressions.ipynb | reddyprasade/PYTHON-BASIC-FOR-ALL |
Pattern re SyntaxThis will be the bulk of this lecture on using re with Python. Regular expressions supports a huge variety of patterns the just simply finding where a single string occurred. We can use *metacharacters* along with re to find specific types of patterns. Since we will be testing multiple re syntax forms, let's create a function that will print out results given a list of various regular expressions and a phrase to parse: | def multi_re_find(patterns,phrase):
'''
Takes in a list of regex patterns
Prints a list of all matches
'''
for pattern in patterns:
print ('Searching the phrase using the re check: %r' %pattern)
print (re.findall(pattern,phrase)) | _____no_output_____ | MIT | Regular Expression/PY0101EN-Regular Expressions.ipynb | reddyprasade/PYTHON-BASIC-FOR-ALL |
Repetition SyntaxThere are five ways to express repetition in a pattern: 1.) A pattern followed by the meta-character * is repeated zero or more times. 2.) Replace the * with + and the pattern must appear at least once. 3.) Using ? means the pattern appears zero or one time. 4.) For a specific number of occurrences, use {m} after the pattern, where m is replaced with the number of times the pattern should repeat. 5.) Use {m,n} where m is the minimum number of repetitions and n is the maximum. Leaving out n ({m,}) means the value appears at least m times, with no maximum. Now we will see an example of each of these using our multi_re_find function: | test_phrase = 'sdsd..sssddd...sdddsddd...dsds...dsssss...sdddd'
test_patterns = [ 'sd*', # s followed by zero or more d's
'sd+', # s followed by one or more d's
'sd?', # s followed by zero or one d's
'sd{3}', # s followed by three d's
'sd{2,3}', # s followed by two to three d's
]
multi_re_find(test_patterns,test_phrase) | Searching the phrase using the re check: 'sd*'
['sd', 'sd', 's', 's', 'sddd', 'sddd', 'sddd', 'sd', 's', 's', 's', 's', 's', 's', 'sdddd']
Searching the phrase using the re check: 'sd+'
['sd', 'sd', 'sddd', 'sddd', 'sddd', 'sd', 'sdddd']
Searching the phrase using the re check: 'sd?'
['sd', 'sd', 's', 's', 'sd', 'sd', 'sd', 'sd', 's', 's', 's', 's', 's', 's', 'sd']
Searching the phrase using the re check: 'sd{3}'
['sddd', 'sddd', 'sddd', 'sddd']
Searching the phrase using the re check: 'sd{2,3}'
['sddd', 'sddd', 'sddd', 'sddd']
| MIT | Regular Expression/PY0101EN-Regular Expressions.ipynb | reddyprasade/PYTHON-BASIC-FOR-ALL |
Character SetsCharacter sets are used when you wish to match any one of a group of characters at a point in the input. Brackets are used to construct character set inputs. For example: the input [ab] searches for occurrences of either a or b.Let's see some examples: | test_phrase = 'sdsd..sssddd...sdddsddd...dsds...dsssss...sdddd'
test_patterns = [ '[sd]', # either s or d
's[sd]+'] # s followed by one or more s or d
multi_re_find(test_patterns,test_phrase) | Searching the phrase using the re check: '[sd]'
['s', 'd', 's', 'd', 's', 's', 's', 'd', 'd', 'd', 's', 'd', 'd', 'd', 's', 'd', 'd', 'd', 'd', 's', 'd', 's', 'd', 's', 's', 's', 's', 's', 's', 'd', 'd', 'd', 'd']
Searching the phrase using the re check: 's[sd]+'
['sdsd', 'sssddd', 'sdddsddd', 'sds', 'sssss', 'sdddd']
| MIT | Regular Expression/PY0101EN-Regular Expressions.ipynb | reddyprasade/PYTHON-BASIC-FOR-ALL |
It makes sense that the first [sd] returns every instance. Also the second input will just return any thing starting with an s in this particular case of the test phrase input. ExclusionWe can use ^ to exclude terms by incorporating it into the bracket syntax notation. For example: [^...] will match any single character not in the brackets. Let's see some examples: | test_phrase = 'This is a string! But it has punctuation. How can we remove it?' | _____no_output_____ | MIT | Regular Expression/PY0101EN-Regular Expressions.ipynb | reddyprasade/PYTHON-BASIC-FOR-ALL |
Use [^!.? ] to check for matches that are not a !,.,?, or space. Add the + to check that the match appears at least once, this basically translate into finding the words. | re.findall('[^!.? ]+',test_phrase) | _____no_output_____ | MIT | Regular Expression/PY0101EN-Regular Expressions.ipynb | reddyprasade/PYTHON-BASIC-FOR-ALL |
Character RangesAs character sets grow larger, typing every character that should (or should not) match could become very tedious. A more compact format using character ranges lets you define a character set to include all of the contiguous characters between a start and stop point. The format used is [start-end].Common use cases are to search for a specific range of letters in the alphabet, such [a-f] would return matches with any instance of letters between a and f. Let's walk through some examples: |
test_phrase = 'This is an example sentence. Lets see if we can find some letters.'
test_patterns=[ '[a-z]+', # sequences of lower case letters
'[A-Z]+', # sequences of upper case letters
'[a-zA-Z]+', # sequences of lower or upper case letters
'[A-Z][a-z]+'] # one upper case letter followed by lower case letters
multi_re_find(test_patterns,test_phrase) | Searching the phrase using the re check: '[a-z]+'
['his', 'is', 'an', 'example', 'sentence', 'ets', 'see', 'if', 'we', 'can', 'find', 'some', 'letters']
Searching the phrase using the re check: '[A-Z]+'
['T', 'L']
Searching the phrase using the re check: '[a-zA-Z]+'
['This', 'is', 'an', 'example', 'sentence', 'Lets', 'see', 'if', 'we', 'can', 'find', 'some', 'letters']
Searching the phrase using the re check: '[A-Z][a-z]+'
['This', 'Lets']
| MIT | Regular Expression/PY0101EN-Regular Expressions.ipynb | reddyprasade/PYTHON-BASIC-FOR-ALL |
Escape CodesYou can use special escape codes to find specific types of patterns in your data, such as digits, non-digits,whitespace, and more. For example:CodeMeaning\da digit\Da non-digit\swhitespace (tab, space, newline, etc.)\Snon-whitespace\walphanumeric\Wnon-alphanumericEscapes are indicated by prefixing the character with a backslash (\). Unfortunately, a backslash must itself be escaped in normal Python strings, and that results in expressions that are difficult to read. Using raw strings, created by prefixing the literal value with r, for creating regular expressions eliminates this problem and maintains readability.Personally, I think this use of r to escape a backslash is probably one of the things that block someone who is not familiar with regex in Python from being able to read regex code at first. Hopefully after seeing these examples this syntax will become clear. | test_phrase = 'This is a string with some numbers 1233 and a symbol #hashtag'
test_patterns=[ r'\d+', # sequence of digits
r'\D+', # sequence of non-digits
r'\s+', # sequence of whitespace
r'\S+', # sequence of non-whitespace
r'\w+', # alphanumeric characters
r'\W+', # non-alphanumeric
]
multi_re_find(test_patterns,test_phrase) | Searching the phrase using the re check: '\\d+'
['1233']
Searching the phrase using the re check: '\\D+'
['This is a string with some numbers ', ' and a symbol #hashtag']
Searching the phrase using the re check: '\\s+'
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
Searching the phrase using the re check: '\\S+'
['This', 'is', 'a', 'string', 'with', 'some', 'numbers', '1233', 'and', 'a', 'symbol', '#hashtag']
Searching the phrase using the re check: '\\w+'
['This', 'is', 'a', 'string', 'with', 'some', 'numbers', '1233', 'and', 'a', 'symbol', 'hashtag']
Searching the phrase using the re check: '\\W+'
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' #']
| MIT | Regular Expression/PY0101EN-Regular Expressions.ipynb | reddyprasade/PYTHON-BASIC-FOR-ALL |
You will scrape this mockup site that lists a few data points for addiction centers. | pip install icecream
## import library(ies)
import requests
from bs4 import BeautifulSoup
import pandas as pd
from icecream import ic
## capture the contents of the site in a response object
url = "https://sandeepmj.github.io/scrape-example-page/homework-site.html"
response = requests.get(url)
ic(response.status_code)
## generate and print soup
soup = BeautifulSoup(response.text, 'html.parser')
soup
## check data type of soup
type(soup)
### Return the name of the first center (including the html)
soup.find("a")
## if there were another a tag that did not have our target, we coud be more specific.
soup.find("div", class_="wrap").find("h4").find("a")
### Return only the name of the first center (remove all the html)
soup.find("a").get_text()
### Return only the URL of the first center
soup.find("a").get("href")
### Find first instance of ALL a center's data
### Think of this as the first group of data associated with a company
soup.find("div", class_="wrap")
#### Find all the instances of every centers' data points.
soup.find_all("div", class_="wrap")
### Find all the registration data
soup.find_all("p", class_="registration") | _____no_output_____ | MIT | homework/homework-for-week-5-SOLUTION.ipynb | jchapamalacara/fall21-students-practical-python |
Place all the registration data into a list with only the numbers in the format.It should look like this:```['4235', '4234', '4231']``` | ## for loop
regs = soup.find_all("p", class_="registration")
reg_list_fl = []
for item in regs:
reg_list_fl.append(item.get_text().replace("Registration# ", ""))
reg_list_fl
## do it here (create more cells if you need them)
## via list comprehension
regs = soup.find_all("p", class_="registration")
reg_list_lc = [item.get_text().replace("Registration# ", "") for item in regs]
reg_list_lc | _____no_output_____ | MIT | homework/homework-for-week-5-SOLUTION.ipynb | jchapamalacara/fall21-students-practical-python |
Place all the company names into a list.It should look like this:```['Recovery Foundation','New Horizons','Renewable Light']``` | ## do it here (create more cells if you need them)
cos = soup.find_all("a")
cos
### lc
co_names_list = [item.get_text() for item in cos]
co_names_list | _____no_output_____ | MIT | homework/homework-for-week-5-SOLUTION.ipynb | jchapamalacara/fall21-students-practical-python |
Place all the URLS into a list. | ## do it here (create more cells if you need them)
co_urls = [item.get("href") for item in cos]
co_urls | _____no_output_____ | MIT | homework/homework-for-week-5-SOLUTION.ipynb | jchapamalacara/fall21-students-practical-python |
Place all the status into a list.It should look like this:```['Passed', 'Failed', 'Passed']``` | ## do it here (create more cells if you need them)
center_status = soup.find_all("p", class_="status")
center_status
status_list = [status.get_text().replace("Inspection: ", "") for status in center_status ]
status_list
| _____no_output_____ | MIT | homework/homework-for-week-5-SOLUTION.ipynb | jchapamalacara/fall21-students-practical-python |
Turn these lists into dataframes and export to a csv | ### use pandas DataFrame method to zip files into a dataframe
df = pd.DataFrame(list(zip(co_names_list, reg_list, status_list, co_urls)),
columns =['center_name', "registration_number",'status', 'link'])
df
## export to csv
filename = "recovery_center_list.csv"
df.to_csv(filename, encoding='utf-8', index=False) ## export to csv as utf-8 coding (it just has to be this)
| _____no_output_____ | MIT | homework/homework-for-week-5-SOLUTION.ipynb | jchapamalacara/fall21-students-practical-python |
---_You are currently looking at **version 1.1** of this notebook. To download notebooks and datafiles, as well as get help on Jupyter notebooks in the Coursera platform, visit the [Jupyter Notebook FAQ](https://www.coursera.org/learn/python-data-analysis/resources/0dhYG) course resource._--- Assignment 2 - Pandas IntroductionAll questions are weighted the same in this assignment. Part 1The following code loads the olympics dataset (olympics.csv), which was derrived from the Wikipedia entry on [All Time Olympic Games Medals](https://en.wikipedia.org/wiki/All-time_Olympic_Games_medal_table), and does some basic data cleaning. The columns are organized as of Summer games, Summer medals, of Winter games, Winter medals, total number of games, total of medals. Use this dataset to answer the questions below. | import pandas as pd
df = pd.read_csv('olympics.csv', index_col=0, skiprows=1)
for col in df.columns:
if col[:2]=='01':
df.rename(columns={col:'Gold'+col[4:]}, inplace=True)
if col[:2]=='02':
df.rename(columns={col:'Silver'+col[4:]}, inplace=True)
if col[:2]=='03':
df.rename(columns={col:'Bronze'+col[4:]}, inplace=True)
if col[:1]=='№':
df.rename(columns={col:'#'+col[1:]}, inplace=True)
names_ids = df.index.str.split('\s\(') # split the index by '('
df.index = names_ids.str[0] # the [0] element is the country name (new index)
df['ID'] = names_ids.str[1].str[:3] # the [1] element is the abbreviation or ID (take first 3 characters from that)
df = df.drop('Totals')
df.head() | _____no_output_____ | MIT | 1_introduction/w2_pandas/4_assignment (ipynb)/Assignment 2.ipynb | shijiansu/coursera-applied-data-science-with-python |
Question 0 (Example)What is the first country in df?*This function should return a Series.* | # You should write your whole answer within the function provided. The autograder will call
# this function and compare the return value against the correct solution value
def answer_zero():
# This function returns the row for Afghanistan, which is a Series object. The assignment
# question description will tell you the general format the autograder is expecting
return df.iloc[0]
# You can examine what your function returns by calling it in the cell. If you have questions
# about the assignment formats, check out the discussion forums for any FAQs
answer_zero() | _____no_output_____ | MIT | 1_introduction/w2_pandas/4_assignment (ipynb)/Assignment 2.ipynb | shijiansu/coursera-applied-data-science-with-python |
Question 1Which country has won the most gold medals in summer games?*This function should return a single string value.* | def answer_one():
return "YOUR ANSWER HERE" | _____no_output_____ | MIT | 1_introduction/w2_pandas/4_assignment (ipynb)/Assignment 2.ipynb | shijiansu/coursera-applied-data-science-with-python |
Question 2Which country had the biggest difference between their summer and winter gold medal counts?*This function should return a single string value.* | def answer_two():
return "YOUR ANSWER HERE" | _____no_output_____ | MIT | 1_introduction/w2_pandas/4_assignment (ipynb)/Assignment 2.ipynb | shijiansu/coursera-applied-data-science-with-python |
Question 3Which country has the biggest difference between their summer gold medal counts and winter gold medal counts relative to their total gold medal count? $$\frac{Summer~Gold - Winter~Gold}{Total~Gold}$$Only include countries that have won at least 1 gold in both summer and winter.*This function should return a single string value.* | def answer_three():
return "YOUR ANSWER HERE" | _____no_output_____ | MIT | 1_introduction/w2_pandas/4_assignment (ipynb)/Assignment 2.ipynb | shijiansu/coursera-applied-data-science-with-python |
Question 4Write a function to update the dataframe to include a new column called "Points" which is a weighted value where each gold medal counts for 3 points, silver medals for 2 points, and bronze mdeals for 1 point. The function should return only the column (a Series object) which you created.*This function should return a Series named `Points` of length 146* | def answer_four():
return "YOUR ANSWER HERE" | _____no_output_____ | MIT | 1_introduction/w2_pandas/4_assignment (ipynb)/Assignment 2.ipynb | shijiansu/coursera-applied-data-science-with-python |
Part 2For the next set of questions, we will be using census data from the [United States Census Bureau](http://www.census.gov/popest/data/counties/totals/2015/CO-EST2015-alldata.html). Counties are political and geographic subdivisions of states in the United States. This dataset contains population data for counties and states in the US from 2010 to 2015. [See this document](http://www.census.gov/popest/data/counties/totals/2015/files/CO-EST2015-alldata.pdf) for a description of the variable names.The census dataset (census.csv) should be loaded as census_df. Answer questions using this as appropriate. Question 5Which state has the most counties in it? (hint: consider the sumlevel key carefully! You'll need this for future questions too...)*This function should return a single string value.* | census_df = pd.read_csv('census.csv')
census_df.head()
def answer_five():
return "YOUR ANSWER HERE" | _____no_output_____ | MIT | 1_introduction/w2_pandas/4_assignment (ipynb)/Assignment 2.ipynb | shijiansu/coursera-applied-data-science-with-python |
Question 6Only looking at the three most populous counties for each state, what are the three most populous states (in order of highest population to lowest population)?*This function should return a list of string values.* | def answer_six():
return "YOUR ANSWER HERE" | _____no_output_____ | MIT | 1_introduction/w2_pandas/4_assignment (ipynb)/Assignment 2.ipynb | shijiansu/coursera-applied-data-science-with-python |
Question 7Which county has had the largest absolute change in population within the period 2010-2015? (Hint: population values are stored in columns POPESTIMATE2010 through POPESTIMATE2015, you need to consider all six columns.)e.g. If County Population in the 5 year period is 100, 120, 80, 105, 100, 130, then its largest change in the period would be |130-80| = 50.*This function should return a single string value.* | def answer_seven():
return "YOUR ANSWER HERE" | _____no_output_____ | MIT | 1_introduction/w2_pandas/4_assignment (ipynb)/Assignment 2.ipynb | shijiansu/coursera-applied-data-science-with-python |
Question 8In this datafile, the United States is broken up into four regions using the "REGION" column. Create a query that finds the counties that belong to regions 1 or 2, whose name starts with 'Washington', and whose POPESTIMATE2015 was greater than their POPESTIMATE 2014.*This function should return a 5x2 DataFrame with the columns = ['STNAME', 'CTYNAME'] and the same index ID as the census_df (sorted ascending by index).* | def answer_eight():
return "YOUR ANSWER HERE" | _____no_output_____ | MIT | 1_introduction/w2_pandas/4_assignment (ipynb)/Assignment 2.ipynb | shijiansu/coursera-applied-data-science-with-python |
Visualize all the RGB channel | def visualize_RGB_Channels(imgArray=None, fig_size=(10,7)):
# spliting the RGB components
B,G,R=cv2.split(imgArray)
#zero matrix
Z=np.zeros(B.shape,dtype=B.dtype)
#initilize subplot
fig,ax=plt.subplots(2,2, figsize=fig_size)
[axi.set_axis_off() for axi in ax.ravel()]
ax[0,0].set_title("Original image")
ax[0,0].imshow(cv2.merge((R,G,B)))
ax[0,1].set_title("Red Chanel")
ax[0,1].imshow(cv2.merge((R,Z,Z)))
ax[1,0].set_title("Green Chanel")
ax[1,0].imshow(cv2.merge((Z,G,Z)))
ax[1,1].set_title("Blue Chanel")
ax[1,1].imshow(cv2.merge((Z,Z,B)))
visualize_RGB_Channels(imgArray=car1_cv2)
random_colored_image=np.random.randint(0,255,(6,6,3))
random_colored_image.shape
visualize_RGB_Channels(imgArray=random_colored_image)
random_colored_image[0,0:]
random_colored_image[0,0,:]
random_colored_image[-1,-1,:] | _____no_output_____ | MIT | Image-Processing/image-understanding-in-Details.ipynb | TUCchkul/ComputerVision-ObjectDetection |
Filters | sobel=np.array([[1,0,-1],[2,0,-2],[1,0,-1]])
print(sobel)
sobel.T
example1=[[0,0,0,255,255,255],
[0,0,0,255,255,255],
[0,0,0,255,255,255],
[0,0,0,255,255,255],
[0,0,0,255,255,255],
[0,0,0,255,255,255]]
example1=np.array(example1)
plt.imshow(example1, cmap="gray") | _____no_output_____ | MIT | Image-Processing/image-understanding-in-Details.ipynb | TUCchkul/ComputerVision-ObjectDetection |
Apply filter on this image | def find_edges(imgFilter=None, picture=None):
# extract row and column of an input picture
p_row,p_col=picture.shape
k=imgFilter.shape[0]
temp=list()
strides=1
#resultant rows and columns
final_columns=(p_col -k)//strides +1
final_rows=(p_row -k)//strides +1
#take vertically down sr´tride accross row by row
for v_stride in range(final_rows):
for h_stride in range(final_columns):
target_area_of_pic=picture[v_stride:v_stride +k, h_stride:h_stride+k]
temp.append(sum(sum(imgFilter* target_area_of_pic)))
#print(temp)
return np.array(temp).reshape(final_rows,final_columns)
result=find_edges(sobel, example1)
result
sum(sum(result))
example1
sum(example1)
sum(sum(example1))
plt.imshow(result, cmap="gray")
sobel.T
result_T=find_edges(sobel.T, example1)
result_T
plt.imshow(result_T, cmap="gray")
example1
example_T=example1.T
plt.imshow(example_T,cmap="gray")
result_T1=find_edges(sobel.T, example_T)
result_T1
plt.imshow(result_T1, cmap="gray")
result_car=find_edges(sobel,car1_cv2_BGR_Gray)
result_car
plt.imshow(result_car, cmap="gray") | _____no_output_____ | MIT | Image-Processing/image-understanding-in-Details.ipynb | TUCchkul/ComputerVision-ObjectDetection |
lets now apply horizontal edges | result_car_hor=find_edges(sobel.T, car1_cv2_BGR_Gray)
plt.imshow(result_car, cmap="gray")
example1
example1=[[255,0,0,0,255,255,255,255,0,0,0,255],
[0,0,0,0,255,255,255,255,0,0,0,0],
[0,0,0,0,255,255,255,255,255,255,255,255],
[0,0,0,0,255,255,255,255,255,255,255,255],
[0,0,0,0,255,255,255,255,255,255,255,255],
[0,0,0,0,255,255,255,255,255,255,255,255],
[0,0,0,0,255,255,255,255,255,255,255,255],
[0,0,0,0,255,255,255,255,0,0,0,0],
[0,0,0,0,255,255,255,255,0,0,0,0],
[255,0,0,0,255,255,255,255,0,0,0,255]]
example1=np.array(example1)
plt.imshow(example1, cmap="gray")
result=find_edges(sobel.T, example1)
plt.imshow(result, cmap="gray")
result.shape | _____no_output_____ | MIT | Image-Processing/image-understanding-in-Details.ipynb | TUCchkul/ComputerVision-ObjectDetection |
Tarefa 1 1. Stemizacao | from nltk.stem.snowball import SnowballStemmer
# É importante definir a lingua
stemizador = SnowballStemmer('portuguese')
palavras_stemizadas = []
for palavra in nltk.word_tokenize(texto_formatado):
print(palavra, ' = ', stemizador.stem(palavra))
palavras_stemizadas.append(stemizador.stem(palavra))
print(palavras_stemizadas)
resultado = ' '.join([str(cada_token) for cada_token in palavras_stemizadas if not cada_token.isdigit()])
print(resultado)
frequencia_palavras = nltk.FreqDist(nltk.word_tokenize(resultado))
frequencia_palavras
frequencia_maxima = max(frequencia_palavras.values())
frequencia_maxima
for cada_palavra in frequencia_palavras.keys():
frequencia_palavras[cada_palavra] = frequencia_palavras[cada_palavra]/frequencia_maxima
frequencia_palavras
notas_das_sentencas = {}
for cada_sentenca in sentencas:
# print(cada_sentenca)
for cada_palavra in nltk.word_tokenize(cada_sentenca.lower()):
# print(cada_palavra)
aux = stemizador.stem(cada_palavra)
if aux in frequencia_palavras.keys():
if cada_sentenca not in notas_das_sentencas:
notas_das_sentencas[cada_sentenca] = frequencia_palavras[aux]
else:
notas_das_sentencas[cada_sentenca] += frequencia_palavras[aux]
notas_das_sentencas
melhores_sentencas = heapq.nlargest(3, notas_das_sentencas, key = notas_das_sentencas.get)
melhores_sentencas
resumo = ''.join(melhores_sentencas)
resumo
texto_final = ''
display(HTML(f'<h1> RESUMO GERADO AUTOMATICAMENTE (Stemizadas)</h1>'))
for cada_sentenca in sentencas:
#texto_final = ''
#texto_final += cada_sentenca
if cada_sentenca in melhores_sentencas:
texto_final += str(cada_sentenca).replace(cada_sentenca, f"<mark>{cada_sentenca}</mark>")
else:
texto_final += str(cada_sentenca)
texto_final += ' '
display(HTML(f"""{texto_final}""")) | _____no_output_____ | MIT | processamento-de-linguagem-natural/aula1.ipynb | andredarcie/my-data-science-notebooks |
2. Lematizacao | import spacy
!python -m spacy download pt_core_news_sm
pln = spacy.load('pt_core_news_sm')
pln
palavras = pln(texto_formatado)
# Spacy já separa as palavras em tokens
palavras_lematizadas = []
for palavra in palavras:
#print(palavra.text, ' = ', palavra.lemma_)
palavras_lematizadas.append(palavra.lemma_)
print(palavras_lematizadas)
resultado = ' '.join([str(cada_token) for cada_token in palavras_lematizadas if not cada_token.isdigit()])
print(resultado)
frequencia_palavras = nltk.FreqDist(nltk.word_tokenize(resultado))
frequencia_palavras
frequencia_maxima = max(frequencia_palavras.values())
frequencia_maxima
for cada_palavra in frequencia_palavras.keys():
frequencia_palavras[cada_palavra] = frequencia_palavras[cada_palavra]/frequencia_maxima
frequencia_palavras
notas_das_sentencas = {}
for cada_sentenca in sentencas:
# print(cada_sentenca)
for cada_palavra in pln(cada_sentenca):
# print(cada_palavra)
aux = cada_palavra.lemma_
if aux in frequencia_palavras.keys():
if cada_sentenca not in notas_das_sentencas:
notas_das_sentencas[cada_sentenca] = frequencia_palavras[aux]
else:
notas_das_sentencas[cada_sentenca] += frequencia_palavras[aux]
notas_das_sentencas
melhores_sentencas = heapq.nlargest(3, notas_das_sentencas, key = notas_das_sentencas.get)
melhores_sentencas
resumo = ''.join(melhores_sentencas)
resumo
texto_final = ''
display(HTML(f'<h1> RESUMO GERADO AUTOMATICAMENTE (Lematizacao)</h1>'))
for cada_sentenca in sentencas:
#texto_final = ''
#texto_final += cada_sentenca
if cada_sentenca in melhores_sentencas:
texto_final += str(cada_sentenca).replace(cada_sentenca, f"<mark>{cada_sentenca}</mark>")
else:
texto_final += str(cada_sentenca)
texto_final += ' '
display(HTML(f"""{texto_final}""")) | _____no_output_____ | MIT | processamento-de-linguagem-natural/aula1.ipynb | andredarcie/my-data-science-notebooks |
Fim da Tarefa 1 Uso da lib Goose3 | from goose3 import Goose
g = Goose()
url = 'https://www.techtudo.com.br/noticias/2017/08/o-que-e-replika-app-usa-inteligencia-artificial-para-criar-um-clone-seu.ghtml'
materia = g.extract(url)
materia.title
materia.tags
materia.infos
materia.cleaned_text | _____no_output_____ | MIT | processamento-de-linguagem-natural/aula1.ipynb | andredarcie/my-data-science-notebooks |
Tarefa 2 | frequencia_palavras.keys()
frequencia_palavras
frase = """Algoritmos de aprendizados supervisionados utilizam dados coletados""".split(' ')
frequencia_palavras_frase = []
for palavra in frase:
for freq_palavra in frequencia_palavras:
if palavra in freq_palavra:
frequencia_palavras_frase.append([palavra, 1])
frequencia_palavras_frase
for x in frequencia_palavras:
print(x) | correr
característico
dar
inteligente
aprendizado
coletados
partir
estruturar
estatístico
algoritmo
supervisionar
utilizar
conjuntar
extrair
poder
ser
corrido
estabelecer
relação
inteligência
enquanto
quantitativo
modelo
máquina
construir
reconhecimento
atividades
humano
| MIT | processamento-de-linguagem-natural/aula1.ipynb | andredarcie/my-data-science-notebooks |
Subsets and Splits