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
Here, pass in the path to a checkpoint and sample from the network.
tf.train.latest_checkpoint('checkpoints') checkpoint = tf.train.latest_checkpoint('checkpoints') samp = sample(checkpoint, 2000, lstm_size, len(vocab), prime="Far") print(samp) checkpoint = 'checkpoints/i200_l512.ckpt' samp = sample(checkpoint, 1000, lstm_size, len(vocab), prime="Far") print(samp) checkpoint = 'checkpo...
_____no_output_____
MIT
intro-to-rnns/Anna_KaRNNa_Solution.ipynb
ys3x/deep-learning
desafio 1: Encontre os 18 filmes que não tiveram avaliação
filmes_com_media = filmes.join(notas_media_por_filme, on = "filmeid") filmes_com_media.head()
_____no_output_____
MIT
DataSciencefilmes.ipynb
KazumaShachou/DataSciencePython
desafio 2mudar o nome da coluna nota para media apos o join
filmes_com_media.sort_values("nota", ascending=False).head(15)
_____no_output_____
MIT
DataSciencefilmes.ipynb
KazumaShachou/DataSciencePython
desafio 3coloque o numero de avaliações por filme
import matplotlib.pyplot as plt avaliacoes.query("filmeid == 1")["nota"].plot(kind = 'hist', title= "avaliações do filme toy story") #plt.title("Avaliações do filme toy story") plt.show() avaliacoes.query("filmeid == 1")["nota"].plot(kind = 'hist') avaliacoes.query("filmeid == 2...
_____no_output_____
MIT
DataSciencefilmes.ipynb
KazumaShachou/DataSciencePython
desafio4arredondar o valor da coluna de nota media em 2 casas desafio5 descobrir os generos de filmes(quais são eles, unicos) (esse daqui o bicho pega) desafio6contar o numero de aparições de cada genero. desafio7plotar o gráfico de aparições por genero, pode ser um gráfico de tipo igual a barra
_____no_output_____
MIT
DataSciencefilmes.ipynb
KazumaShachou/DataSciencePython
Aula 2
filmes["generos"].str.get_dummies('|').sum() #srt é string, para cortar a parte que você quer, get dummies cria variaveis que true é 1 e 0 falso, por ultimo o | é para separação, por ultimo "sum" é somar generos filmes["generos"].str.get_dummies('|').sum().sort_values(ascending=False) #ordenar por ordem decrescente g...
_____no_output_____
MIT
DataSciencefilmes.ipynb
KazumaShachou/DataSciencePython
_____no_output_____
MIT
DataSciencefilmes.ipynb
KazumaShachou/DataSciencePython
Since accuracy is not that great, we will use a pre-trained model with transfer learning.
train_batches1 = ImageDataGenerator(preprocessing_function=tf.keras.applications.vgg16.preprocess_input) \ .flow_from_dataframe( train_df, "/kaggle/working/train", x_col='filename', y_col='category', class_mode='binary', target_size=(224, 224), batch_size=124) valid_batches1 = ImageDa...
Model: "vgg16" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= input_1 (InputLayer) [(None, 224, 224, 3)] 0 _________________________________________...
Apache-2.0
dogs-vs-cats-transfer-learning.ipynb
saptarshidatta96/Transfer-Learning-with-VGG-16
Removing the Last Layer
model = Sequential() for layer in vgg16_model.layers[:-1]: model.add(layer) model.summary() for layer in model.layers: layer.trainable = False model.add(Dense(units=1, activation='sigmoid')) model.summary() model.compile(optimizer=Adam(learning_rate=0.0001), loss='binary_crossentropy', ...
Epoch 1/3 182/182 - 114s - loss: 0.2074 - accuracy: 0.9144 - val_loss: 0.0748 - val_accuracy: 0.9764 Epoch 2/3 182/182 - 112s - loss: 0.0647 - accuracy: 0.9785 - val_loss: 0.0541 - val_accuracy: 0.9800 Epoch 3/3 182/182 - 111s - loss: 0.0519 - accuracy: 0.9826 - val_loss: 0.0470 - val_accuracy: 0.9832
Apache-2.0
dogs-vs-cats-transfer-learning.ipynb
saptarshidatta96/Transfer-Learning-with-VGG-16
Predict
results = model.predict(test_batches) test_df['category'] = np.where(results > 0.5, 1,0)
_____no_output_____
Apache-2.0
dogs-vs-cats-transfer-learning.ipynb
saptarshidatta96/Transfer-Learning-with-VGG-16
Submission
submission_df = test_df.copy() submission_df['id'] = submission_df['filename'].str.split('.').str[0] submission_df['label'] = submission_df['category'] submission_df.drop(['filename', 'category'], axis=1, inplace=True) submission_df.to_csv('submission.csv', index=False)
_____no_output_____
Apache-2.0
dogs-vs-cats-transfer-learning.ipynb
saptarshidatta96/Transfer-Learning-with-VGG-16
Import Dependencies
import numpy as np import pandas as pd import matplotlib.pyplot as plt import matplotlib.ticker as ticker # scaling and dataset split from sklearn import preprocessing from sklearn.model_selection import train_test_split # OLS, Ridge from sklearn.linear_model import LinearRegression, Ridge # model evaluation from skle...
_____no_output_____
CC-BY-3.0
RF_model_with_PCA.ipynb
shilpiray/ML_Project
Read the CSV and Perform Basic Data Cleaning
data_to_load = "new_folder/googleplaystore.csv" df_apps = pd.read_csv(data_to_load) categories = list(df_apps["Category"].unique()) #Remove Category 1.9 categories.remove('1.9') a = df_apps.loc[df_apps["Category"] == "1.9"] df_apps = df_apps.drop(int(a.index.values),axis=0) #df_apps = df_apps[df_apps['Category']!= "1...
_____no_output_____
CC-BY-3.0
RF_model_with_PCA.ipynb
shilpiray/ML_Project
Split the data into training and testing
from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42) from sklearn.preprocessing import LabelEncoder, MinMaxScaler X_scaler = MinMaxScaler().fit(X_train) X_train_scaled = X_scaler.transform(X_train) X_test_scaled = X_scaler.transform(X_test)
_____no_output_____
CC-BY-3.0
RF_model_with_PCA.ipynb
shilpiray/ML_Project
SVC Model
# Support vector machine linear classifier from sklearn.svm import SVC model = SVC(kernel='linear') model.fit(X_train_scaled, y_train) print('Test Acc: %.3f' % model.score(X_test_scaled, y_test)) print(f"Training Data Score: {model.score(X_train_scaled, y_train)}") print(f"Testing Data Score: {model.score(X_test_scale...
_____no_output_____
CC-BY-3.0
RF_model_with_PCA.ipynb
shilpiray/ML_Project
Random Forest Model
from sklearn import tree clf = tree.DecisionTreeClassifier() clf = clf.fit(X_train, y_train) print('Test_score:', clf.score(X_test, y_test)) print('Train_score:', clf.score(X_train, y_train)) clf = tree.DecisionTreeClassifier() clf = clf.fit(X_train_scaled, y_train) print('Test_score:', clf.score(X_test_scaled, y_test)...
_____no_output_____
CC-BY-3.0
RF_model_with_PCA.ipynb
shilpiray/ML_Project
Hyperparameter Tuning
# Create the GridSearch estimator along with a parameter object containing the values to adjust from sklearn.model_selection import GridSearchCV param_grid = {'n_estimators':[100,200,300,400,500,600,700,800,900,1000], 'max_depth':[1,5,10,15,20]} grid = GridSearchCV(rf,param_grid,verbose=3) grid.fit(X_trai...
_____no_output_____
CC-BY-3.0
RF_model_with_PCA.ipynb
shilpiray/ML_Project
Remove least imp features
X_red = popAppsCopy.drop(["Genres","Category","Installs","Content Rating","Genres"], axis = 1) y_red = popApps["Installs"] y = y_red.replace({1:'1000+',5: '1000+', 10: '1000+',50:'1000+',100:'1000+',500:'1000+', 1000: '1000+',5000:'10000+',10000: '10000+', 50000:'100000+',100000:'100000+', ...
_____no_output_____
CC-BY-3.0
RF_model_with_PCA.ipynb
shilpiray/ML_Project
PCA
X.head() from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0) from sklearn.preprocessing import StandardScaler sc = StandardScaler() X_train = sc.fit_transform(X_train) X_test = sc.transform(X_test) from sklearn.decomposition imp...
Accuracy 0.27262507026419336
CC-BY-3.0
RF_model_with_PCA.ipynb
shilpiray/ML_Project
Remove the least 2 values from knee effect
X_knee = X.drop(["Content Rating_Adults only 18+","Content Rating_Unrated"], axis = 1) y_knee = y print(X_knee.shape, y_knee.shape) from sklearn.model_selection import train_test_split X_train_k, X_test_k, y_train_k, y_test_k = train_test_split(X_knee, y_knee, random_state=42) from sklearn.preprocessing import LabelE...
_____no_output_____
CC-BY-3.0
RF_model_with_PCA.ipynb
shilpiray/ML_Project
Regression on Decison Trees and Random Forest
#importing important libraries #libraries for reading dataset import numpy as np import pandas as pd #libraries for data visualisation import matplotlib.pyplot as plt import seaborn as sns #libraries for model building and understanding import sklearn from sklearn.model_selection import train_test_split #importing ...
_____no_output_____
Apache-2.0
Geely Auto-Boosting(Regression).ipynb
ridhimanwazir/Boosting-Regression
Reading Data
cp = pd.read_csv('carprice.csv')
_____no_output_____
Apache-2.0
Geely Auto-Boosting(Regression).ipynb
ridhimanwazir/Boosting-Regression
Understanding the data
cp.head() cp.shape cp.info() cp.describe() #symboling is a categorical data so we convert to the specified type cp['symboling'] = cp['symboling'].apply(str)
_____no_output_____
Apache-2.0
Geely Auto-Boosting(Regression).ipynb
ridhimanwazir/Boosting-Regression
There are 11 categorical data and remaining are the numerical data
#as per the bussiness requirements we only need name of the carcompany and not the carmodel #so we drop carmodel and only keep carCompany cp['CarName'] = cp['CarName'].str.lower() cp['carCompany'] = cp['CarName'].str.split(' ').str[0] cp = cp.drop('CarName',axis = 1) cp.head()
_____no_output_____
Apache-2.0
Geely Auto-Boosting(Regression).ipynb
ridhimanwazir/Boosting-Regression
Data visualization and understanding using EDA Price is a dependent variable Visualising numerical data
#Finding correlation cor = cp.corr() cor # visulaising correlation using heatmap plt.subplots(figsize=(20, 20)) plt.title('Correlation between each data variable') sns.heatmap(cor, xticklabels=cor.columns.values, yticklabels=cor.columns.values,annot= True,linecolor="black",linewidths=2, cmap="viridis") plt....
_____no_output_____
Apache-2.0
Geely Auto-Boosting(Regression).ipynb
ridhimanwazir/Boosting-Regression
`citympg` and `highwaympg` have negative correlation with price`carlength`,`carwidth`,`curbweight`,`enginesize` and `horsepower` have positve correlation with price
#scatter plot for numerical data with yaxis fixed as price plt.figure(figsize=[18,12]) plt.subplot(3,3,1) plt.scatter(cp.wheelbase, cp.price) plt.title('wheelbase vs price') plt.subplot(3,3,2) plt.scatter(cp.peakrpm, cp.price) plt.title('peakrpm vs price') plt.subplot(3,3,3) plt.scatter(cp.carheight, cp.price) plt.ti...
0.841118268481846 0.9713370423425061
Apache-2.0
Geely Auto-Boosting(Regression).ipynb
ridhimanwazir/Boosting-Regression
Visualising categorical data
plt.figure(figsize=(20, 15)) plt.subplot(3,3,1) sns.countplot(cp.fueltype) plt.subplot(3,3,2) sns.countplot(cp.aspiration) plt.subplot(3,3,3) sns.countplot(cp.doornumber) plt.subplot(3,3,4) sns.countplot(cp.drivewheel) plt.subplot(3,3,5) sns.countplot(cp.carbody) plt.subplot(3,3,6) sns.countplot(cp.enginelocation...
_____no_output_____
Apache-2.0
Geely Auto-Boosting(Regression).ipynb
ridhimanwazir/Boosting-Regression
`ohc` is the most preferred enginetypemost cars have `four cylinders``sedan` and `hatchback` are most common carbodymost cars prefer `gas` fueltype
plt.figure(figsize=(30,25)) plt.subplot(2,1,1) sns.countplot(cp.fuelsystem) plt.subplot(2,1,2) sns.countplot(cp.carCompany) plt.show()
_____no_output_____
Apache-2.0
Geely Auto-Boosting(Regression).ipynb
ridhimanwazir/Boosting-Regression
`mpfi` and `2bbl` are most common fuelsystem`Toyota` is most favoured carcompany we can observe that numerous carcompanies are misspelled
# replcaing incorrect carcompanies with correct ones so we replace them with correct spellings cp['carCompany'] = cp['carCompany'].str.replace('vok','volk') cp['carCompany'] = cp['carCompany'].str.replace('ou','o') cp['carCompany'] = cp['carCompany'].str.replace('cshce','sche') cp['carCompany'] = cp['carCompany'].str....
_____no_output_____
Apache-2.0
Geely Auto-Boosting(Regression).ipynb
ridhimanwazir/Boosting-Regression
`ohcv` are most expensive of the enginetype`doornumber` don't have much impact on the price`hardtop` and `covertible` are most expensive among the carbodycars that are `rwd` have higher price
plt.figure(figsize=(30,25)) plt.subplot(2,1,1) sns.boxplot(x = 'fuelsystem',y='price', data = cp) plt.subplot(2,1,2) sns.boxplot(x = 'carCompany',y='price', data = cp) plt.show()
_____no_output_____
Apache-2.0
Geely Auto-Boosting(Regression).ipynb
ridhimanwazir/Boosting-Regression
`buick`, `jaguar`, `porsche` and `bmw` are most expensive carCompany`mpfi` and `idi` having the highest price range. Encoding categorical data
#defining fucntion for binary encoding of features with only 2 types of data def number_map(x): return x.map({'gas':1,'diesel':0,'std':0,'turbo':1,'two':0,'four':1,'front':0,'rear':1}) cp[['aspiration']] =cp[['aspiration']].apply(number_map) cp[['doornumber']] =cp[['doornumber']].apply(number_map) cp[['fueltype']]...
_____no_output_____
Apache-2.0
Geely Auto-Boosting(Regression).ipynb
ridhimanwazir/Boosting-Regression
Splitting data into test and train datasets
#splitting the data into test and train for evaluation # taking the test data as 30% and train data as 70% X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
_____no_output_____
Apache-2.0
Geely Auto-Boosting(Regression).ipynb
ridhimanwazir/Boosting-Regression
Gradient Boosting
# fitting the model on train data model = GradientBoostingRegressor() gbr = model.fit(X_train,y_train) # predicting on test data y_pred = gbr.predict(X_test) # checking the goodness of the model metrics.r2_score(y_test, y_pred)
_____no_output_____
Apache-2.0
Geely Auto-Boosting(Regression).ipynb
ridhimanwazir/Boosting-Regression
Hyper parameter tuning
# hyper parameter tuning for GBR GBR = GradientBoostingRegressor() param_dist = {"learning_rate": np.linspace(0.05, 0.15,5),"subsample": [0.3, 0.6, 0.9]} rand = RandomizedSearchCV(GBR, param_dist, cv=5,n_iter=10, random_state=100) rand.fit(X_train,y_train) print(rand.best_params_) GBR = GradientBoostingRegressor(lear...
_____no_output_____
Apache-2.0
Geely Auto-Boosting(Regression).ipynb
ridhimanwazir/Boosting-Regression
XGboost
# fitting XGB on training data XGB = XGBRegressor() XGB = XGB.fit(X_train,y_train) # predicting on test data Y_pred = XGB.predict(X_test) np.sqrt(mean_squared_log_error(y_test,Y_pred)) # checking the goodness of the model metrics.r2_score(y_test, Y_pred) importance = XGB.feature_importances_ # plotting feature importan...
_____no_output_____
Apache-2.0
Geely Auto-Boosting(Regression).ipynb
ridhimanwazir/Boosting-Regression
Hyperparameter tuning
# hyper parameter tuning for XGB XGB = XGBRegressor() param_grid = {"learning_rate": np.linspace(0.05, 0.15,5), "subsample": [0.3, 0.6, 0.9]} rand = RandomizedSearchCV(XGB, param_grid, cv=5,n_iter=10, random_state=100) rand.fit(X_train,y_train) print(rand.best_params_) xgb = XGBRegressor(learning_rat...
_____no_output_____
Apache-2.0
Geely Auto-Boosting(Regression).ipynb
ridhimanwazir/Boosting-Regression
Data Preprocessing
df = pd.read_csv('Iris.csv') df2 = df.drop(['Id', 'SepalLengthCm', 'PetalLengthCm'], axis=1) df2['Species'].replace(to_replace=['Iris-setosa', 'Iris-virginica', 'Iris-versicolor'], value=[1., -1., -1.], inplace=True) df2.head() x = df2[['SepalWidthCm', 'PetalWidthCm']].values y = df2['Species'].values # Plot the train...
_____no_output_____
MIT
Lecture 2/Iris Classification with Perceptron.ipynb
GO-Loc-GO/MIT-ML-and-CV
In this note book the following steps are taken:1. Remove highly correlated attributes2. Find the best hyper parameters for estimator3. Find the most important features by tunned random forest4. Find f1 score of the tunned full model5. Find best hyper parameter of model with selected features6. Find f1 score of the tu...
import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from sklearn.feature_selection import RFECV,RFE from sklearn.model_selection import train_test_split, GridSearchCV, KFold,RandomizedSearchCV from sklearn.preprocessing import StandardScaler from sklearn.pipeline import Pipeline...
_____no_output_____
Unlicense
RandomForest-RFECV-BreakStatus-Halifax-RandomizedSearch.ipynb
SadafGharaati/Important-factors
Anailís ghramadaí trí [deplacy](https://koichiyasuoka.github.io/deplacy/) le [Stanza](https://stanfordnlp.github.io/stanza)
!pip install deplacy stanza import stanza stanza.download("ga") nlp=stanza.Pipeline("ga") doc=nlp("Táimid faoi dhraíocht ag ceol na farraige.") import deplacy deplacy.render(doc) deplacy.serve(doc,port=None) # import graphviz # graphviz.Source(deplacy.dot(doc))
_____no_output_____
MIT
doc/ga.ipynb
KoichiYasuoka/deplacy
le [UDPipe 2](http://ufal.mff.cuni.cz/udpipe/2)
!pip install deplacy def nlp(t): import urllib.request,urllib.parse,json with urllib.request.urlopen("https://lindat.mff.cuni.cz/services/udpipe/api/process?model=ga&tokenizer&tagger&parser&data="+urllib.parse.quote(t)) as r: return json.loads(r.read())["result"] doc=nlp("Táimid faoi dhraíocht ag ceol na farrai...
_____no_output_____
MIT
doc/ga.ipynb
KoichiYasuoka/deplacy
le [COMBO-pytorch](https://gitlab.clarin-pl.eu/syntactic-tools/combo)
!pip install --index-url https://pypi.clarin-pl.eu/simple deplacy combo import combo.predict nlp=combo.predict.COMBO.from_pretrained("irish-ud27") doc=nlp("Táimid faoi dhraíocht ag ceol na farraige.") import deplacy deplacy.render(doc) deplacy.serve(doc,port=None) # import graphviz # graphviz.Source(deplacy.dot(doc))
_____no_output_____
MIT
doc/ga.ipynb
KoichiYasuoka/deplacy
le [Trankit](https://github.com/nlp-uoregon/trankit)
!pip install deplacy trankit transformers import trankit nlp=trankit.Pipeline("irish") doc=nlp("Táimid faoi dhraíocht ag ceol na farraige.") import deplacy deplacy.render(doc) deplacy.serve(doc,port=None) # import graphviz # graphviz.Source(deplacy.dot(doc))
_____no_output_____
MIT
doc/ga.ipynb
KoichiYasuoka/deplacy
le [spacy-udpipe](https://github.com/TakeLab/spacy-udpipe)
!pip install deplacy spacy-udpipe import spacy_udpipe spacy_udpipe.download("ga") nlp=spacy_udpipe.load("ga") doc=nlp("Táimid faoi dhraíocht ag ceol na farraige.") import deplacy deplacy.render(doc) deplacy.serve(doc,port=None) # import graphviz # graphviz.Source(deplacy.dot(doc))
_____no_output_____
MIT
doc/ga.ipynb
KoichiYasuoka/deplacy
le [spaCy-COMBO](https://github.com/KoichiYasuoka/spaCy-COMBO)
!pip install deplacy spacy_combo import spacy_combo nlp=spacy_combo.load("ga_idt") doc=nlp("Táimid faoi dhraíocht ag ceol na farraige.") import deplacy deplacy.render(doc) deplacy.serve(doc,port=None) # import graphviz # graphviz.Source(deplacy.dot(doc))
_____no_output_____
MIT
doc/ga.ipynb
KoichiYasuoka/deplacy
le [spaCy-jPTDP](https://github.com/KoichiYasuoka/spaCy-jPTDP)
!pip install deplacy spacy_jptdp import spacy_jptdp nlp=spacy_jptdp.load("ga_idt") doc=nlp("Táimid faoi dhraíocht ag ceol na farraige.") import deplacy deplacy.render(doc) deplacy.serve(doc,port=None) # import graphviz # graphviz.Source(deplacy.dot(doc))
_____no_output_____
MIT
doc/ga.ipynb
KoichiYasuoka/deplacy
le [Camphr-Udify](https://camphr.readthedocs.io/en/latest/notes/udify.html)
!pip install deplacy camphr en-udify@https://github.com/PKSHATechnology-Research/camphr_models/releases/download/0.7.0/en_udify-0.7.tar.gz import pkg_resources,imp imp.reload(pkg_resources) import spacy nlp=spacy.load("en_udify") doc=nlp("Táimid faoi dhraíocht ag ceol na farraige.") import deplacy deplacy.render(doc) d...
_____no_output_____
MIT
doc/ga.ipynb
KoichiYasuoka/deplacy
MMClassification Python API tutorial on ColabIn this tutorial, we will introduce the following content:* How to install MMCls* Inference a model with Python API* Fine-tune a model with Python API Install MMClassificationBefore using MMClassification, we need to prepare the environment with the following steps:1. Ins...
%cd /content !pwd # Check nvcc version !nvcc -V # Check GCC version !gcc --version # Check PyTorch installation import torch, torchvision print(torch.__version__) print(torch.cuda.is_available())
1.9.0+cu111 True
Apache-2.0
docs/en/tutorials/MMClassification_python.ipynb
HXZhong1997/mmclassification
Install MMCVMMCV is the basic package of all OpenMMLab packages. We have pre-built wheels on Linux, so we can download and install them directly.Please pay attention to PyTorch and CUDA versions to match the wheel.In the above steps, we have checked the version of PyTorch and CUDA, and they are 1.9.0 and 11.1 respecti...
# Install mmcv !pip install mmcv -f https://download.openmmlab.com/mmcv/dist/cu111/torch1.9.0/index.html # !pip install mmcv-full -f https://download.openmmlab.com/mmcv/dist/cu110/torch1.9.0/index.html
Looking in links: https://download.openmmlab.com/mmcv/dist/cu111/torch1.9.0/index.html Collecting mmcv Downloading mmcv-1.3.15.tar.gz (352 kB)  |████████████████████████████████| 352 kB 5.2 MB/s [?25hCollecting addict Downloading addict-2.4.0-py3-none-any.whl (3.8 kB) Requirement already satisfied: numpy i...
Apache-2.0
docs/en/tutorials/MMClassification_python.ipynb
HXZhong1997/mmclassification
Clone and install MMClassificationNext, we clone the latest mmcls repository from GitHub and install it.
# Clone mmcls repository !git clone https://github.com/open-mmlab/mmclassification.git %cd mmclassification/ # Install MMClassification from source !pip install -e . # Check MMClassification installation import mmcls print(mmcls.__version__)
0.16.0
Apache-2.0
docs/en/tutorials/MMClassification_python.ipynb
HXZhong1997/mmclassification
Inference a model with Python APIMMClassification provides many pre-trained models, and you can check them by the link of [model zoo](https://mmclassification.readthedocs.io/en/latest/model_zoo.html). Almost all models can reproduce the results in original papers or reach higher metrics. And we can use these models di...
# Get the demo image !wget https://www.dropbox.com/s/k5fsqi6qha09l1v/banana.png?dl=0 -O demo/banana.png from PIL import Image Image.open('demo/banana.png')
_____no_output_____
Apache-2.0
docs/en/tutorials/MMClassification_python.ipynb
HXZhong1997/mmclassification
Prepare the config file and checkpoint fileWe configure a model with a config file and save weights with a checkpoint file.On GitHub, you can find all these pre-trained models in the config folder of MMClassification. For example, you can find the config files and checkpoints of Mobilenet V2 in [this link](https://git...
# Confirm the config file exists !ls configs/mobilenet_v2/mobilenet-v2_8xb32_in1k.py # Specify the path of the config file and checkpoint file. config_file = 'configs/mobilenet_v2/mobilenet-v2_8xb32_in1k.py' checkpoint_file = 'https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagen...
configs/mobilenet_v2/mobilenet-v2_8xb32_in1k.py
Apache-2.0
docs/en/tutorials/MMClassification_python.ipynb
HXZhong1997/mmclassification
Inference the modelMMClassification provides high-level Python API to inference models.At first, we build the MobilenetV2 model and load the checkpoint.
import mmcv from mmcls.apis import inference_model, init_model, show_result_pyplot # Specify the device, if you cannot use GPU, you can also use CPU # by specifying `device='cpu'`. device = 'cuda:0' # device = 'cpu' # Build the model according to the config file and load the checkpoint. model = init_model(config_fil...
_____no_output_____
Apache-2.0
docs/en/tutorials/MMClassification_python.ipynb
HXZhong1997/mmclassification
Fine-tune a model with Python APIFine-tuning is to re-train a model which has been trained on another dataset (like ImageNet) to fit our target dataset. Compared with training from scratch, fine-tuning is much faster can avoid over-fitting problems during training on a small dataset.The basic steps of fine-tuning are ...
# Download the cats & dogs dataset !wget https://www.dropbox.com/s/wml49yrtdo53mie/cats_dogs_dataset_reorg.zip?dl=0 -O cats_dogs_dataset.zip !mkdir -p data !unzip -qo cats_dogs_dataset.zip -d ./data/
--2021-10-21 03:57:58-- https://www.dropbox.com/s/wml49yrtdo53mie/cats_dogs_dataset_reorg.zip?dl=0 Resolving www.dropbox.com (www.dropbox.com)... 162.125.80.18, 2620:100:6018:18::a27d:312 Connecting to www.dropbox.com (www.dropbox.com)|162.125.80.18|:443... connected. HTTP request sent, awaiting response... 301 Moved ...
Apache-2.0
docs/en/tutorials/MMClassification_python.ipynb
HXZhong1997/mmclassification
Read the config file and modify the configIn the [tools tutorial](https://colab.research.google.com/github/open-mmlab/mmclassification/blob/master/docs/tutorials/MMClassification_tools.ipynb), we have introduced all parts of the config file, and here we can modify the loaded config by Python code.
# Load the base config file from mmcv import Config cfg = Config.fromfile('configs/mobilenet_v2/mobilenet-v2_8xb32_in1k.py') # Modify the number of classes in the head. cfg.model.head.num_classes = 2 cfg.model.head.topk = (1, ) # Load the pre-trained model's checkpoint. cfg.model.backbone.init_cfg = dict(type='Pretra...
_____no_output_____
Apache-2.0
docs/en/tutorials/MMClassification_python.ipynb
HXZhong1997/mmclassification
Fine-tune the modelUse the API `train_model` to fine-tune our model on the cats & dogs dataset.
import time import mmcv import os.path as osp from mmcls.datasets import build_dataset from mmcls.models import build_classifier from mmcls.apis import train_model # Create the work directory mmcv.mkdir_or_exist(osp.abspath(cfg.work_dir)) # Build the classifier model = build_classifier(cfg.model) model.init_weights()...
_____no_output_____
Apache-2.0
docs/en/tutorials/MMClassification_python.ipynb
HXZhong1997/mmclassification
Análise de Drugs Discovery - Imersão Dados AluraDesafio 1: Investigar por que a classe tratamento é tão desbalanceada
import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt %matplotlib inline url_dados = 'https://github.com/alura-cursos/imersaodados3/blob/main/dados/dados_experimentos.zip?raw=true' dados = pd.read_csv(url_dados, compression = 'zip') #compression = 'zip' serve par aarquivos que es...
_____no_output_____
MIT
aula05_imersao_alura_dados.ipynb
EnzoGolfetti/imersaoalura_dados_3
Cada linha é um experimento de cultura de células que foi submetida a alguma droga com determinada dosagem e por determinada quantidade de tempo.
dados.info() #para ver as primeiras infos dos dados, número de index (linhas) #colunas # e tipo dos dados, no caso são 872 de float64, 1 de int64 e 4 object (string) dados.isnull().sum() #o .isnull .summ serve para somar por coluna os valores nulos, da um parecer inicial sobre quais colunas tem nulos e dar uma ideia #d...
_____no_output_____
MIT
aula05_imersao_alura_dados.ipynb
EnzoGolfetti/imersaoalura_dados_3
Os tratamentos tem expressiva quantidade de experimentos 'com_droga' e apenas 1866 de 23814 sendo 'com_controle'. Com controle significa, aqueles que não recebem os tratamentos para testar como os com experimento reagiram a droga, para saber que foi a droga que mudou a resposta, temos que ter o grupo controle que estej...
#próxima variável a ser analisada = tempo dados['tempo'] dados['tempo'].value_counts()
_____no_output_____
MIT
aula05_imersao_alura_dados.ipynb
EnzoGolfetti/imersaoalura_dados_3
Podemos ver que o tempo está disposto em unidades de 'hora', respectivamente:24, 48, 72.48 horas foi a maioria do tempo observado nos experimentos, e 24 horas a que menos foi (segundo a bióloga da imersão, devido a que, muitas vezes, 24 horas não é o suficiente para as células desenvolverem respostas à droga aplicada.
dados['dose'].value_counts()
_____no_output_____
MIT
aula05_imersao_alura_dados.ipynb
EnzoGolfetti/imersaoalura_dados_3
Observamos que tem apenas dois tipos doses (D1, D2), D1 tendo a maioria dos registros - 12147
dados['droga'].value_counts()
_____no_output_____
MIT
aula05_imersao_alura_dados.ipynb
EnzoGolfetti/imersaoalura_dados_3
Nas drogas, podemos ver que a droga 'cacb2b860' foi a mais usada (1866 vezes)E a droga '87d714366' foi a segunda mais usada com 718 vezes.O nome das drogas, é "confuso", pois foram anonimizados para evitar vieses nas análises.O total de drogas investigados foi de 3289 (registrado em 'length')
dados['g-0'].value_counts()
_____no_output_____
MIT
aula05_imersao_alura_dados.ipynb
EnzoGolfetti/imersaoalura_dados_3
Os 'g' são abreviação de genes, portanto, existem observações das respostas de vários deles, que estão dispostos nas colunas, e os valores que vemos é a expressão dos genes frente à droga, dose e tempo de exposição. Os valores provavelmente estão normalizados para permitir o entendimento e a comparação deles
#contando quantos valores maiores que 0, temos em 'g-0' dados[dados['g-0'] > 0].count() #máscara para os dados g-0 maiores que '0' dados_g0_maior_zero = dados[dados['g-0'] > 0] dados_g0_maior_zero.head()
_____no_output_____
MIT
aula05_imersao_alura_dados.ipynb
EnzoGolfetti/imersaoalura_dados_3
Desafio 2: Plotar as últimas 5 linhas do Dataframe
#plotando últimas 5 linhas dados.iloc[23809:,:]
_____no_output_____
MIT
aula05_imersao_alura_dados.ipynb
EnzoGolfetti/imersaoalura_dados_3
Desafio 3: Registrar a proporção da classe tratamento
#usando método matemático (dados['tratamento'].value_counts() * 100) / 23814 #usando função value_counts do Pandas dados['tratamento'].value_counts(normalize=True) #o normalize nos dá os porcent deles
_____no_output_____
MIT
aula05_imersao_alura_dados.ipynb
EnzoGolfetti/imersaoalura_dados_3
É interessante termos um comparativo com dados da própria tabela, porém de outras colunas, nesse caso, vamos comparar com a distribuição das doses
dados['dose'].value_counts(normalize=True) #plotando gráfico de pizza para mostrar as proporções dos valores em tratamento fig, ax = plt.subplots(figsize=(20,6)) labels = ['com_droga', 'com_controle'] ax.pie(dados['tratamento'].value_counts(normalize=True), labels=labels, autopct='%1.1f%%') ax.set_title('Distribuição d...
_____no_output_____
MIT
aula05_imersao_alura_dados.ipynb
EnzoGolfetti/imersaoalura_dados_3
Observando graficamente os valores de tempo
barplot_time = dados['tempo'].value_counts().plot.bar() barplot_time.set_title('Distribuição dos experimentos por tempo') barplot_time.set_xlabel('Tempo observado') barplot_time.set_ylabel('Nº de experimentos') fig, ax = plt.subplots(figsize=(15,6)) ax.bar(dados['tempo'].unique(), height=dados['tempo'].value_counts(asc...
_____no_output_____
MIT
aula05_imersao_alura_dados.ipynb
EnzoGolfetti/imersaoalura_dados_3
Desafio 4: Quantos tipos de drogas foram investigados?
dados['droga'].nunique()
_____no_output_____
MIT
aula05_imersao_alura_dados.ipynb
EnzoGolfetti/imersaoalura_dados_3
Desafio 5: Procurar a documentação do query (no pandas) e resolver o desafio de criar a máscara de valores g-0 maiores que zero
dados.query('g0 > 0') dados.query('dose == "D1"') #fazendo mais um uso do Query
_____no_output_____
MIT
aula05_imersao_alura_dados.ipynb
EnzoGolfetti/imersaoalura_dados_3
Desafio 6: Renomear as colunas tirando o hífen
dados.columns = dados.columns.str.replace("-","") dados.head()
_____no_output_____
MIT
aula05_imersao_alura_dados.ipynb
EnzoGolfetti/imersaoalura_dados_3
Desafio 7: Fazer um resumo das descobertas Preferi deixar as anotações ao longo das células, se você leu até aqui, provavelmente viu minhas notas! Observando a distribuição dos genes g0 e g1
#histograma da distribuição dos resultados de g0 ax = sns.displot(data=dados, x='g0', kde=True) print(dados['g0'].min()) print(dados['g0'].max()) print(dados['g0'].mean()) print(dados['g0'].median()) print(dados['g0'].var()) print(dados['g0'].skew()) sns.displot(data=dados, x='g1', kde=True) print(dados['g1'].min()) pr...
_____no_output_____
MIT
aula05_imersao_alura_dados.ipynb
EnzoGolfetti/imersaoalura_dados_3
Aula 02
#forma interessante de substituir nome de coluna #através de um mapa mapa = {'droga':'composto'} dados.rename(columns=mapa, inplace=True)
_____no_output_____
MIT
aula05_imersao_alura_dados.ipynb
EnzoGolfetti/imersaoalura_dados_3
Criando um countplot com os primeiros 5 compostos mais usados
comp = dados['composto'].value_counts().index[:5] #coletando as infos dos 5 compostos com o query d_comp = dados.query('composto in @comp') #o @ serve para declarar que a váriavel foi definida pelo python e não pelo dados
_____no_output_____
MIT
aula05_imersao_alura_dados.ipynb
EnzoGolfetti/imersaoalura_dados_3
Desafio 9: Melhorar a visualização e estética dos gráficos
#usando o Seaborn fig, ax = plt.subplots(figsize=(15,6)) sns.set() #rodar pelo menos uma vez o .set() tras as novas configurações automáticas de estilização do Seaborn ax = sns.countplot(data=d_comp, x='composto') ax.set_title('5 compostos mais usados', ) ax.set_xlabel('Composto') ax.set_ylabel('vezes usado') plt.show(...
_____no_output_____
MIT
aula05_imersao_alura_dados.ipynb
EnzoGolfetti/imersaoalura_dados_3
Histograma das médias dos genes 'g'
#com o .T fazemos a transposição do DataFrame describe_g = dados.loc[:,'g0':'g771'].describe().T #plotando o histograma das médias hist_g = sns.histplot(describe_g, x='mean', kde=True) plt.show() #histograma dos desvios-padrão hist_g = sns.histplot(describe_g, x='std', kde=True) plt.show()
_____no_output_____
MIT
aula05_imersao_alura_dados.ipynb
EnzoGolfetti/imersaoalura_dados_3
Observando as variáveis 'c'
describe_c = dados.loc[:,'c0':'c99'].describe().T #histograma das médias sns.histplot(data=describe_c, x='mean', kde=True) plt.show()
_____no_output_____
MIT
aula05_imersao_alura_dados.ipynb
EnzoGolfetti/imersaoalura_dados_3
No Dataframe, cada 'c' respresenta linhagens de células, o pressuposto de ter vários tipos de células é para garantir a famosa independência estatística, e não gerar o viés de que o o medicamento agiu em determinado tipo, ou que foi o tipo que gerou o resultado da célula, e também garantir saber possíveis colaterais.Os...
sns.boxplot(data=dados, x='g0') #boxplot da resposta de g0 por dose administrada plt.figure(figsize=(10,6)) sns.boxplot(data=dados, x='g0', y='dose', ) #boxplot da resposta de g0 por tratamento sns.boxplot(data=dados, x='g0', y='tratamento')
_____no_output_____
MIT
aula05_imersao_alura_dados.ipynb
EnzoGolfetti/imersaoalura_dados_3
Plotando um boxplot mais bonito e mais completo
fig, ax = plt.subplots(figsize=(10,9)) sns.set_style('darkgrid') sns.set_context('talk') ax = sns.boxplot(data=dados, x='tratamento', y='g0', hue='dose', palette='Paired') ax.set_xlabel('Tipo de tratamento', fontdict={'fontsize':20}) ax.set_ylabel('gene g0') ax.set_title('Quartis e mediana por tratamento e dose', fontd...
_____no_output_____
MIT
aula05_imersao_alura_dados.ipynb
EnzoGolfetti/imersaoalura_dados_3
Dia 3 Função nova: ".crosstab" que cria uma frequency table Para filtrar mais de um dado, nas colunas ou linhas (e criar um MultiIndex) devemos inserir os **colchetes antes**(procedimento padrão no Pandas).Podemos normalizar os valores de várias formas (ver documetação) com o **'normalize='**.Para adicionar um valor es...
pd.crosstab(dados['dose'], [dados['tratamento'], dados['tempo']]) #outra forma de fazer pd.crosstab([dados['dose'], dados['tempo']], dados['tratamento']) #plotando as proporções pd.crosstab([dados['dose'], dados['tempo']], dados['tratamento'], normalize=True) * 100 #plotando as proporções pelo index (nesse caso será e...
_____no_output_____
MIT
aula05_imersao_alura_dados.ipynb
EnzoGolfetti/imersaoalura_dados_3
Desafio 08: Fazer uma tabela parecida com a crosstab mas utilizando o Groupby Nota pessoal: Eu gosto muito de Groupby, ela é muito poderosa
groupby = dados.groupby(by=['dose', 'tratamento','tempo']).count() groupby.iloc[:13,2:3] groupby.iloc[:13,2:3].T
_____no_output_____
MIT
aula05_imersao_alura_dados.ipynb
EnzoGolfetti/imersaoalura_dados_3
Desafio 9: Normalizar o crosstab pela coluna
pd.crosstab([dados['dose'],dados['tempo']], dados['tratamento'], normalize='columns')
_____no_output_____
MIT
aula05_imersao_alura_dados.ipynb
EnzoGolfetti/imersaoalura_dados_3
Desafio 10: Quais outros agregadores existem? Média
pd.crosstab([dados['dose'], dados['tempo']], dados['tratamento'], values=dados['g0'], aggfunc='mean')
_____no_output_____
MIT
aula05_imersao_alura_dados.ipynb
EnzoGolfetti/imersaoalura_dados_3
Mediana
pd.crosstab([dados['dose'], dados['tempo']], dados['tratamento'], values=dados['g0'], aggfunc='median')
_____no_output_____
MIT
aula05_imersao_alura_dados.ipynb
EnzoGolfetti/imersaoalura_dados_3
Standard Deviation a.k.a Desvio-padrão
pd.crosstab([dados['dose'], dados['tempo']], dados['tratamento'], values=dados['g0'], aggfunc='std')
_____no_output_____
MIT
aula05_imersao_alura_dados.ipynb
EnzoGolfetti/imersaoalura_dados_3
Variância
pd.crosstab([dados['dose'], dados['tempo']], dados['tratamento'], values=dados['g0'], aggfunc='var')
_____no_output_____
MIT
aula05_imersao_alura_dados.ipynb
EnzoGolfetti/imersaoalura_dados_3
Desafio 11: Explorar o Melt Esse método pode ser aplicado tanto em pd (pandas) quanto diretamente no Dataframe
pd.melt(dados, id_vars=['dose','tratamento', 'tempo'], value_vars=['g0']) dados.melt(id_vars=['dose','tratamento','tempo'], value_vars=['g0']) dados.melt(id_vars=['dose','tratamento','tempo'], value_vars=['g0'])[:5] #podemos aplicar o index como sempre para dar uma filtrada dados.melt(id_vars=['dose','tratamento','temp...
_____no_output_____
MIT
aula05_imersao_alura_dados.ipynb
EnzoGolfetti/imersaoalura_dados_3
Explorando as correlações e variações de g0 e g1
#usando a dispersão sns.scatterplot(data=dados, x='g0', y='g1') sns.scatterplot(data=dados, x='g0', y='g3', ) #o jointplot mostra a distruibuição junto com a dispersão sns.jointplot(data=dados, x='g0', y='g3', kind='reg') #outra forma de ver a linha de distribuição é com o lmplot sns.lmplot(data=dados, x='g0', y='g3', ...
_____no_output_____
MIT
aula05_imersao_alura_dados.ipynb
EnzoGolfetti/imersaoalura_dados_3
Observando as correlações O Próprio Pandas pode nos mostrar as correlações
#.corr() dados.loc[:,'g0':'g771'].corr()
_____no_output_____
MIT
aula05_imersao_alura_dados.ipynb
EnzoGolfetti/imersaoalura_dados_3
No geral, utilizamos um gráfico 'heatmap' para ver as correlações.Aqui, usaremos um ctrl+c ctrl+v da matriz diagonal de correlação
corr = dados.loc[:,'g0':'g50'].corr() # Generate a mask for the upper triangle mask = np.triu(np.ones_like(corr, dtype=bool)) # Set up the matplotlib figure f, ax = plt.subplots(figsize=(30, 15)) # Generate a custom diverging colormap cmap = sns.diverging_palette(230, 20, as_cmap=True) # Draw the heatmap with the m...
_____no_output_____
MIT
aula05_imersao_alura_dados.ipynb
EnzoGolfetti/imersaoalura_dados_3
VELHO LEMBRETE: **Correlação não é causalidade!** Correlações de C
corr_c = dados.loc[:,'c0':'c50'].corr() # Generate a mask for the upper triangle mask = np.triu(np.ones_like(corr_c, dtype=bool)) # Set up the matplotlib figure f, ax = plt.subplots(figsize=(30, 15)) # Generate a custom diverging colormap cmap = sns.diverging_palette(230, 20, as_cmap=True) # Draw the heatmap with t...
_____no_output_____
MIT
aula05_imersao_alura_dados.ipynb
EnzoGolfetti/imersaoalura_dados_3
Desafio 12: Explorar a correlação entre expressões gênicas g e os tipos célulares c
_____no_output_____
MIT
aula05_imersao_alura_dados.ipynb
EnzoGolfetti/imersaoalura_dados_3
Dia 4 Hoje vamos observar os resultados dos testes experimentais
dados_resultados = pd.read_csv('https://github.com/alura-cursos/imersaodados3/blob/main/dados/dados_resultados.csv?raw=true') dados_resultados.head()
_____no_output_____
MIT
aula05_imersao_alura_dados.ipynb
EnzoGolfetti/imersaoalura_dados_3
De forma superficial, essa base contém os mecanismos de ação, se 1, foi ativado pelo experimento, se 0 é que não foi ativado pelo experimento
dados_resultados.info()
_____no_output_____
MIT
aula05_imersao_alura_dados.ipynb
EnzoGolfetti/imersaoalura_dados_3
Três formas de fazer a contagem dos mecanismos de ação Com o Iloc
contagem_moa = dados_resultados.iloc[:,1:].sum().sort_values(ascending=False) contagem_moa
_____no_output_____
MIT
aula05_imersao_alura_dados.ipynb
EnzoGolfetti/imersaoalura_dados_3
COm o select_dtypes
contagem_moa = dados_resultados.select_dtypes('int64').sum().sort_values(ascending=False) contagem_moa
_____no_output_____
MIT
aula05_imersao_alura_dados.ipynb
EnzoGolfetti/imersaoalura_dados_3
Com o drop
contagem_moa = dados_resultados.drop('id', axis=1).sum().sort_values(ascending=False) contagem_moa dados_resultados['n_moa'] = dados_resultados.drop('id', axis=1).sum(axis=1) dados_resultados['moa_ativado'] = dados_resultados['n_moa'] != 0 dados_resultados.head() dados_final = pd.merge(dados, dados_resultados[['id', 'n...
_____no_output_____
MIT
aula05_imersao_alura_dados.ipynb
EnzoGolfetti/imersaoalura_dados_3
Desafio 01: Encontrar o top10 das ações do MoA (inibidor, agonista, etc.)
copy_dados = dados_resultados copy_dados #contando quantos tem inhibitor len(copy_dados.columns[copy_dados.columns.str.contains('inhibitor')]) #Contando quantos tem agonist len(copy_dados.columns[copy_dados.columns.str.contains('agonist')]) #vendo os que não contém nem inhibitor nem agonist copy_dados.columns[(copy_dad...
_____no_output_____
MIT
aula05_imersao_alura_dados.ipynb
EnzoGolfetti/imersaoalura_dados_3
Desafio 2: Criar uma coluna True False (0,1) para a coluna tratamento
dados_final['eh_controle'] = dados_final['tratamento'] == 'com_controle' dados_final['eh_controle'].value_counts()
_____no_output_____
MIT
aula05_imersao_alura_dados.ipynb
EnzoGolfetti/imersaoalura_dados_3
Desafio 3: Criar colunas para 24, 48 e 72 de True e False
dados_final['tempo'].dtype dados_final['24h'] = dados_final['tempo'] == 24 dados_final.head(2) dados_final['48h'] = dados_final['tempo'] == 48 dados_final['72h'] = dados_final['tempo'] == 72
_____no_output_____
MIT
aula05_imersao_alura_dados.ipynb
EnzoGolfetti/imersaoalura_dados_3
Desafio 4: Criar coluna para dose
dados_final['d1'] = dados_final['dose'] == 'D1' dados_final['d2'] = dados_final['dose'] == 'D2'
_____no_output_____
MIT
aula05_imersao_alura_dados.ipynb
EnzoGolfetti/imersaoalura_dados_3
Desafio 4: Análise mais profunda para quando há tempo e dose
dados_final['composto'].value_counts() #não esquecer: para teste boleano não aplicar o filtro (nome do dataset no início), para fazer slice ai sim se coloca o filtro, como no caso abaixo analise_comp = dados_final[(dados_final['composto'] == 'cacb2b860') | (dados_final['composto'] == '5628cb3ee')] analise_comp sns.catp...
_____no_output_____
MIT
aula05_imersao_alura_dados.ipynb
EnzoGolfetti/imersaoalura_dados_3