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 |
|---|---|---|---|---|---|
For the most part, we'll almost never perform manual standardization because we'll include preprocessing steps in **model pipelines**.So let's import the make_pipeline() function from Scikit-Learn. | # Function for creating model pipelines
from sklearn.pipeline import make_pipeline | _____no_output_____ | MIT | Day_7/Lesson 4 - Real Estate Model Training.ipynb | SoftStackFactory/DSML_Primer |
Now let's import the StandardScaler, which is used for standardization. | # For standardization
from sklearn.preprocessing import StandardScaler | _____no_output_____ | MIT | Day_7/Lesson 4 - Real Estate Model Training.ipynb | SoftStackFactory/DSML_Primer |
Next, create a pipelines dictionary.* It should include 3 keys: 'lasso', 'ridge', and 'enet'* The corresponding values should be pipelines that first standardize the data.* For the algorithm in each pipeline, set random_state=123 to ensure replicable results. | # Create pipelines dictionary
pipeline_dict = { 'lasso' : make_pipeline(StandardScaler(), Lasso(random_state=123)),
'ridge' : make_pipeline(StandardScaler(), Ridge(random_state=123)),
'enet' : make_pipeline(StandardScaler(), ElasticNet(random_state=123)) } | _____no_output_____ | MIT | Day_7/Lesson 4 - Real Estate Model Training.ipynb | SoftStackFactory/DSML_Primer |
In the next exercise, you'll add pipelines for tree ensembles. Exercise 5.2**Add pipelines for RandomForestRegressor and GradientBoostingRegressor to your pipeline dictionary.*** Name them 'rf' for random forest and 'gb' for gradient boosted tree.* Both pipelines should standardize the data first.* For both, set rando... | # Add a pipeline for 'rf'
pipeline_dict['rf'] = make_pipeline(StandardScaler(), RandomForestRegressor(random_state=123))
# Add a pipeline for 'gb'
pipeline_dict['gb'] = make_pipeline(StandardScaler(), GradientBoostingRegressor(random_state=123)) | _____no_output_____ | MIT | Day_7/Lesson 4 - Real Estate Model Training.ipynb | SoftStackFactory/DSML_Primer |
Let's make sure our dictionary has pipelines for each of our algorithms.**Run this code to confirm that you have all 5 algorithms, each part of a pipeline.** | # Check that we have all 5 algorithms, and that they are all pipelines
for key, value in pipeline_dict.items():
print( key, type(value) ) | lasso <class 'sklearn.pipeline.Pipeline'>
ridge <class 'sklearn.pipeline.Pipeline'>
enet <class 'sklearn.pipeline.Pipeline'>
rf <class 'sklearn.pipeline.Pipeline'>
gb <class 'sklearn.pipeline.Pipeline'>
| MIT | Day_7/Lesson 4 - Real Estate Model Training.ipynb | SoftStackFactory/DSML_Primer |
Now that we have our pipelines, we're ready to move on to declaring hyperparameters to tune.[**Back to Contents**](toc) 3. Declare hyperparameters to tuneUp to now, we've been casually talking about "tuning" models, but now it's time to treat the topic more formally.First, list all the tunable hyperparameters for your... | # List tuneable hyperparameters of our Lasso pipeline
pipeline_dict['lasso'].get_params() | _____no_output_____ | MIT | Day_7/Lesson 4 - Real Estate Model Training.ipynb | SoftStackFactory/DSML_Primer |
Next, declare hyperparameters to tune for Lasso and Ridge regression.* Try values between 0.001 and 10 for alpha. | # Lasso hyperparameters
lasso_hyperparameters = { 'lasso__alpha' : [0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1, 5, 10] }
# Ridge hyperparameters
ridge_hyperparameters = { 'ridge__alpha': [0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1, 5, 10] } | _____no_output_____ | MIT | Day_7/Lesson 4 - Real Estate Model Training.ipynb | SoftStackFactory/DSML_Primer |
Now declare a hyperparameter grid fo Elastic-Net.* You should tune the l1_ratio in addition to alpha. | # Elastic Net hyperparameters
enet_hyperparameters = { 'elasticnet__alpha': [0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1, 5, 10],
'elasticnet__l1_ratio': [0.1, 0.3, 0.5, 0.7, 0.9]} | _____no_output_____ | MIT | Day_7/Lesson 4 - Real Estate Model Training.ipynb | SoftStackFactory/DSML_Primer |
Exercise 5.3Let's start by declaring the hyperparameter grid for our random forest.**Declare a hyperparameter grid for RandomForestRegressor.*** Name it rf_hyperparameters* Set 'randomforestregressor\__n_estimators': [100, 200]* Set 'randomforestregressor\__max_features': ['auto', 'sqrt', 0.33] | # Random forest hyperparameters
rf_hyperparameters = {
'randomforestregressor__n_estimators' : [100, 200],
'randomforestregressor__max_features': ['auto', 'sqrt', 0.33],
} | _____no_output_____ | MIT | Day_7/Lesson 4 - Real Estate Model Training.ipynb | SoftStackFactory/DSML_Primer |
Next, let's declare settings to try for our boosted tree.**Declare a hyperparameter grid for GradientBoostingRegressor.*** Name it gb_hyperparameters.* Set 'gradientboostingregressor\__n_estimators': [100, 200]* Set 'gradientboostingregressor\__learning_rate': [0.05, 0.1, 0.2]* Set 'gradientboostingregressor\__max_dept... | # Boosted tree hyperparameters
gb_hyperparameters = { 'gradientboostingregressor__n_estimators': [100, 200],
'gradientboostingregressor__learning_rate': [0.05, 0.1, 0.2],
'gradientboostingregressor__max_depth': [1, 3, 5]} | _____no_output_____ | MIT | Day_7/Lesson 4 - Real Estate Model Training.ipynb | SoftStackFactory/DSML_Primer |
Now that we have all of our hyperparameters declared, let's store them in a dictionary for ease of access.**Create a hyperparameters dictionary**.* Use the same keys as in the pipelines dictionary. * If you forgot what those keys were, you can insert a new code cell and call pipelines.keys() for a reminder.* Set the... | # Create hyperparameters dictionary
hyperparameters = {
'rf' : rf_hyperparameters,
'gb' : gb_hyperparameters,
'lasso' : lasso_hyperparameters,
'ridge' : ridge_hyperparameters,
'enet' : enet_hyperparameters
} | _____no_output_____ | MIT | Day_7/Lesson 4 - Real Estate Model Training.ipynb | SoftStackFactory/DSML_Primer |
**Finally, run this code to check that hyperparameters is set up correctly.** | for key in ['enet', 'gb', 'ridge', 'rf', 'lasso']:
if key in hyperparameters:
if type(hyperparameters[key]) is dict:
print( key, 'was found in hyperparameters, and it is a grid.' )
else:
print( key, 'was found in hyperparameters, but it is not a grid.' )
else:
pri... | enet was found in hyperparameters, and it is a grid.
gb was found in hyperparameters, and it is a grid.
ridge was found in hyperparameters, and it is a grid.
rf was found in hyperparameters, and it is a grid.
lasso was found in hyperparameters, and it is a grid.
| MIT | Day_7/Lesson 4 - Real Estate Model Training.ipynb | SoftStackFactory/DSML_Primer |
[**Back to Contents**](toc) 4. Fit and tune models with cross-validationNow that we have our pipelines and hyperparameters dictionaries declared, we're ready to tune our models with cross-validation.First, let's to import a helper for cross-validation called GridSearchCV. | # Helper for cross-validation
from sklearn.model_selection import GridSearchCV | _____no_output_____ | MIT | Day_7/Lesson 4 - Real Estate Model Training.ipynb | SoftStackFactory/DSML_Primer |
Next, to see an example, set up cross-validation for Lasso regression. | # Create cross-validation object from Lasso pipeline and Lasso hyperparameters
model = GridSearchCV(pipeline_dict['lasso'], hyperparameters['lasso'], cv=10, n_jobs=-1) | _____no_output_____ | MIT | Day_7/Lesson 4 - Real Estate Model Training.ipynb | SoftStackFactory/DSML_Primer |
Pass X_train and y_train into the .fit() function to tune hyperparameters. | # Fit and tune model
model.fit(X_train, y_train) | /opt/conda/lib/python3.6/site-packages/sklearn/linear_model/coordinate_descent.py:491: ConvergenceWarning: Objective did not converge. You might want to increase the number of iterations. Fitting data with very small alpha may cause precision problems.
ConvergenceWarning)
/opt/conda/lib/python3.6/site-packages/sklear... | MIT | Day_7/Lesson 4 - Real Estate Model Training.ipynb | SoftStackFactory/DSML_Primer |
By the way, don't worry if you get the message:ConvergenceWarning: Objective did not converge. You might want to increase the number of iterationsWe'll dive into some of the under-the-hood nuances later.In the next exercise, we'll write a loop that tunes all of our models. Exercise 5.4**Create a dictionary of models n... | # Create empty dictionary called fitted_models
fitted_models = {}
# Loop through model pipelines, tuning each one and saving it to fitted_models
for name, pipeline in pipeline_dict.items():
# Create cross-validation object from pipeline and hyperparameters
model = GridSearchCV(pipeline, hyperparameters[name], ... | /opt/conda/lib/python3.6/site-packages/sklearn/linear_model/coordinate_descent.py:491: ConvergenceWarning: Objective did not converge. You might want to increase the number of iterations. Fitting data with very small alpha may cause precision problems.
ConvergenceWarning)
/opt/conda/lib/python3.6/site-packages/sklear... | MIT | Day_7/Lesson 4 - Real Estate Model Training.ipynb | SoftStackFactory/DSML_Primer |
**Run this code to check that the models are of the correct type.** | # Check that we have 5 cross-validation objects
for key, value in fitted_models.items():
print( key, type(value) ) | lasso <class 'sklearn.model_selection._search.GridSearchCV'>
ridge <class 'sklearn.model_selection._search.GridSearchCV'>
enet <class 'sklearn.model_selection._search.GridSearchCV'>
rf <class 'sklearn.model_selection._search.GridSearchCV'>
gb <class 'sklearn.model_selection._search.GridSearchCV'>
| MIT | Day_7/Lesson 4 - Real Estate Model Training.ipynb | SoftStackFactory/DSML_Primer |
**Finally, run this code to check that the models have been fitted correctly.** | from sklearn.exceptions import NotFittedError
for name, model in fitted_models.items():
try:
pred = model.predict(X_test)
print(name, 'has been fitted.')
except NotFittedError as e:
print(repr(e)) | lasso has been fitted.
ridge has been fitted.
enet has been fitted.
rf has been fitted.
gb has been fitted.
| MIT | Day_7/Lesson 4 - Real Estate Model Training.ipynb | SoftStackFactory/DSML_Primer |
Nice. Now we're ready to evaluate how our models performed 5. Evaluate models and select winnerFinally, it's time to evaluate our models and pick the best one.Let's display the holdout $R^2$ score for each fitted model. | # Display best_score_ for each fitted model
for name, model in fitted_models.items():
print(name, model.best_score_) | lasso 0.3074411588306972
ridge 0.3155067536069877
enet 0.3422914802767902
rf 0.4833888008561866
gb 0.48722517575886765
| MIT | Day_7/Lesson 4 - Real Estate Model Training.ipynb | SoftStackFactory/DSML_Primer |
You should see something similar to the below scores: enet 0.342759786956 lasso 0.309321321129 ridge 0.316805719351 gb 0.48873808731 rf 0.480576134721If your numbers are way off, check to see if you've set the random_state= correctly for each of the models. Next, import the r2_score() and mean_absolute_e... | # Import r2_score and mean_absolute_error functions
from sklearn.metrics import r2_score
from sklearn.metrics import mean_absolute_error | _____no_output_____ | MIT | Day_7/Lesson 4 - Real Estate Model Training.ipynb | SoftStackFactory/DSML_Primer |
Finally, let's see how the fitted models perform on our test set!First, access your fitted random forest and display the object. | # Display fitted random forest object
fitted_models['rf'] | _____no_output_____ | MIT | Day_7/Lesson 4 - Real Estate Model Training.ipynb | SoftStackFactory/DSML_Primer |
Predict the test set using the fitted random forest. | # Predict test set using fitted random forest
pred = fitted_models['rf'].predict(X_test) | _____no_output_____ | MIT | Day_7/Lesson 4 - Real Estate Model Training.ipynb | SoftStackFactory/DSML_Primer |
Finally, we use the scoring functions we imported to calculate and print $R^2$ and MAE. | # Calculate and print R^2 and MAE
print('R^2: ', r2_score(y_test, pred))
print('MAE: ', mean_absolute_error(y_test, pred)) | R^2: 0.566278620200386
MAE: 68497.58
| MIT | Day_7/Lesson 4 - Real Estate Model Training.ipynb | SoftStackFactory/DSML_Primer |
In the next exercise, we'll evaluate all of our fitted models on the test set and pick the winner. Exercise 5.5**Use a for loop, print the performance of each model in fitted_models on the test set.*** Print both r2_score and mean_absolute_error.* Those functions each take two arguments: * The actual values for you... | # Code here
for name, model in fitted_models.items():
pred_var = model.predict(X_test)
print(name)
print('R^2: ', r2_score(y_test, pred_var))
print('MAE: ', mean_absolute_error(y_test, pred_var))
print('===================================')
| lasso
R^2: 0.4093410739690313
MAE: 84957.9784492079
===================================
ridge
R^2: 0.40978386776640285
MAE: 84899.82281275438
===================================
enet
R^2: 0.40415614629545416
MAE: 86465.82558534491
===================================
rf
R^2: 0.566278620200386
MAE: 68497.58
=====... | MIT | Day_7/Lesson 4 - Real Estate Model Training.ipynb | SoftStackFactory/DSML_Primer |
**Next, ask yourself these questions to pick the winning model:*** Which model had the highest $R^2$ on the test set?> Random forest* Which model had the lowest mean absolute error?> Random forest* Are these two models the same one?> Yes* Did it also have the best holdout $R^2$ score from cross-validation?> Yes* **Does... | gb_pred = fitted_models['rf'].predict(X_test)
plt.scatter(gb_pred, y_test)
plt.xlabel('predicted')
plt.ylabel('actual')
plt.show() | _____no_output_____ | MIT | Day_7/Lesson 4 - Real Estate Model Training.ipynb | SoftStackFactory/DSML_Primer |
This last visual check is a nice way to confirm our model's performance.* Are the points scattered around the 45 degree diagonal?[**Back to Contents**](toc) Finally, let's save the winning model.Great job! You've created a pretty kick-ass model for real-estate valuation. Now it's time to save your hard work.First, let... | type(fitted_models['rf']) | _____no_output_____ | MIT | Day_7/Lesson 4 - Real Estate Model Training.ipynb | SoftStackFactory/DSML_Primer |
It looks like this is still the GridSearchCV data type. * You can actually directly save this object if you want, because it will use the winning model pipeline by default. * However, what we really care about is the actual winning model Pipeline, right?In that case, we can use the best\_estimator_ method to access it: | type(fitted_models['rf'].best_estimator_) | _____no_output_____ | MIT | Day_7/Lesson 4 - Real Estate Model Training.ipynb | SoftStackFactory/DSML_Primer |
If we output that object directly, we can also see the winning values for our hyperparameters. | fitted_models['rf'].best_estimator_ | _____no_output_____ | MIT | Day_7/Lesson 4 - Real Estate Model Training.ipynb | SoftStackFactory/DSML_Primer |
See? The winning values for our hyperparameters are:* n_estimators: 200* max_features : 'auto'Great, now let's import a helpful package called pickle, which saves Python objects to disk. | import pickle | _____no_output_____ | MIT | Day_7/Lesson 4 - Real Estate Model Training.ipynb | SoftStackFactory/DSML_Primer |
Let's save the winning Pipeline object into a pickle file. | with open('saved_models/final_model_employee.pkl', 'wb') as f:
pickle.dump(fitted_models['rf'].best_estimator_, f) | _____no_output_____ | MIT | Day_7/Lesson 4 - Real Estate Model Training.ipynb | SoftStackFactory/DSML_Primer |
Title of the Project__Enter Subtitle here if any__ Overview__What?__- Tell us about the problem you are about to solve.__When?__- Tell us when and how you will determine that this project is successful (metrics)__Why?__- Tell us why this problem is interesting.__Who?__- Tell us who might be interested in your project... | ## Decision tree model
## Logistic regression model
## confusion matrices for both models | _____no_output_____ | MIT | assignments/Final Project Report Template.ipynb | mikev6/UMBC_Data601 |
Fine Tune - Make sure that you played with the hyper-parameters and fine-tuned the parameters. - Use grid search, cross validation to compare different models. - Don't show all of your work here only mention if it is necessary to understand you work's results. | ## here your code if necessary | _____no_output_____ | MIT | assignments/Final Project Report Template.ipynb | mikev6/UMBC_Data601 |
Copyright by Pierian Data Inc. Created by Jose Marcial Portilla. Keras Syntax BasicsWith TensorFlow 2.0 , Keras is now the main API choice. Let's work through a simple regression project to understand the basics of the Keras syntax and adding layers. The DataTo learn the basic syntax of Keras, we will use a very simp... | import pandas as pd
df = pd.read_csv('../DATA/fake_reg.csv')
df.head() | _____no_output_____ | Apache-2.0 | FINAL-TF2-FILES/TF_2_Notebooks_and_Data/03-ANNs/00-Keras-Syntax-Basics.ipynb | tanuja333/Tensorflow_Keras |
Explore the dataLet's take a quick look, we should see strong correlation between the features and the "price" of this made up product. | import seaborn as sns
import matplotlib.pyplot as plt
sns.pairplot(df) | _____no_output_____ | Apache-2.0 | FINAL-TF2-FILES/TF_2_Notebooks_and_Data/03-ANNs/00-Keras-Syntax-Basics.ipynb | tanuja333/Tensorflow_Keras |
Feel free to visualize more, but this data is fake, so we will focus on feature engineering and exploratory data analysis later on in the course in much more detail! Test/Train Split | from sklearn.model_selection import train_test_split
# Convert Pandas to Numpy for Keras
# Features
X = df[['feature1','feature2']].values
# Label
y = df['price'].values
# Split
X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.3,random_state=42)
X_train.shape
X_test.shape
y_train.shape
y_test.shap... | _____no_output_____ | Apache-2.0 | FINAL-TF2-FILES/TF_2_Notebooks_and_Data/03-ANNs/00-Keras-Syntax-Basics.ipynb | tanuja333/Tensorflow_Keras |
Normalizing/Scaling the DataWe scale the feature data.[Why we don't need to scale the label](https://stats.stackexchange.com/questions/111467/is-it-necessary-to-scale-the-target-value-in-addition-to-scaling-features-for-re) | from sklearn.preprocessing import MinMaxScaler
help(MinMaxScaler)
scaler = MinMaxScaler()
# Notice to prevent data leakage from the test set, we only fit our scaler to the training set
scaler.fit(X_train)
X_train = scaler.transform(X_train)
X_test = scaler.transform(X_test) | _____no_output_____ | Apache-2.0 | FINAL-TF2-FILES/TF_2_Notebooks_and_Data/03-ANNs/00-Keras-Syntax-Basics.ipynb | tanuja333/Tensorflow_Keras |
TensorFlow 2.0 Syntax Import OptionsThere are several ways you can import Keras from Tensorflow (this is hugely a personal style choice, please use any import methods you prefer). We will use the method shown in the **official TF documentation**. | import tensorflow as tf
from tensorflow.keras.models import Sequential
help(Sequential) | Help on class Sequential in module tensorflow.python.keras.engine.sequential:
class Sequential(tensorflow.python.keras.engine.training.Model)
| Sequential(layers=None, name=None)
|
| Linear stack of layers.
|
| Arguments:
| layers: list of layers to add to the model.
|
| Example:
|
| ```pyt... | Apache-2.0 | FINAL-TF2-FILES/TF_2_Notebooks_and_Data/03-ANNs/00-Keras-Syntax-Basics.ipynb | tanuja333/Tensorflow_Keras |
Creating a ModelThere are two ways to create models through the TF 2 Keras API, either pass in a list of layers all at once, or add them one by one.Let's show both methods (its up to you to choose which method you prefer). | from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Activation | _____no_output_____ | Apache-2.0 | FINAL-TF2-FILES/TF_2_Notebooks_and_Data/03-ANNs/00-Keras-Syntax-Basics.ipynb | tanuja333/Tensorflow_Keras |
Model - as a list of layers | model = Sequential([
Dense(units=2),
Dense(units=2),
Dense(units=2)
]) | _____no_output_____ | Apache-2.0 | FINAL-TF2-FILES/TF_2_Notebooks_and_Data/03-ANNs/00-Keras-Syntax-Basics.ipynb | tanuja333/Tensorflow_Keras |
Model - adding in layers one by one | model = Sequential()
model.add(Dense(2))
model.add(Dense(2))
model.add(Dense(2)) | _____no_output_____ | Apache-2.0 | FINAL-TF2-FILES/TF_2_Notebooks_and_Data/03-ANNs/00-Keras-Syntax-Basics.ipynb | tanuja333/Tensorflow_Keras |
Let's go ahead and build a simple model and then compile it by defining our solver | model = Sequential()
model.add(Dense(4,activation='relu'))
model.add(Dense(4,activation='relu'))
model.add(Dense(4,activation='relu'))
# Final output node for prediction
model.add(Dense(1))
model.compile(optimizer='rmsprop',loss='mse') | _____no_output_____ | Apache-2.0 | FINAL-TF2-FILES/TF_2_Notebooks_and_Data/03-ANNs/00-Keras-Syntax-Basics.ipynb | tanuja333/Tensorflow_Keras |
Choosing an optimizer and lossKeep in mind what kind of problem you are trying to solve: For a multi-class classification problem model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy']) For a binary classification problem model.compile(o... | model.fit(X_train,y_train,epochs=250) | Train on 700 samples
Epoch 1/250
700/700 [==============================] - 1s 1ms/sample - loss: 256678.6899
Epoch 2/250
700/700 [==============================] - 0s 67us/sample - loss: 256557.3328
Epoch 3/250
700/700 [==============================] - 0s 67us/sample - loss: 256435.2685
Epoch 4/250
700/700 [=========... | Apache-2.0 | FINAL-TF2-FILES/TF_2_Notebooks_and_Data/03-ANNs/00-Keras-Syntax-Basics.ipynb | tanuja333/Tensorflow_Keras |
EvaluationLet's evaluate our performance on our training set and our test set. We can compare these two performances to check for overfitting. | model.history.history
loss = model.history.history['loss']
sns.lineplot(x=range(len(loss)),y=loss)
plt.title("Training Loss per Epoch"); | _____no_output_____ | Apache-2.0 | FINAL-TF2-FILES/TF_2_Notebooks_and_Data/03-ANNs/00-Keras-Syntax-Basics.ipynb | tanuja333/Tensorflow_Keras |
Compare final evaluation (MSE) on training set and test set.These should hopefully be fairly close to each other. | model.metrics_names
training_score = model.evaluate(X_train,y_train,verbose=0)
test_score = model.evaluate(X_test,y_test,verbose=0)
training_score
test_score | _____no_output_____ | Apache-2.0 | FINAL-TF2-FILES/TF_2_Notebooks_and_Data/03-ANNs/00-Keras-Syntax-Basics.ipynb | tanuja333/Tensorflow_Keras |
Further Evaluations | test_predictions = model.predict(X_test)
test_predictions
pred_df = pd.DataFrame(y_test,columns=['Test Y'])
pred_df
test_predictions = pd.Series(test_predictions.reshape(300,))
test_predictions
pred_df = pd.concat([pred_df,test_predictions],axis=1)
pred_df.columns = ['Test Y','Model Predictions']
pred_df | _____no_output_____ | Apache-2.0 | FINAL-TF2-FILES/TF_2_Notebooks_and_Data/03-ANNs/00-Keras-Syntax-Basics.ipynb | tanuja333/Tensorflow_Keras |
Let's compare to the real test labels! | sns.scatterplot(x='Test Y',y='Model Predictions',data=pred_df)
pred_df['Error'] = pred_df['Test Y'] - pred_df['Model Predictions']
sns.distplot(pred_df['Error'],bins=50)
from sklearn.metrics import mean_absolute_error,mean_squared_error
mean_absolute_error(pred_df['Test Y'],pred_df['Model Predictions'])
mean_squared_er... | _____no_output_____ | Apache-2.0 | FINAL-TF2-FILES/TF_2_Notebooks_and_Data/03-ANNs/00-Keras-Syntax-Basics.ipynb | tanuja333/Tensorflow_Keras |
Predicting on brand new dataWhat if we just saw a brand new gemstone from the ground? What should we price it at? This is the **exact** same procedure as predicting on a new test data! | # [[Feature1, Feature2]]
new_gem = [[998,1000]]
# Don't forget to scale!
scaler.transform(new_gem)
new_gem = scaler.transform(new_gem)
model.predict(new_gem) | _____no_output_____ | Apache-2.0 | FINAL-TF2-FILES/TF_2_Notebooks_and_Data/03-ANNs/00-Keras-Syntax-Basics.ipynb | tanuja333/Tensorflow_Keras |
Saving and Loading a Model | from tensorflow.keras.models import load_model
model.save('my_model.h5') # creates a HDF5 file 'my_model.h5'
later_model = load_model('my_model.h5')
later_model.predict(new_gem) | _____no_output_____ | Apache-2.0 | FINAL-TF2-FILES/TF_2_Notebooks_and_Data/03-ANNs/00-Keras-Syntax-Basics.ipynb | tanuja333/Tensorflow_Keras |
Basic exampleLet's present what classo does when using its default parameters on synthetic data. | from classo import classo_problem, random_data
import numpy as np | _____no_output_____ | MIT | docs/source/auto_examples/plot_basic_example.ipynb | wendazhou/c-lasso |
Generate the dataThis code snippet generates a problem instance with sparse ß in dimensiond=100 (sparsity d_nonzero=5). The design matrix X comprises n=100 samples generated from an i.i.d standard normaldistribution. The dimension of the constraint matrix C is d x k matrix. The noise level is σ=0.5. The input `zerosum... | m, d, d_nonzero, k, sigma = 100, 200, 5, 1, 0.5
(X, C, y), sol = random_data(m, d, d_nonzero, k, sigma, zerosum=True, seed=1) | _____no_output_____ | MIT | docs/source/auto_examples/plot_basic_example.ipynb | wendazhou/c-lasso |
Remark : one can see the parameters that should be selected : | print(np.nonzero(sol)) | _____no_output_____ | MIT | docs/source/auto_examples/plot_basic_example.ipynb | wendazhou/c-lasso |
Define the classo instanceNext we can define a default c-lasso problem instance with the generated data: | problem = classo_problem(X, y, C) | _____no_output_____ | MIT | docs/source/auto_examples/plot_basic_example.ipynb | wendazhou/c-lasso |
Check parametersYou can look at the generated problem instance by typing: | print(problem) | _____no_output_____ | MIT | docs/source/auto_examples/plot_basic_example.ipynb | wendazhou/c-lasso |
Solve optimization problemsWe only use stability selection as default model selection strategy. The command also allows you to inspect the computed stability profile for all variables at the theoretical λ | problem.solve() | _____no_output_____ | MIT | docs/source/auto_examples/plot_basic_example.ipynb | wendazhou/c-lasso |
VisualisationAfter completion, the results of the optimization and model selection routines can be visualized using | print(problem.solution) | _____no_output_____ | MIT | docs/source/auto_examples/plot_basic_example.ipynb | wendazhou/c-lasso |
Tag Analysis | !pip install loguru
from loguru import logger
from collections import Counter, defaultdict
def get_counts(keywords, level=0):
kws = map(lambda x: x[level if level<len(x) else len(x)-1], keywords)
kws = list(kws)
# kws = list(map(str.lower, kws))
counter = Counter(kws)
return counter
def analyze_kws(... | _____no_output_____ | MIT | colab-analysis-training.ipynb | NISH1001/earth-science-text-classification |
Data Analysis | def parse_kws(kw_str, level=2):
res = kw_str.split(",")
res = map(lambda kw: [_.strip().lower() for _ in kw.split(">")], res)
res = map(lambda x: x[level if level<len(x) else len(x)-1], res)
return list(set(res))
def load_data(path, level=0):
logger.info(f"Loading data from {path}. [KW Level={level... | _____no_output_____ | MIT | colab-analysis-training.ipynb | NISH1001/earth-science-text-classification |
Baseline Model Encode Labels | from sklearn.preprocessing import MultiLabelBinarizer
DATA_TO_USE = DATA.copy()
DATA_TO_USE = DATA_TO_USE[DATA_TO_USE["textlen"]<=500]
DATA_TO_USE.shape
DATA_TO_USE.head()
analyze_labels(DATA_TO_USE)
LE = MultiLabelBinarizer()
LABELS_ENCODED = LE.fit_transform(DATA_TO_USE["labels"])
LABELS_ENCODED.shape
LE.classes_
LE.... | _____no_output_____ | MIT | colab-analysis-training.ipynb | NISH1001/earth-science-text-classification |
Split Dataset | from sklearn.model_selection import train_test_split
X_train, X_test, Y_train, Y_test = train_test_split(DATA_TO_USE["desc"].to_numpy(), LABELS_ENCODED, test_size=0.1, random_state=42)
X_train, X_val, Y_train, Y_val = train_test_split(X_train, Y_train, test_size=0.1, random_state=42)
X_train.shape, X_val.shape, X_te... | _____no_output_____ | MIT | colab-analysis-training.ipynb | NISH1001/earth-science-text-classification |
CreateDataset | ! pip install pytorch_lightning
import torch
from torch.utils.data import DataLoader, Dataset
import pytorch_lightning as pl
class TagDataset (Dataset):
def __init__(self,texts, tags, tokenizer, max_len=512):
self.tokenizer = tokenizer
self.texts = texts
self.labels = tags
self.max_l... | _____no_output_____ | MIT | colab-analysis-training.ipynb | NISH1001/earth-science-text-classification |
Transformers | !pip install transformers
from transformers import AutoTokenizer, AutoModel
TOKENIZER = AutoTokenizer.from_pretrained("bert-base-uncased")
# BASE_MODEL = AutoModel.from_pretrained("bert-base-uncased")
BASE_MODEL = None
# Initialize the parameters that will be use for training
EPOCHS = 10
BATCH_SIZE = 4
MAX_LEN = 512
LR... | _____no_output_____ | MIT | colab-analysis-training.ipynb | NISH1001/earth-science-text-classification |
Model | from pytorch_lightning.callbacks import ModelCheckpoint
from transformers import AdamW, get_linear_schedule_with_warmup
class TagClassifier(pl.LightningModule):
# Set up the classifier
def __init__(self, base_model=None, n_classes=10, steps_per_epoch=None, n_epochs=5, lr=1e-5 ):
super().__init__()
... | _____no_output_____ | MIT | colab-analysis-training.ipynb | NISH1001/earth-science-text-classification |
Test | trainer.test(MODEL,datamodule=TAG_DATA_MODULE) | _____no_output_____ | MIT | colab-analysis-training.ipynb | NISH1001/earth-science-text-classification |
Inference | MODEL.eval()
import pickle
with open("le.pkl", "wb") as f:
pickle.dump(LE, f)
from torch.utils.data import TensorDataset, SequentialSampler
DEVICE = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
MODEL.to(DEVICE)
def inference(model, texts, tokenizer, batch_size=2):
# model.eval()
if isinsta... | _____no_output_____ | MIT | colab-analysis-training.ipynb | NISH1001/earth-science-text-classification |
Custom Evaluation | def inference2(model, tokenizer, texts, gts, threshold=0.3):
_pred_outs = inference(model, texts, tokenizer, batch_size=1)
res = []
for txt, gt, pred in zip(texts, gts, _pred_outs):
p = pred.flatten().copy()
confs = p[p>threshold]
p[p<threshold] = 0
p[p>=threshold] = 1
... | _____no_output_____ | MIT | colab-analysis-training.ipynb | NISH1001/earth-science-text-classification |
作業: (1)以, Adam, 為例, 調整 batch_size, epoch , 觀察accurancy, loss 的變化 (2)以同一模型, 分別驗證 SGD, Adam, Rmsprop 的 accurancy | import keras
#from keras.datasets import cifar10
from keras.datasets import mnist
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential, load_model
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras import optimiz... | _____no_output_____ | MIT | homeworks/D076/Day76-Optimizer_HW.ipynb | peteryuX/100Day-ML-Marathon |
Probabilistic Multiple Cracking Model of Brittle-Matrix Composite: One-by-One Crack Tracing AlgorithmInteractive application for fragmentation model presented in the paper [citation and link will be added upon paper publication] - Change the material parameters to trigger the recalculation. - Inspect the cracking his... | %%html
<style>
.output_wrapper button.btn.btn-default,
.output_wrapper .ui-dialog-titlebar {
display: none;
}
</style>
%matplotlib notebook
import numpy as np
from scipy.optimize import newton
import matplotlib.pylab as plt
Em=25e3 # [MPa] matrix modulus
Ef=180e3 # [MPa] fiber modulus
vf=0.01 # [-] reinforcement r... | _____no_output_____ | MIT | pmcm/fragmentation2.ipynb | bmcs-group/bmcs_fragmentation |
Copyright 2022 The TensorFlow Authors. | #@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under... | _____no_output_____ | Apache-2.0 | tensorflow/lite/g3doc/models/modify/model_maker/text_searcher.ipynb | QS-L-1992/tensorflow |
Text Searcher with TensorFlow Lite Model Maker View on TensorFlow.org Run in Google Colab View source on GitHub Download notebook See TF Hub model In this colab notebook, you can learn how to use the [TensorFlow Lite Model Maker](https://www.tensorflow.org/lite/guide/model_maker) li... | !sudo apt -y install libportaudio2
!pip install -q tflite-model-maker
!pip install gdown | _____no_output_____ | Apache-2.0 | tensorflow/lite/g3doc/models/modify/model_maker/text_searcher.ipynb | QS-L-1992/tensorflow |
Import the required packages. | from tflite_model_maker import searcher | _____no_output_____ | Apache-2.0 | tensorflow/lite/g3doc/models/modify/model_maker/text_searcher.ipynb | QS-L-1992/tensorflow |
Prepare the datasetThis tutorial uses the dataset CNN / Daily Mail summarization dataset from the [GitHub repo](https://github.com/abisee/cnn-dailymail).First, download the text and urls of cnn and dailymail and unzip them. If itfailed to download from google drive, please wait a few minutes to try it again or downloa... | !gdown https://drive.google.com/uc?id=0BwmD_VLjROrfTHk4NFg2SndKcjQ
!gdown https://drive.google.com/uc?id=0BwmD_VLjROrfM1BxdkxVaTY2bWs
!wget -O all_train.txt https://raw.githubusercontent.com/abisee/cnn-dailymail/master/url_lists/all_train.txt
!tar xzf cnn_stories.tgz
!tar xzf dailymail_stories.tgz | _____no_output_____ | Apache-2.0 | tensorflow/lite/g3doc/models/modify/model_maker/text_searcher.ipynb | QS-L-1992/tensorflow |
Then, save the data into the CSV file that can be loaded into `tflite_model_maker` library. The code is based on the logic used to load this data in [`tensorflow_datasets`](https://github.com/tensorflow/datasets/blob/master/tensorflow_datasets/summarization/cnn_dailymail.py). We can't use `tensorflow_dataset` directly ... | #@title Save the highlights and urls to the CSV file
#@markdown Load the highlights from the stories of CNN / Daily Mail, map urls with highlights, and save them to the CSV file.
CNN_FRACTION = 0.05 #@param {type:"number"}
DAILYMAIL_FRACTION = 0.05 #@param {type:"number"}
import csv
import hashlib
import os
import te... | _____no_output_____ | Apache-2.0 | tensorflow/lite/g3doc/models/modify/model_maker/text_searcher.ipynb | QS-L-1992/tensorflow |
Build the text Searcher model Create a text Searcher model by loading a dataset, creating a model with the data and exporting the TFLite model. Step 1. Load the datasetModel Maker takes the text dataset and the corresponding metadata of each text string (such as urls in this example) in the CSV format. It embeds the t... | !wget -O universal_sentence_encoder.tflite https://storage.googleapis.com/download.tensorflow.org/models/tflite_support/searcher/text_to_image_blogpost/text_embedder.tflite | _____no_output_____ | Apache-2.0 | tensorflow/lite/g3doc/models/modify/model_maker/text_searcher.ipynb | QS-L-1992/tensorflow |
Create a `searcher.TextDataLoader` instance and use `data_loader.load_from_csv` method to load the dataset. It takes ~10 minutes for thisstep since it generates the embedding feature vector for each text one by one. You can try to upload your own CSV file and load it to build the customized model as well.Specify the na... | data_loader = searcher.TextDataLoader.create("universal_sentence_encoder.tflite", l2_normalize=True)
data_loader.load_from_csv("cnn_dailymail.csv", text_column="highlights", metadata_column="urls") | _____no_output_____ | Apache-2.0 | tensorflow/lite/g3doc/models/modify/model_maker/text_searcher.ipynb | QS-L-1992/tensorflow |
For image use cases, you can create a `searcher.ImageDataLoader` instance and then use `data_loader.load_from_folder` to load images from the folder. The `searcher.ImageDataLoader` instance needs to be created by a TFLite embedder model because it will be leveraged to encode queries to feature vectors and be exported w... | scann_options = searcher.ScaNNOptions(
distance_measure="dot_product",
tree=searcher.Tree(num_leaves=140, num_leaves_to_search=4),
score_ah=searcher.ScoreAH(dimensions_per_block=1, anisotropic_quantization_threshold=0.2))
model = searcher.Searcher.create_from_data(data_loader, scann_options) | _____no_output_____ | Apache-2.0 | tensorflow/lite/g3doc/models/modify/model_maker/text_searcher.ipynb | QS-L-1992/tensorflow |
In the above example, we define the following options:* `distance_measure`: we use "dot_product" to measure the distance between two embedding vectors. Note that we actually compute the **negative** dot product value to preserve the notion that "smaller is closer".* `tree`: the dataset is divided the dataset into 140 p... | model.export(
export_filename="searcher.tflite",
userinfo="",
export_format=searcher.ExportFormat.TFLITE) | _____no_output_____ | Apache-2.0 | tensorflow/lite/g3doc/models/modify/model_maker/text_searcher.ipynb | QS-L-1992/tensorflow |
Test the TFLite model on your queryYou can test the exported TFLite model using custom query text. To query text using the Searcher model, initialize the model and run a search with text phrase, as follows: | from tflite_support.task import text
# Initializes a TextSearcher object.
searcher = text.TextSearcher.create_from_file("searcher.tflite")
# Searches the input query.
results = searcher.search("The Airline Quality Rankings Report looks at the 14 largest U.S. airlines.")
print(results) | _____no_output_____ | Apache-2.0 | tensorflow/lite/g3doc/models/modify/model_maker/text_searcher.ipynb | QS-L-1992/tensorflow |
StreuungWellenvektor des einfallenden Strahls: $\vec {k}^{(i)}$ Wellenvektor des ausgehenden Strahls: $\vec {k}^{(s)}$Impulsübertrag: $\vec Q =\vec {k}^{(i)} - \vec {k}^{(s)}$ Laue-BedingungVoraussetzung: elastische Streuung ($|\vec {k}^{(i)}| = |\vec {k}^{(s)}| = \frac{2\pi}{\lambda}$)$\vec Q = \Delta \vec{k} = \ve... | import ipywidgets as iw
import matplotlib
import matplotlib.pyplot as plt
from math import *
import numpy as np
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def length(self):
return sqrt(self.x*self.x + self.y * self.y)
def length_sq(self):
r... | _____no_output_____ | MIT | Ewaldkugel.ipynb | moosbruggerj/ewaldkugel-sim |
AI for Medicine Course 1 Week 1 lecture exercises Counting labelsAs you saw in the lecture videos, one way to avoid having class imbalance impact the loss function is to weight the losses differently. To choose the weights, you first need to calculate the class frequencies.For this exercise, you'll just get the coun... | # Import the necessary packages
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline
# Read csv file containing training datadata
train_df = pd.read_csv("nih/train-small.csv")
# Count up the number of instances of each class (drop non-class columns from the cou... | _____no_output_____ | Apache-2.0 | 1_diagnosis/week1/lecture_exercise/AI4M_C1_W1_lecture_ex_02.ipynb | amitbcp/ai_for_medicine_specialisation |
Weighted Loss function Below is an example of calculating weighted loss. In the assignment, you will calculate a weighted loss function. This sample code will give you some intuition for what the weighted loss function is doing, and also help you practice some syntax you will use in the graded assignment.For this ex... | # Generate an array of 4 binary label values, 3 positive and 1 negative
y_true = np.array(
[[1],
[1],
[1],
[0]])
print(f"y_true: \n{y_true}") | y_true:
[[1]
[1]
[1]
[0]]
| Apache-2.0 | 1_diagnosis/week1/lecture_exercise/AI4M_C1_W1_lecture_ex_02.ipynb | amitbcp/ai_for_medicine_specialisation |
Two modelsTo better understand the loss function, you will pretend that you have two models.- Model 1 always outputs a 0.9 for any example that it's given. - Model 2 always outputs a 0.1 for any example that it's given. | # Make model predictions that are always 0.9 for all examples
y_pred_1 = 0.9 * np.ones(y_true.shape)
print(f"y_pred_1: \n{y_pred_1}")
print()
y_pred_2 = 0.1 * np.ones(y_true.shape)
print(f"y_pred_2: \n{y_pred_2}") | y_pred_1:
[[0.9]
[0.9]
[0.9]
[0.9]]
y_pred_2:
[[0.1]
[0.1]
[0.1]
[0.1]]
| Apache-2.0 | 1_diagnosis/week1/lecture_exercise/AI4M_C1_W1_lecture_ex_02.ipynb | amitbcp/ai_for_medicine_specialisation |
Problems with the regular loss functionThe learning goal here is to notice that with a regular loss function (not a weighted loss), the model that always outputs 0.9 has a smaller loss (performs better) than model 2.- This is because there is a class imbalance, where 3 out of the 4 labels are 1.- If the data were perf... | loss_reg_1 = -1 * np.sum(y_true * np.log(y_pred_1)) + \
-1 * np.sum((1 - y_true) * np.log(1 - y_pred_1))
print(f"loss_reg_1: {loss_reg_1:.4f}")
loss_reg_2 = -1 * np.sum(y_true * np.log(y_pred_2)) + \
-1 * np.sum((1 - y_true) * np.log(1 - y_pred_2))
print(f"loss_reg_2: {loss_reg_2:.4f}")
... | When the model 1 always predicts 0.9, the regular loss is 2.6187
When the model 2 always predicts 0.1, the regular loss is 7.0131
| Apache-2.0 | 1_diagnosis/week1/lecture_exercise/AI4M_C1_W1_lecture_ex_02.ipynb | amitbcp/ai_for_medicine_specialisation |
Notice that the loss function gives a greater loss when the predictions are always 0.1, because the data is imbalanced, and has three labels of `1` but only one label for `0`.Given a class imbalance with more positive labels, the regular loss function implies that the model with the higher prediction of 0.9 performs be... | # calculate the positive weight as the fraction of negative labels
w_p = 1/4
# calculate the negative weight as the fraction of positive labels
w_n = 3/4
print(f"positive weight w_p: {w_p}")
print(f"negative weight w_n {w_n}") | positive weight w_p: 0.25
negative weight w_n 0.75
| Apache-2.0 | 1_diagnosis/week1/lecture_exercise/AI4M_C1_W1_lecture_ex_02.ipynb | amitbcp/ai_for_medicine_specialisation |
Model 1 weighted lossRun the next two cells to calculate the two loss terms separately.Here, `loss_1_pos` and `loss_1_neg` are calculated using the `y_pred_1` predictions. | # Calculate and print out the first term in the loss function, which we are calling 'loss_pos'
loss_1_pos = -1 * np.sum(w_p * y_true * np.log(y_pred_1 ))
print(f"loss_1_pos: {loss_1_pos:.4f}")
# Calculate and print out the second term in the loss function, which we're calling 'loss_neg'
loss_1_neg = -1 * np.sum(w_n * (... | loss_1: 1.8060
| Apache-2.0 | 1_diagnosis/week1/lecture_exercise/AI4M_C1_W1_lecture_ex_02.ipynb | amitbcp/ai_for_medicine_specialisation |
Model 2 weighted lossNow do the same calculations for when the predictions are from `y_pred_2'. Calculate the two terms of the weighted loss function and add them together. | # Calculate and print out the first term in the loss function, which we are calling 'loss_pos'
loss_2_pos = -1 * np.sum(w_p * y_true * np.log(y_pred_2))
print(f"loss_2_pos: {loss_2_pos:.4f}")
# Calculate and print out the second term in the loss function, which we're calling 'loss_neg'
loss_2_neg = -1 * np.sum(w_n * (1... | loss_2: 1.8060
| Apache-2.0 | 1_diagnosis/week1/lecture_exercise/AI4M_C1_W1_lecture_ex_02.ipynb | amitbcp/ai_for_medicine_specialisation |
Compare model 1 and model 2 weighted loss | print(f"When the model always predicts 0.9, the total loss is {loss_1:.4f}")
print(f"When the model always predicts 0.1, the total loss is {loss_2:.4f}") | When the model always predicts 0.9, the total loss is 1.8060
When the model always predicts 0.1, the total loss is 1.8060
| Apache-2.0 | 1_diagnosis/week1/lecture_exercise/AI4M_C1_W1_lecture_ex_02.ipynb | amitbcp/ai_for_medicine_specialisation |
What do you notice?Since you used a weighted loss, the calculated loss is the same whether the model always predicts 0.9 or always predicts 0.1. You may have also noticed that when you calculate each term of the weighted loss separately, there is a bit of symmetry when comparing between the two sets of predictions. | print(f"loss_1_pos: {loss_1_pos:.4f} \t loss_1_neg: {loss_1_neg:.4f}")
print()
print(f"loss_2_pos: {loss_2_pos:.4f} \t loss_2_neg: {loss_2_neg:.4f}") | loss_1_pos: 0.0790 loss_1_neg: 1.7269
loss_2_pos: 1.7269 loss_2_neg: 0.0790
| Apache-2.0 | 1_diagnosis/week1/lecture_exercise/AI4M_C1_W1_lecture_ex_02.ipynb | amitbcp/ai_for_medicine_specialisation |
Even though there is a class imbalance, where there are 3 positive labels but only one negative label, the weighted loss accounts for this by giving more weight to the negative label than to the positive label. Weighted Loss for more than one classIn this week's assignment, you will calculate the multi-class weighted ... | # View the labels (true values) that you will practice with
y_true = np.array(
[[1,0],
[1,0],
[1,0],
[1,0],
[0,1]
])
y_true | _____no_output_____ | Apache-2.0 | 1_diagnosis/week1/lecture_exercise/AI4M_C1_W1_lecture_ex_02.ipynb | amitbcp/ai_for_medicine_specialisation |
Choosing axis=0 or axis=1You will use `numpy.sum` to count the number of times column `0` has the value 0. First, notice the difference when you set axis=0 versus axis=1 | # See what happens when you set axis=0
print(f"using axis = 0 {np.sum(y_true,axis=0)}")
# Compare this to what happens when you set axis=1
print(f"using axis = 1 {np.sum(y_true,axis=1)}") | using axis = 0 [4 1]
using axis = 1 [1 1 1 1 1]
| Apache-2.0 | 1_diagnosis/week1/lecture_exercise/AI4M_C1_W1_lecture_ex_02.ipynb | amitbcp/ai_for_medicine_specialisation |
Notice that if you choose `axis=0`, the sum is taken for each of the two columns. This is what you want to do in this case. If you set `axis=1`, the sum is taken for each row. Calculate the weightsPreviously, you visually inspected the data to calculate the fraction of negative and positive labels. Here, you can do ... | # set the positive weights as the fraction of negative labels (0) for each class (each column)
w_p = np.sum(y_true == 0,axis=0) / y_true.shape[0]
w_p
# set the negative weights as the fraction of positive labels (1) for each class
w_n = np.sum(y_true == 1, axis=0) / y_true.shape[0]
w_n | _____no_output_____ | Apache-2.0 | 1_diagnosis/week1/lecture_exercise/AI4M_C1_W1_lecture_ex_02.ipynb | amitbcp/ai_for_medicine_specialisation |
In the assignment, you will train a model to try and make useful predictions. In order to make this example easier to follow, you will pretend that your model always predicts the same value for every example. | # Set model predictions where all predictions are the same
y_pred = np.ones(y_true.shape)
y_pred[:,0] = 0.3 * y_pred[:,0]
y_pred[:,1] = 0.7 * y_pred[:,1]
y_pred | _____no_output_____ | Apache-2.0 | 1_diagnosis/week1/lecture_exercise/AI4M_C1_W1_lecture_ex_02.ipynb | amitbcp/ai_for_medicine_specialisation |
As before, calculate the two terms that make up the loss function. Notice that you are working with more than one class (represented by columns). In this case, there are two classes.Start by calculating the loss for class `0`.$$ loss^{(i)} = loss_{pos}^{(i)} + los_{neg}^{(i)} $$$$loss_{pos}^{(i)} = -1 \times weight_{... | # Print and view column zero of the weight
print(f"w_p[0]: {w_p[0]}")
print(f"y_true[:,0]: {y_true[:,0]}")
print(f"y_pred[:,0]: {y_pred[:,0]}")
# calculate the loss from the positive predictions, for class 0
loss_0_pos = -1 * np.sum(w_p[0] *
y_true[:, 0] *
np.log(y_pred[:, 0])
... | loss_0_pos: 0.9632
| Apache-2.0 | 1_diagnosis/week1/lecture_exercise/AI4M_C1_W1_lecture_ex_02.ipynb | amitbcp/ai_for_medicine_specialisation |
View the zero column for the weights, true values, and predictions that you will use to calculate the loss from the negative predictions. | # Print and view column zero of the weight
print(f"w_n[0]: {w_n[0]}")
print(f"y_true[:,0]: {y_true[:,0]}")
print(f"y_pred[:,0]: {y_pred[:,0]}")
# Calculate the loss from the negative predictions, for class 0
loss_0_neg = -1 * np.sum(
w_n[0] *
(1 - y_true[:, 0]) *
np.lo... | loss_0: 1.2485
| Apache-2.0 | 1_diagnosis/week1/lecture_exercise/AI4M_C1_W1_lecture_ex_02.ipynb | amitbcp/ai_for_medicine_specialisation |
Now you are familiar with the array slicing that you would use when there are multiple disease classes stored in a two-dimensional array. Now it's your turn!* Can you calculate the loss for class (column) `1`? | # calculate the loss from the positive predictions, for class 1
loss_1_pos = None | _____no_output_____ | Apache-2.0 | 1_diagnosis/week1/lecture_exercise/AI4M_C1_W1_lecture_ex_02.ipynb | amitbcp/ai_for_medicine_specialisation |
Expected output```CPPloss_1_pos: 0.2853``` | # Calculate the loss from the negative predictions, for class 1
loss_1_neg = None | _____no_output_____ | Apache-2.0 | 1_diagnosis/week1/lecture_exercise/AI4M_C1_W1_lecture_ex_02.ipynb | amitbcp/ai_for_medicine_specialisation |
Expected output```CPPloss_1_neg: 0.9632``` | # add the two loss terms to get the total loss for class 0
loss_1 = None | _____no_output_____ | Apache-2.0 | 1_diagnosis/week1/lecture_exercise/AI4M_C1_W1_lecture_ex_02.ipynb | amitbcp/ai_for_medicine_specialisation |
LightGBM Model作者:艾宏峰创建时间:2020.11.15 | import gc
import pandas as pd
import lightgbm as lgb
import numpy as np
from datetime import datetime
from tqdm import tqdm
from sklearn.model_selection import StratifiedKFold, TimeSeriesSplit
from sklearn.metrics import accuracy_score
import copy
import warnings
warnings.filterwarnings("ignore") | _____no_output_____ | MIT | lightgbm_cu_20201123.ipynb | AlvinAi96/serverless_prediction |
LGBMRegressor有下列参数可调整:- boosting_type(gbdt):提升方法,默认是gbdt。有四种:(1)gbdt:传统梯度提升决策树。(2)rf:随机森林。(3)dart:Dropouts meet Multiple Additive Regression Trees。(4)goss:Gradient-based One-Side Sampling。- num_leaves(31):数的最大叶子数量。- max_depth(-1):树的最大深度。- learning_rate(0.1):学习率。- n_estimators(100):提升树数量。- subsample_for_bin(200000):构建bi... | # LightGBM参数
params = {
'metric':'mse',
'objective':'regression',
'seed':2022,
'boosting_type':'gbdt', # 也可用其他的,一个个试着先,dart不支持early stopping
'early_stopping_rounds':10,
'subsample':0.8,
'feature_fraction':0.75,
'bagging_fraction': 0.75,
'reg_lambda': 10
}
verbose_flag = False # 是否展... | _____no_output_____ | MIT | lightgbm_cu_20201123.ipynb | AlvinAi96/serverless_prediction |
process image detect | import cv2
import numpy as np
import torch
import torchvision
import os.path as osp
from mot_neural_solver.path_cfg import OUTPUT_PATH, DATA_PATH
from torchvision.models.detection.faster_rcnn import FastRCNNPredictor
import matplotlib.pyplot as plt
num_classes = 2
_config = {'dataset_dir': 'synthShrimps/test', 'train_... | prediction
| MIT | test_object_detection.ipynb | OpenSuze/mot_neural_solver |
Inheritance | from random import randrange
# Here's the original Pet class
class Pet():
boredom_decrement = 4
hunger_decrement = 6
boredom_threshold = 5
hunger_threshold = 10
sounds = ['Mrrp']
def __init__(self, name = "Kitty"):
self.name = name
self.hunger = randrange(self.hunger_threshold)
... | _____no_output_____ | MIT | Class ,Constractor,Inheritance,overriding,Exception.ipynb | Ks226/upgard_code |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.