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
1) Add a list of friends to each user
# set each user’s friends property to an empty list: for user in users: user["friends"] = [] print users print users[0]['friends'] # then we populate the lists using the friendships data: for i, j in friendships: # this works because users[i] is the user whose id is i users[i]["friends"].append(users[j]) ...
{'friends': [{'friends': [{...}, {'friends': [{...}, {...}, {'friends': [{...}, {...}, {'friends': [{...}, {'friends': [{...}, {'friends': [{...}, {'friends': [{...}, {'friends': [{...}, {...}], 'id': 7, 'name': 'Devin'}, {'friends': [{...}], 'id': 9, 'name': 'Klein'}], 'id': 8, 'name': 'Kate'}], 'id': 6, 'name': 'Hick...
Unlicense
my-code/ch01/ch01.ipynb
tuanavu/data-science-from-scratch
2) what’s the average number of connections Once each user dict contains a list of friends, we can easily ask questions of ourgraph, like “what’s the average number of connections?”First we find the total number of connections, by summing up the lengths of all thefriends lists:
def number_of_friends(user): """how many friends does _user_ have?""" return len(user["friends"]) # length of friend_ids list total_connections = sum(number_of_friends(user) for user in users) # 24 print total_connections # And then we just divide by the number of users: from __future__...
10 2.4
Unlicense
my-code/ch01/ch01.ipynb
tuanavu/data-science-from-scratch
It’s also easy to find the most connected people—they’re the people who have the largestnumber of friends.Since there aren’t very many users, we can sort them from “most friends” to “leastfriends”:
# create a list (user_id, number_of_friends) num_friends_by_id = [(user["id"], number_of_friends(user)) for user in users] print num_friends_by_id sorted(num_friends_by_id, # get it sorted key=lambda (user_id, num_friends): num_friends, # by num_friends reverse=True) # largest to sm...
[(0, 2), (1, 3), (2, 3), (3, 3), (4, 2), (5, 3), (6, 2), (7, 2), (8, 3), (9, 1)]
Unlicense
my-code/ch01/ch01.ipynb
tuanavu/data-science-from-scratch
3) Data Scientists You May Know Your first instinct is to suggest that a user might know the friends of friends. Theseare easy to compute: for each of a user’s friends, iterate over that person’s friends, andcollect all the results:
def friends_of_friend_ids_bad(user): # "foaf" is short for "friend of a friend" return [foaf["id"] for friend in user["friends"] # for each of user's friends for foaf in friend["friends"]] # get each of _their_ friends friends_of_friend_ids_bad(users[0])
_____no_output_____
Unlicense
my-code/ch01/ch01.ipynb
tuanavu/data-science-from-scratch
It includes user 0 (twice), since Hero is indeed friends with both of his friends. Itincludes users 1 and 2, although they are both friends with Hero already. And itincludes user 3 twice, as Chi is reachable through two different friends:
print [friend["id"] for friend in users[0]["friends"]] # [1, 2] print [friend["id"] for friend in users[1]["friends"]] # [0, 2, 3] print [friend["id"] for friend in users[2]["friends"]] # [0, 1, 3]
[1, 2] [0, 2, 3] [0, 1, 3]
Unlicense
my-code/ch01/ch01.ipynb
tuanavu/data-science-from-scratch
Knowing that people are friends-of-friends in multiple ways seems like interestinginformation, so maybe instead we should produce a count of mutual friends. And wedefinitely should use a helper function to exclude people already known to the user:
from collections import Counter # not loaded by default def not_the_same(user, other_user): """two users are not the same if they have different ids""" return user["id"] != other_user["id"] def not_friends(user, other_user): """other_user is not a friend if he's not in user["friends"]; that is, if he'...
Counter({0: 2, 5: 1})
Unlicense
my-code/ch01/ch01.ipynb
tuanavu/data-science-from-scratch
This correctly tells Chi (id 3) that she has two mutual friends with Hero (id 0) butonly one mutual friend with Clive (id 5). As a data scientist, you know that you also might enjoy meeting users with similarinterests. (This is a good example of the “substantive expertise” aspect of data science.)After asking around, y...
interests = [ (0, "Hadoop"), (0, "Big Data"), (0, "HBase"), (0, "Java"), (0, "Spark"), (0, "Storm"), (0, "Cassandra"), (1, "NoSQL"), (1, "MongoDB"), (1, "Cassandra"), (1, "HBase"), (1, "Postgres"), (2, "Python"), (2, "scikit-learn"), (2, "scipy"), (2, "numpy"), (2, "statsmodels"), (2, "pandas"), (3, "R"), (3, "Python")...
_____no_output_____
Unlicense
my-code/ch01/ch01.ipynb
tuanavu/data-science-from-scratch
For example, Thor (id 4) has no friends in common with Devin (id 7), but they sharean interest in machine learning.It’s easy to build a function that finds users with a certain interest:
def data_scientists_who_like(target_interest): return [user_id for user_id, user_interest in interests if user_interest == target_interest] data_scientists_who_like('Java')
_____no_output_____
Unlicense
my-code/ch01/ch01.ipynb
tuanavu/data-science-from-scratch
This works, but it has to examine the whole list of interests for every search. If wehave a lot of users and interests (or if we just want to do a lot of searches), we’re probablybetter off building an index from interests to users:
from collections import defaultdict # keys are interests, values are lists of user_ids with that interest user_ids_by_interest = defaultdict(list) for user_id, interest in interests: user_ids_by_interest[interest].append(user_id) print user_ids_by_interest # And another from users to interests: # keys are user_i...
defaultdict(<type 'list'>, {0: ['Hadoop', 'Big Data', 'HBase', 'Java', 'Spark', 'Storm', 'Cassandra'], 1: ['NoSQL', 'MongoDB', 'Cassandra', 'HBase', 'Postgres'], 2: ['Python', 'scikit-learn', 'scipy', 'numpy', 'statsmodels', 'pandas'], 3: ['R', 'Python', 'statistics', 'regression', 'probability'], 4: ['machine learning...
Unlicense
my-code/ch01/ch01.ipynb
tuanavu/data-science-from-scratch
Now it’s easy to find who has the most interests in common with a given user:- Iterate over the user’s interests.- For each interest, iterate over the other users with that interest.- Keep count of how many times we see each other user.
def most_common_interests_with(user): return Counter(interested_user_id for interest in interests_by_user_id[user["id"]] for interested_user_id in user_ids_by_interest[interest] if interested_user_id != user["id"])
_____no_output_____
Unlicense
my-code/ch01/ch01.ipynb
tuanavu/data-science-from-scratch
4) Salaries and Experience
# Salary data is of course sensitive, # but he manages to provide you an anonymous data set containing each user’s # salary (in dollars) and tenure as a data scientist (in years): salaries_and_tenures = [(83000, 8.7), (88000, 8.1), (48000, 0.7), (76000, 6), (69000, 6...
_____no_output_____
Unlicense
my-code/ch01/ch01.ipynb
tuanavu/data-science-from-scratch
It seems pretty clear that people with more experience tend to earn more. How canyou turn this into a fun fact? Your first idea is to look at the average salary for eachtenure:
# keys are years, values are lists of the salaries for each tenure salary_by_tenure = defaultdict(list) for salary, tenure in salaries_and_tenures: salary_by_tenure[tenure].append(salary) print salary_by_tenure # keys are years, each value is average salary for that tenure average_salary_by_tenure = { te...
defaultdict(<type 'list'>, {6.5: [69000], 7.5: [76000], 6: [76000], 10: [83000], 8.1: [88000], 4.2: [63000], 0.7: [48000], 8.7: [83000], 1.9: [48000], 2.5: [60000]}) {6.5: 69000.0, 7.5: 76000.0, 6: 76000.0, 10: 83000.0, 8.1: 88000.0, 4.2: 63000.0, 8.7: 83000.0, 0.7: 48000.0, 1.9: 48000.0, 2.5: 60000.0}
Unlicense
my-code/ch01/ch01.ipynb
tuanavu/data-science-from-scratch
This turns out to be not particularly useful, as none of the users have the same tenure, which means we’re just reporting the individual users’ salaries.
# It might be more helpful to bucket the tenures: def tenure_bucket(tenure): if tenure < 2: return "less than two" elif tenure < 5: return "between two and five" else: return "more than five" # Then group together the salaries corresponding to each bucket: # keys are tenure buckets,...
{'more than five': 79166.66666666667, 'between two and five': 61500.0, 'less than two': 48000.0}
Unlicense
my-code/ch01/ch01.ipynb
tuanavu/data-science-from-scratch
5) Paid Accounts
def predict_paid_or_unpaid(years_experience): if years_experience < 3.0: return "paid" elif years_experience < 8.5: return "unpaid" else: return "paid"
_____no_output_____
Unlicense
my-code/ch01/ch01.ipynb
tuanavu/data-science-from-scratch
6) Topics of Interest One simple (if not particularly exciting) way to find the most popular interests is simplyto count the words:1. Lowercase each interest (since different users may or may not capitalize theirinterests).2. Split it into words.3. Count the results.
words_and_counts = Counter(word for user, interest in interests for word in interest.lower().split()) print words_and_counts
Counter({'learning': 3, 'java': 3, 'python': 3, 'big': 3, 'data': 3, 'hbase': 2, 'regression': 2, 'cassandra': 2, 'statistics': 2, 'probability': 2, 'hadoop': 2, 'networks': 2, 'machine': 2, 'neural': 2, 'scikit-learn': 2, 'r': 2, 'nosql': 1, 'programming': 1, 'deep': 1, 'haskell': 1, 'languages': 1, 'decision': 1, 'ar...
Unlicense
my-code/ch01/ch01.ipynb
tuanavu/data-science-from-scratch
This makes it easy to list out the words that occur more than once:
for word, count in words_and_counts.most_common(): if count > 1: print word, count
learning 3 java 3 python 3 big 3 data 3 hbase 2 regression 2 cassandra 2 statistics 2 probability 2 hadoop 2 networks 2 machine 2 neural 2 scikit-learn 2 r 2
Unlicense
my-code/ch01/ch01.ipynb
tuanavu/data-science-from-scratch
LOFO Feature Importancehttps://github.com/aerdem4/lofo-importance
!pip install lofo-importance import numpy as np import pandas as pd df = pd.read_csv("../input/train.csv", index_col='id') df['wheezy-copper-turtle-magic'] = df['wheezy-copper-turtle-magic'].astype('category') df.shape
_____no_output_____
MIT
5 instant gratification/instantgratification-lofo-feature-importance.ipynb
MLVPRASAD/KaggleProjects
Use the best model in public kernels
from sklearn.pipeline import Pipeline from sklearn.preprocessing import StandardScaler from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis def get_model(): return Pipeline([('scaler', StandardScaler()), ('qda', QuadraticDiscriminantAnalysis(reg_param=0.111)) ...
_____no_output_____
MIT
5 instant gratification/instantgratification-lofo-feature-importance.ipynb
MLVPRASAD/KaggleProjects
Top 20 Features for wheezy-copper-turtle-magic = 0
from sklearn.model_selection import KFold, StratifiedKFold, train_test_split from sklearn.linear_model import LogisticRegression from lofo import LOFOImportance, FLOFOImportance, plot_importance features = [c for c in df.columns if c not in ['id', 'target', 'wheezy-copper-turtle-magic']] def get_lofo_importance(wct...
/opt/conda/lib/python3.6/site-packages/lofo/lofo_importance.py:32: UserWarning: Warning: If your model is multithreaded, please initialise the number of jobs of LOFO to be equal to 1, otherwise you may experience issues. warnings.warn(warning_str)
MIT
5 instant gratification/instantgratification-lofo-feature-importance.ipynb
MLVPRASAD/KaggleProjects
Top 20 Features for wheezy-copper-turtle-magic = 1
plot_importance(get_lofo_importance(1), figsize=(12, 12))
/opt/conda/lib/python3.6/site-packages/lofo/lofo_importance.py:32: UserWarning: Warning: If your model is multithreaded, please initialise the number of jobs of LOFO to be equal to 1, otherwise you may experience issues. warnings.warn(warning_str)
MIT
5 instant gratification/instantgratification-lofo-feature-importance.ipynb
MLVPRASAD/KaggleProjects
Top 20 Features for wheezy-copper-turtle-magic = 2
plot_importance(get_lofo_importance(2), figsize=(12, 12))
/opt/conda/lib/python3.6/site-packages/lofo/lofo_importance.py:32: UserWarning: Warning: If your model is multithreaded, please initialise the number of jobs of LOFO to be equal to 1, otherwise you may experience issues. warnings.warn(warning_str)
MIT
5 instant gratification/instantgratification-lofo-feature-importance.ipynb
MLVPRASAD/KaggleProjects
Find the most harmful features for each wheezy-copper-turtle-magic
from tqdm import tqdm_notebook import warnings warnings.filterwarnings("ignore") features_to_remove = [] potential_gain = [] for i in tqdm_notebook(range(512)): imp = get_lofo_importance(i) features_to_remove.append(imp["feature"].values[-1]) potential_gain.append(-imp["importance_mean"].values[-1]) ...
_____no_output_____
MIT
5 instant gratification/instantgratification-lofo-feature-importance.ipynb
MLVPRASAD/KaggleProjects
Create submission using the current best kernelhttps://www.kaggle.com/tunguz/ig-pca-nusvc-knn-qda-lr-stack by Bojan Tunguz
import numpy as np, pandas as pd from sklearn.model_selection import StratifiedKFold from sklearn.metrics import roc_auc_score from sklearn import svm, neighbors, linear_model, neural_network from sklearn.svm import NuSVC from sklearn.preprocessing import StandardScaler from sklearn.decomposition import PCA from tqdm i...
lr 0.790131655722408 knn 0.9016209110875143 svc 0.9496455309107024 svcnu 0.9602070184471454 mlp 0.9099946396711365 qda 0.9645745359410043 blend 1 0.9606747834832012 blend 2 0.9658290716499904 (262144, 6) (131073, 6) stack CV score = 0.965867
MIT
5 instant gratification/instantgratification-lofo-feature-importance.ipynb
MLVPRASAD/KaggleProjects
Submitting various things for end of grant.
import os import sys import requests import pandas import paramiko import json from IPython import display from curation_common import * from htsworkflow.submission.encoded import DCCValidator PANDAS_ODF = os.path.expanduser('~/src/odf_pandas') if PANDAS_ODF not in sys.path: sys.path.append(PANDAS_ODF) from pan...
_____no_output_____
BSD-3-Clause
encode-mirna-2018-01.ipynb
detrout/encode4-curation
Submit Documents Example Document submission
#atac_uuid = '0fc44318-b802-474e-8199-f3b6d708eb6f' #atac = Document(os.path.expanduser('~/proj/encode3-curation/Wold_Lab_ATAC_Seq_protocol_December_2016.pdf'), # 'general protocol', # 'ATAC-Seq experiment protocol for Wold lab', # ) #body = atac.create_if_needed(server, ata...
_____no_output_____
BSD-3-Clause
encode-mirna-2018-01.ipynb
detrout/encode4-curation
Submit Annotations
#sheet = gcat.get_file(spreadsheet_name, fmt='pandas_excel') #annotations = sheet.parse('Annotations', header=0) #created = server.post_sheet('/annotations/', annotations, verbose=True, dry_run=True) #print(len(created)) #if created: # annotations.to_excel('/tmp/annotations.xlsx', index=False)
_____no_output_____
BSD-3-Clause
encode-mirna-2018-01.ipynb
detrout/encode4-curation
Register Biosamples
book = gcat.get_file(spreadsheet_name, fmt='pandas_excel') biosample = book.parse('Biosamples', header=0) created = server.post_sheet('/biosamples/', biosample, verbose=True, dry_run=True, validator=validator) print(len(created)) if ...
_____no_output_____
BSD-3-Clause
encode-mirna-2018-01.ipynb
detrout/encode4-curation
Register Libraries
print(spreadsheet_name) book = gcat.get_file(spreadsheet_name, fmt='pandas_excel') libraries = book.parse('Libraries', header=0) created = server.post_sheet('/libraries/', libraries, verbose=True, dry_run=True, validator=validator) print(len(created)) if created: libraries.to_excel('/dev/shm/libraries.xlsx', index=...
_____no_output_____
BSD-3-Clause
encode-mirna-2018-01.ipynb
detrout/encode4-curation
Register Experiments
print(server.server) book = gcat.get_file(spreadsheet_name, fmt='pandas_excel') experiments = book.parse('Experiments', header=0) created = server.post_sheet('/experiments/', experiments, verbose=True, dry_run=False, validator=validator) print(len(created)) if created: experiments.to_excel('/dev/shm/experiments.xls...
_____no_output_____
BSD-3-Clause
encode-mirna-2018-01.ipynb
detrout/encode4-curation
Register Replicates
print(server.server) print(spreadsheet_name) book = gcat.get_file(spreadsheet_name, fmt='pandas_excel') replicates = book.parse('Replicates', header=0) created = server.post_sheet('/replicates/', replicates, verbose=True, dry_run=True, validator=validator) print(len(created)) if created: replicates.to_excel('/dev/s...
_____no_output_____
BSD-3-Clause
encode-mirna-2018-01.ipynb
detrout/encode4-curation
End-to-end learning for music audio- http://qiita.com/himono/items/a94969e35fa8d71f876c ``` データのダウンロードwget http://mi.soi.city.ac.uk/datasets/magnatagatune/mp3.zip.001wget http://mi.soi.city.ac.uk/datasets/magnatagatune/mp3.zip.002wget http://mi.soi.city.ac.uk/datasets/magnatagatune/mp3.zip.003 結合cat data/mp3.zip.* > d...
%matplotlib inline import os import matplotlib.pyplot as plt
_____no_output_____
MIT
keras/170711-music-tagging.ipynb
aidiary/notebooks
MP3ファイルのロード
import numpy as np from pydub import AudioSegment def mp3_to_array(file): # MP3 => RAW song = AudioSegment.from_mp3(file) song_arr = np.fromstring(song._data, np.int16) return song_arr %ls data/music/1/ambient_teknology-phoenix-01-ambient_teknology-0-29.mp3 file = 'data/music/1/ambient_teknology-phoeni...
_____no_output_____
MIT
keras/170711-music-tagging.ipynb
aidiary/notebooks
楽曲タグデータをロード- ランダムに3000曲を抽出- よく使われるタグ50個を抽出- 各曲には複数のタグがついている
import pandas as pd tags_df = pd.read_csv('data/annotations_final.csv', delim_whitespace=True) # 全体をランダムにサンプリング tags_df = tags_df.sample(frac=1) # 最初の3000曲を使う tags_df = tags_df[:3000] tags_df top50_tags = tags_df.iloc[:, 1:189].sum().sort_values(ascending=False).index[:50].tolist() y = tags_df[top50_tags].values y
_____no_output_____
MIT
keras/170711-music-tagging.ipynb
aidiary/notebooks
楽曲データをロード- tags_dfのmp3_pathからファイルパスを取得- mp3_to_array()でnumpy arrayをロード- (samples, features, channels) になるようにreshape- 音声波形は1次元なのでchannelsは1- 訓練データはすべて同じサイズなのでfeaturesは同じになるはず(パディング不要)
files = tags_df.mp3_path.values files = [os.path.join('data', 'music', x) for x in files] X = np.array([mp3_to_array(file) for file in files]) X = X.reshape(X.shape[0], X.shape[1], 1) X.shape
_____no_output_____
MIT
keras/170711-music-tagging.ipynb
aidiary/notebooks
訓練データとテストデータに分割
from sklearn.model_selection import train_test_split random_state = 42 train_x, test_x, train_y, test_y = train_test_split(X, y, test_size=0.2, random_state=random_state) print(train_x.shape) print(test_x.shape) print(train_y.shape) print(test_y.shape) plt.plot(train_x[0]) np.save('train_x.npy', train_x) np.save('test...
_____no_output_____
MIT
keras/170711-music-tagging.ipynb
aidiary/notebooks
訓練
import numpy as np from keras.models import Model from keras.layers import Dense, Flatten, Input, Conv1D, MaxPooling1D from keras.callbacks import CSVLogger, ModelCheckpoint train_x = np.load('train_x.npy') train_y = np.load('train_y.npy') test_x = np.load('test_x.npy') test_y = np.load('test_y.npy') print(train_x.s...
_____no_output_____
MIT
keras/170711-music-tagging.ipynb
aidiary/notebooks
予測- taggerは複数のタグを出力するのでevaluate()ではダメ?
import numpy as np from keras.models import load_model from sklearn.metrics import roc_auc_score test_x = np.load('test_x.npy') test_y = np.load('test_y.npy') model = load_model('model.22-9.187-0.202.h5') pred_y = model.predict(test_x, batch_size=50) print(roc_auc_score(test_y, pred_y)) print(model.evaluate(test_x, ...
Using TensorFlow backend.
MIT
keras/170711-music-tagging.ipynb
aidiary/notebooks
Splitting data for Training and Testing
from sklearn.model_selection import train_test_split X_train,X_test,Y_train,Y_test = train_test_split(x,y,train_size=0.7,random_state=0) X_train.shape X_test.shape Y_train.shape Y_test.shape
_____no_output_____
MIT
.ipynb_checkpoints/MLDC MAY'21 - Day 3-checkpoint.ipynb
CodeSnooker/ds-fireblazeaischool.in
Creating a ML Model
from sklearn.linear_model import LinearRegression regressor = LinearRegression() regressor.fit(X_train,Y_train) y_predict = regressor.predict(X_test) y_predict Y_test
_____no_output_____
MIT
.ipynb_checkpoints/MLDC MAY'21 - Day 3-checkpoint.ipynb
CodeSnooker/ds-fireblazeaischool.in
Model Coefficients
regressor.intercept_ regressor.coef_
_____no_output_____
MIT
.ipynb_checkpoints/MLDC MAY'21 - Day 3-checkpoint.ipynb
CodeSnooker/ds-fireblazeaischool.in
Equation of Line --> y = 9360.26* x + 26777.39 Model Evaluation
from sklearn import metrics MAE = metrics.mean_absolute_error(Y_test,y_predict) MAE MSE = metrics.mean_squared_error(Y_test,y_predict) MSE RMSE = np.sqrt(MSE) RMSE R2 = metrics.r2_score(Y_test,y_predict) R2
_____no_output_____
MIT
.ipynb_checkpoints/MLDC MAY'21 - Day 3-checkpoint.ipynb
CodeSnooker/ds-fireblazeaischool.in
Hands on Task
df1 = pd.read_csv('data/auto-mpg.csv') df1.head()
_____no_output_____
MIT
.ipynb_checkpoints/MLDC MAY'21 - Day 3-checkpoint.ipynb
CodeSnooker/ds-fireblazeaischool.in
Markers for watershed transformThe watershed is a classical algorithm used for **segmentation**, thatis, for separating different objects in an image.Here a marker image is built from the region of low gradient inside the image.In a gradient image, the areas of high values provide barriers that help tosegment the imag...
from scipy import ndimage as ndi import matplotlib.pyplot as plt from skimage.morphology import disk from skimage.segmentation import watershed from skimage import data from skimage.filters import rank from skimage.util import img_as_ubyte image = img_as_ubyte(data.camera()) # denoise image denoised = rank.median(i...
_____no_output_____
MIT
digital-image-processing/notebooks/segmentation/plot_marked_watershed.ipynb
sinamedialab/courses
prepared by Abuzer Yakaryilmaz (QLatvia) This cell contains some macros. If there is a problem with displaying mathematical formulas, please run this cell to load these macros. $ \newcommand{\bra}[1]{\langle 1|} $$ \newcommand{\ket}[1]{|1\rangle} $$ \newcommand{...
# all portions are stored in a list all_portions = [7,5,4,2,6,1]; # let's calculate the total portion total_portion = 0 for i in range(6): total_portion = total_portion + all_portions[i] print("total portion is",total_portion) # find the weight of one portion one_portion = 1/total_portion print("the weight of o...
_____no_output_____
Apache-2.0
bronze/B07_Probabilistic_Bit_Solutions.ipynb
KuantumTurkiye/bronze
Porto Seguro's Safe Driving PredictionPorto Seguro, one of Brazil’s largest auto and homeowner insurance companies, completely agrees. Inaccuracies in car insurance company’s claim predictions raise the cost of insurance for good drivers and reduce the price for bad ones.In the [Porto Seguro Safe Driver Prediction com...
import os import numpy as np import pandas as pd import lightgbm from sklearn.model_selection import train_test_split import joblib from sklearn import metrics
_____no_output_____
MIT
step0/porto-seguro-safe-driver-prediction-LGBM.ipynb
kawo123/azure-mlops
Load DataLoad the training dataset from the ./data/ directory. Df.shape() allows you to view the dimensions of the dataset you are passing in. If you want to view the first 5 rows of data, df.head() allows for this.
DATA_DIR = "../data" data_df = pd.read_csv(os.path.join(DATA_DIR, 'porto_seguro_safe_driver_prediction_input.csv')) print(data_df.shape) data_df.head()
(595212, 59)
MIT
step0/porto-seguro-safe-driver-prediction-LGBM.ipynb
kawo123/azure-mlops
Split Data into Train and Validatation SetsPartitioning data into training, validation, and holdout sets allows you to develop highly accurate models that are relevant to data that you collect in the future, not just the data the model was trained on. In machine learning, features are the measurable property of the ob...
features = data_df.drop(['target', 'id'], axis = 1) labels = np.array(data_df['target']) features_train, features_valid, labels_train, labels_valid = train_test_split(features, labels, test_size=0.2, random_state=0) train_data = lightgbm.Dataset(features_train, label=labels_train) valid_data = lightgbm.Dataset(feature...
_____no_output_____
MIT
step0/porto-seguro-safe-driver-prediction-LGBM.ipynb
kawo123/azure-mlops
Train ModelA machine learning model is an algorithm which learns features from the given data to produce labels which may be continuous or categorical ( regression and classification respectively ). In other words, it tries to relate the given data with its labels, just as the human brain does.In this cell, the data s...
parameters = { 'learning_rate': 0.02, 'boosting_type': 'gbdt', 'objective': 'binary', 'metric': 'auc', 'sub_feature': 0.7, 'num_leaves': 60, 'min_data': 100, 'min_hessian': 1, 'verbose': 4 } model = lightgbm.train(parameters, train_data, ...
[1] valid_0's auc: 0.595844 Training until validation scores don't improve for 20 rounds [2] valid_0's auc: 0.605252 [3] valid_0's auc: 0.612784 [4] valid_0's auc: 0.61756 [5] valid_0's auc: 0.620129 [6] valid_0's auc: 0.622447 [7] valid_0's auc: 0.622163 [8] valid_0's auc: 0.622112 [9] valid_0's auc: 0.622581 [10] val...
MIT
step0/porto-seguro-safe-driver-prediction-LGBM.ipynb
kawo123/azure-mlops
Evaluate ModelEvaluating performance is an essential task in machine learning. In this case, because this is a classification problem, the data scientist elected to use an AUC - ROC Curve. When we need to check or visualize the performance of the multi - class classification problem, we use AUC (Area Under The Curve) ...
predictions = model.predict(valid_data.data) fpr, tpr, thresholds = metrics.roc_curve(valid_data.label, predictions) model_metrics = {"auc": (metrics.auc(fpr, tpr))} print(model_metrics)
{'auc': 0.6377511613946426}
MIT
step0/porto-seguro-safe-driver-prediction-LGBM.ipynb
kawo123/azure-mlops
Save Model In machine learning, we need to save the trained models in a file and restore them in order to reuse it to compare the model with other models, to test the model on a new data. The saving of data is called Serializaion, while restoring the data is called Deserialization.
model_name = "lgbm_binary_model.pkl" joblib.dump(value=model, filename=model_name)
_____no_output_____
MIT
step0/porto-seguro-safe-driver-prediction-LGBM.ipynb
kawo123/azure-mlops
Exploratory Data Analysis (EDA) Univariate Analysis
cat_cols = ['Fuel','Seller Type','Transmission','Owner'] i=0 while i < 4: fig = plt.figure(figsize=[15,6]) plt.subplot(1,2,1) sns.countplot(x=cat_cols[i], data=df) i += 1 plt.subplot(1,2,2) sns.countplot(x=cat_cols[i], data=df) i += 1 plt.show() num_cols = ['Selling Price...
_____no_output_____
MIT
EDA & Prediction.ipynb
an-chowdhury/Used-Car-Price-Prediciton
Bivariate Analysis
sns.set(rc={'figure.figsize':(15,15)}) sns.heatmap(df.corr(),annot=True) print(df['Fuel'].value_counts(),'\n') print(df['Seller Type'].value_counts(),'\n') print(df['Transmission'].value_counts(),'\n') print(df['Owner'].value_counts(),'\n') df.pivot_table(values='Selling Price', index = 'Seller Type', columns= 'Fuel')
_____no_output_____
MIT
EDA & Prediction.ipynb
an-chowdhury/Used-Car-Price-Prediciton
Data Preparation Creating Dummies for Categorical Features
label_encoder = LabelEncoder() df['Owner']= label_encoder.fit_transform(df['Owner']) final_dataset=df[['Year','Selling Price','Current Value','KMs Driven','Fuel', 'Seller Type','max_power','Transmission','Owner','Mileage','Engine','Seats','Gear Box']] final_dataset=pd.get_dummies(final_dataset,drop_fi...
_____no_output_____
MIT
EDA & Prediction.ipynb
an-chowdhury/Used-Car-Price-Prediciton
Feature Importance
from sklearn.ensemble import ExtraTreesRegressor model = ExtraTreesRegressor() model.fit(X,y) print(model.feature_importances_) sns.set(rc={'figure.figsize':(12,8)}) feat_importances = pd.Series(model.feature_importances_, index=X.columns) feat_importances.nlargest(5).plot(kind='barh') plt.show() X_train, X_test, y_t...
_____no_output_____
MIT
EDA & Prediction.ipynb
an-chowdhury/Used-Car-Price-Prediciton
Linear Regression
lr = LinearRegression() lr.fit(X_train,y_train) car_pred_model(lr)
Train R2-score : 0.83 Test R2-score : 0.88 Train CV scores : [0.87318862 0.23054545 0.81581846 0.86005821 0.79216413] Train CV mean : 0.71 MAE: 1.3212115374204905 MSE: 5.731984478802555 RMSE: 2.3941563187900985
MIT
EDA & Prediction.ipynb
an-chowdhury/Used-Car-Price-Prediciton
Ridge
# Creating Ridge model object rg = Ridge() # range of alpha alpha = np.logspace(-3,3,num=14) # Creating RandomizedSearchCV to find the best estimator of hyperparameter rg_rs = RandomizedSearchCV(estimator = rg, param_distributions = dict(alpha=alpha)) rg_rs.fit(X_train,y_train) car_pred_model(rg_rs)
Train R2-score : 0.83 Test R2-score : 0.89 Train CV scores : [0.87345385 0.19438248 0.81973301 0.87546861 0.79190635] Train CV mean : 0.71 MAE: 1.259204342611868 MSE: 5.417232953632579 RMSE: 2.327494995404411
MIT
EDA & Prediction.ipynb
an-chowdhury/Used-Car-Price-Prediciton
Lasso
ls = Lasso() alpha = np.logspace(-3,3,num=14) # range for alpha ls_rs = RandomizedSearchCV(estimator = ls, param_distributions = dict(alpha=alpha)) ls_rs.fit(X_train,y_train) car_pred_model(ls_rs)
Train R2-score : 0.83 Test R2-score : 0.88 Train CV scores : [0.87434025 0.22872808 0.82137491 0.87579026 0.79292455] Train CV mean : 0.72 MAE: 1.28454046198753 MSE: 5.66135888360262 RMSE: 2.379361024225332
MIT
EDA & Prediction.ipynb
an-chowdhury/Used-Car-Price-Prediciton
Random Forest
rf = RandomForestRegressor() # Number of trees in Random forest n_estimators=list(range(500,1000,100)) # Maximum number of levels in a tree max_depth=list(range(4,9,4)) # Minimum number of samples required to split an internal node min_samples_split=list(range(4,9,2)) # Minimum number of samples required to be at a l...
Train R2-score : 0.96 Test R2-score : 0.92 Train CV scores : [0.90932922 0.55268803 0.77245254 0.92139404 0.90756667] Train CV mean : 0.81 MAE: 0.796357939896497 MSE: 3.7897916295929766 RMSE: 1.9467387163132541
MIT
EDA & Prediction.ipynb
an-chowdhury/Used-Car-Price-Prediciton
Gradient Boosting
gb = GradientBoostingRegressor() # Rate at which correcting is being made learning_rate = [0.001, 0.01, 0.1, 0.2] # Number of trees in Gradient boosting n_estimators=list(range(500,1000,100)) # Maximum number of levels in a tree max_depth=list(range(4,9,4)) # Minimum number of samples required to split an internal no...
_____no_output_____
MIT
EDA & Prediction.ipynb
an-chowdhury/Used-Car-Price-Prediciton
继续挑战--- 第10题地址[bull.html](http://www.pythonchallenge.com/pc/return/bull.html)* * 网页标题是`what are you looking at?`,题目内容是`len(a[30]) = ?`,源码里面没有隐藏内容 看到上一题画出来的牛的真面目了!同样以牛的轮廓圈起来的区域有一个[超链接](http://www.pythonchallenge.com/pc/return/sequence.txt),点进去是这样的内容> a = [1, 11, 21, 1211, 111221, 这样的话,结合题目内容一看,思路也是很清晰的。`a`是一个数列,我们要求出`a...
from itertools import islice import re def look_and_say(): num = '1' while True: yield num m = re.findall(r'((\d)\2*)', num) num = ''.join(str(len(pat[0])) + pat[1] for pat in m) a = list(islice(look_and_say(), 31)) print(len(a[30]))
5808
MIT
nbfiles/10_bull.ipynb
StevenPZChan/pythonchallenge
Import Libraries
import cv2 import numpy as np
_____no_output_____
MIT
Ex-01-Read-write-image.ipynb
imsanjoykb/Computer-Vision-Bootcamp
Load Image
image_data = cv2.imread(r'D:\Computer Vision Bootcamp\images\expert.png')
_____no_output_____
MIT
Ex-01-Read-write-image.ipynb
imsanjoykb/Computer-Vision-Bootcamp
Image Shape
print(image_data.shape)
(512, 512, 3)
MIT
Ex-01-Read-write-image.ipynb
imsanjoykb/Computer-Vision-Bootcamp
Show Image at window
cv2.imshow('First Image', image_data) cv2.waitKey(6000) ### The window will automatically close after the 6 seconds. cv2.destroyAllWindows()
_____no_output_____
MIT
Ex-01-Read-write-image.ipynb
imsanjoykb/Computer-Vision-Bootcamp
Show Image at GrayScale
image_data = cv2.imread(r'D:\imsanjoykb.github.io\images\expert.png',0) ## 0 for grayscale cv2.imshow('First Image', image_data) cv2.waitKey(6000) cv2.destroyAllWindows()
_____no_output_____
MIT
Ex-01-Read-write-image.ipynb
imsanjoykb/Computer-Vision-Bootcamp
Saving The Image
cv2.imwrite('D:\Computer Vision Bootcamp\images\expert_output.png',image_data)
_____no_output_____
MIT
Ex-01-Read-write-image.ipynb
imsanjoykb/Computer-Vision-Bootcamp
CIFAR10 using a simple deep networksCredits: \https://medium.com/@sergioalves94/deep-learning-in-pytorch-with-cifar-10-dataset-858b504a6b54 \https://jovian.ai/aakashns/05-cifar10-cnn
import torch import torchvision import numpy as np import matplotlib.pyplot as plt import torch.nn as nn import torch.nn.functional as F from torchvision.datasets import CIFAR10 from torchvision.transforms import ToTensor from torchvision.utils import make_grid from torch.utils.data.dataloader import DataLoader from to...
_____no_output_____
MIT
CIFAR10/pytorch-deep-learning-CIFAR10.ipynb
danhtaihoang/pytorch-deeplearning
Exploring the data
# Dowload the dataset dataset = CIFAR10(root='data/', download=True, transform=ToTensor()) test_dataset = CIFAR10(root='data/', train=False, transform=ToTensor())
_____no_output_____
MIT
CIFAR10/pytorch-deep-learning-CIFAR10.ipynb
danhtaihoang/pytorch-deeplearning
Import the datasets and convert the images into PyTorch tensors.
classes = dataset.classes classes class_count = {} for _, index in dataset: label = classes[index] if label not in class_count: class_count[label] = 0 class_count[label] += 1 class_count
_____no_output_____
MIT
CIFAR10/pytorch-deep-learning-CIFAR10.ipynb
danhtaihoang/pytorch-deeplearning
Split the dataset into two groups: training and validation datasets.
torch.manual_seed(43) val_size = 5000 train_size = len(dataset) - val_size train_ds, val_ds = random_split(dataset, [train_size, val_size]) len(train_ds), len(val_ds) batch_size=128 train_loader = DataLoader(train_ds, batch_size, shuffle=True, num_workers=4, pin_memory=True) val_loader = DataLoader(val_ds, batch_size*2...
_____no_output_____
MIT
CIFAR10/pytorch-deep-learning-CIFAR10.ipynb
danhtaihoang/pytorch-deeplearning
we set `pin_memory=True` because we will push the data from the CPU into the GPU and this parameter lets theDataLoader allocate the samples in page-locked memory, which speeds-up the transfer
for images, _ in train_loader: print('images.shape:', images.shape) plt.figure(figsize=(16,8)) plt.axis('off') plt.imshow(make_grid(images, nrow=16).permute((1, 2, 0))) break
images.shape: torch.Size([128, 3, 32, 32])
MIT
CIFAR10/pytorch-deep-learning-CIFAR10.ipynb
danhtaihoang/pytorch-deeplearning
Model
def accuracy(outputs, labels): _, preds = torch.max(outputs, dim=1) return torch.tensor(torch.sum(preds == labels).item() / len(preds)) class ImageClassificationBase(nn.Module): def training_step(self, batch): images, labels = batch out = self(images) # Generate predictions...
_____no_output_____
MIT
CIFAR10/pytorch-deep-learning-CIFAR10.ipynb
danhtaihoang/pytorch-deeplearning
Training the model
input_size = 3*32*32 output_size = 10 class CIFAR10Model(ImageClassificationBase): def __init__(self): super().__init__() self.linear1 = nn.Linear(input_size, 256) self.linear2 = nn.Linear(256, 128) self.linear3 = nn.Linear(128, output_size) def forward(self, xb): ...
_____no_output_____
MIT
CIFAR10/pytorch-deep-learning-CIFAR10.ipynb
danhtaihoang/pytorch-deeplearning
Kinetics 데이터 세트로 ECO용 DataLoader 작성Kineteics 동영상 데이터를 사용해, ECO용 DataLoader를 만듭니다 9.4 학습 목표1. Kinetics 동영상 데이터 세트를 다운로드할 수 있다2. 동영상 데이터를 프레임별 화상 데이터로 변환할 수 있다3. ECO에서 사용하기 위한 DataLoader를 구현할 수 있다 사전 준비- 이 책의 지시에 따라 Kinetics 동영상 데이터와, 화상 데이터를 frame별로 화상 데이터로 변환하는 조작을 수행해주세요- 가상 환경 pytorch_p36에서 실행합니다
import os from PIL import Image import csv import numpy as np import torch import torch.utils.data from torch import nn import torchvision
_____no_output_____
MIT
9_video_classification_eco/9-4_3_ECO_DataLoader.ipynb
ziippy/pytorch_deep_learning_with_12models
동영상을 화상 데이터로 만든 폴더의 파일 경로 리스트를 작성
def make_datapath_list(root_path): """ 동영상을 화상 데이터로 만든 폴더의 파일 경로 리스트를 작성한다. root_path : str, 데이터 폴더로의 root 경로 Returns: ret : video_list, 동영상을 화상 데이터로 만든 폴더의 파일 경로 리스트 """ # 동영상을 화상 데이터로 만든 폴더의 파일 경로 리스트 video_list = list() # root_path의 클래스 종류와 경로를 취득 class_list = os.listdir(path=ro...
./data/kinetics_videos/arm wrestling/C4lCVBZ3ux0_000028_000038 ./data/kinetics_videos/arm wrestling/ehLnj7pXnYE_000027_000037
MIT
9_video_classification_eco/9-4_3_ECO_DataLoader.ipynb
ziippy/pytorch_deep_learning_with_12models
동영상 전처리 클래스를 작성
class VideoTransform(): """ 동영상을 화상으로 만드는 전처리 클래스. 학습시와 추론시 다르게 작동합니다. 동영상을 화상으로 분할하고 있으므로, 분할된 화상을 한꺼번에 전처리하는 점에 주의하십시오. """ def __init__(self, resize, crop_size, mean, std): self.data_transform = { 'train': torchvision.transforms.Compose([ # DataAugumentation()...
_____no_output_____
MIT
9_video_classification_eco/9-4_3_ECO_DataLoader.ipynb
ziippy/pytorch_deep_learning_with_12models
Dataset 작성
# Kinetics-400의 라벨명을 ID로 변환하는 사전과, 반대로 ID를 라벨명으로 변환하는 사전을 준비 def get_label_id_dictionary(label_dicitionary_path='./video_download/kinetics_400_label_dicitionary.csv'): label_id_dict = {} id_label_dict = {} with open(label_dicitionary_path, encoding="utf-8_sig") as f: # 읽어들이기 reader = csv.D...
torch.Size([8, 16, 3, 224, 224])
MIT
9_video_classification_eco/9-4_3_ECO_DataLoader.ipynb
ziippy/pytorch_deep_learning_with_12models
Kompleksni brojevi u polarnom oblikuU ovome interaktivnom primjeru, kompleksni brojevi se vizualiziraju u kompleksnoj ravnini, a određuju se koristeći polarni oblik. Kompleksni brojevi se, dakle, određuju modulom (duljinom odgovarajućeg vektora) i argumentom (kutom odgovarajućeg vektora). Možete testirati osnovne mate...
%matplotlib notebook import matplotlib.pyplot as plt import matplotlib.patches as mpatches import numpy as np import ipywidgets as widgets from IPython.display import display from IPython.display import HTML import math red_patch = mpatches.Patch(color='red', label='z1') blue_patch = mpatches.Patch(color='blue', labe...
_____no_output_____
BSD-3-Clause
ICCT_hr/examples/01/.ipynb_checkpoints/M-02-Kompleksni_brojevi_polarni_sustav-checkpoint.ipynb
ICCTerasmus/ICCT
Tutorial 09: Standard problem 5> Interactive online tutorial:> [![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/ubermag/oommfc/master?filepath=docs%2Fipynb%2Findex.ipynb) Problem specificationThe sample is a thin film cuboid with dimensions:- length $l_{x} = 100 \,\text{nm}$,- width $l_{y} =...
import oommfc as oc import discretisedfield as df import micromagneticmodel as mm
_____no_output_____
BSD-3-Clause
docs/ipynb/09-tutorial-standard-problem5.ipynb
spinachslayer420/MSE598-SAF-Project
Now, we can set all required geometry and material parameters.
# Geometry lx = 100e-9 # x dimension of the sample(m) ly = 100e-9 # y dimension of the sample (m) lz = 10e-9 # sample thickness (m) dx = dy = dz = 5e-9 #discretisation cell (nm) # Material (permalloy) parameters Ms = 8e5 # saturation magnetisation (A/m) A = 1.3e-11 # exchange energy constant (J/m) # Dynamics (L...
_____no_output_____
BSD-3-Clause
docs/ipynb/09-tutorial-standard-problem5.ipynb
spinachslayer420/MSE598-SAF-Project
As usual, we create the system object with `stdprob5` name.
system = mm.System(name='stdprob5')
_____no_output_____
BSD-3-Clause
docs/ipynb/09-tutorial-standard-problem5.ipynb
spinachslayer420/MSE598-SAF-Project
The mesh is created by providing two points `p1` and `p2` between which the mesh domain spans and the size of a discretisation cell. We choose the discretisation to be $(5, 5, 5) \,\text{nm}$.
%matplotlib inline region = df.Region(p1=(0, 0, 0), p2=(lx, ly, lz)) mesh = df.Mesh(region=region, cell=(dx, dy, dz)) mesh.k3d()
_____no_output_____
BSD-3-Clause
docs/ipynb/09-tutorial-standard-problem5.ipynb
spinachslayer420/MSE598-SAF-Project
**Hamiltonian:** In the second step, we define the system's Hamiltonian. In this standard problem, the Hamiltonian contains only exchange and demagnetisation energy terms. Please note that in the first simulation stage, there is no applied external magnetic field. Therefore, we do not add Zeeman energy term to the Hami...
system.energy = mm.Exchange(A=A) + mm.Demag() system.energy
_____no_output_____
BSD-3-Clause
docs/ipynb/09-tutorial-standard-problem5.ipynb
spinachslayer420/MSE598-SAF-Project
**Magnetisation:** We initialise the system using the initial magnetisation function.
def m_vortex(pos): x, y, z = pos[0]/1e-9-50, pos[1]/1e-9-50, pos[2]/1e-9 return (-y, x, 10) system.m = df.Field(mesh, dim=3, value=m_vortex, norm=Ms) system.m.plane(z=0).mpl()
_____no_output_____
BSD-3-Clause
docs/ipynb/09-tutorial-standard-problem5.ipynb
spinachslayer420/MSE598-SAF-Project
**Dynamics:** In the first (relaxation) stage, we minimise the system's energy and therefore we do not need to specify the dynamics equation.**Minimisation:** Now, we minimise the system's energy using `MinDriver`.
md = oc.MinDriver() md.drive(system) system.m.plane(z=0).mpl()
_____no_output_____
BSD-3-Clause
docs/ipynb/09-tutorial-standard-problem5.ipynb
spinachslayer420/MSE598-SAF-Project
Spin-polarised current In the second part of simulation, we need to specify the dynamics equation for the system.
system.dynamics += mm.Precession(gamma0=gamma0) + mm.Damping(alpha=alpha) + mm.ZhangLi(u=ux, beta=beta) system.dynamics
_____no_output_____
BSD-3-Clause
docs/ipynb/09-tutorial-standard-problem5.ipynb
spinachslayer420/MSE598-SAF-Project
Now, we can drive the system for $8 \,\text{ns}$ and save the magnetisation in $n=100$ steps.
td = oc.TimeDriver() td.drive(system, t=8e-9, n=100)
Running OOMMF (ExeOOMMFRunner) [2020/06/14 11:28]... (17.4 s)
BSD-3-Clause
docs/ipynb/09-tutorial-standard-problem5.ipynb
spinachslayer420/MSE598-SAF-Project
The vortex after $8 \,\text{ns}$ is now displaced from the centre.
system.m.plane(z=0).mpl() system.table.data.plot('t', 'mx')
_____no_output_____
BSD-3-Clause
docs/ipynb/09-tutorial-standard-problem5.ipynb
spinachslayer420/MSE598-SAF-Project
Importing LibrariesJoblib used for ease of importing files. Pandas used for data manipulation.
import joblib import pandas as pd
_____no_output_____
MIT
submission_createcsv.ipynb
georgehtliu/ignition-hack-2020
Importing Classifier, Vectorizer, and Judgement DataSupport for importing from local storage as well as importing from Google Drive for Google Colab.
# Assuming files are stored locally in the same directory. clf_log = joblib.load(SentimentNewton_Log.pkl) vectorizer = joblib.load(Vectorizer.pkl) judge_data_path = "judgement_data.csv" # Uncomment to import files from Google Drive on Google Colab """ from google.colab import drive drive.mount('/content/drive') clf...
_____no_output_____
MIT
submission_createcsv.ipynb
georgehtliu/ignition-hack-2020
Processing Imported FilesPreparing dataframe and vectors.
# Convert csv file to dataframe df_judge = pd.read_csv(judge_data_path) df_mini = df_judge X = df_mini['Text'] X_vectors= vectorizer.transform(X)
_____no_output_____
MIT
submission_createcsv.ipynb
georgehtliu/ignition-hack-2020
Writing to CSV FileEdit the *csv_path* variable to decide where the csv will be stored.
csv_path = '/content/drive/My Drive/predicted_labels.csv' df_mini['Sentiment'] = clf_log.predict(X_vectors) df_mini.to_csv(csv_path) print("Done!")
Done!
MIT
submission_createcsv.ipynb
georgehtliu/ignition-hack-2020
Hierarchical Clustering
import matplotlib.pyplot as plt import pandas as pd import numpy as np import seaborn as sns sns.set() %matplotlib inline import json data = pd.read_csv('../result/caseolap.csv') data = data.set_index('protein') ndf = data ndf.head(2) ndf.shape ndata = ndf.copy(deep = True) ndf.describe()
_____no_output_____
MIT
Cluster.ipynb
CaseOLAP/IonChannel
Clustering
size=(25,25) g = sns.clustermap(ndf.T.corr(),\ figsize=size,\ cmap = "YlGnBu",\ metric='seuclidean') g.savefig('plots/cluster.pdf', format='pdf', dpi=300) g.savefig('plots/cluster.png', format='png', dpi=300) indx = g.dendrogram_row.reordered_ind protein_clus...
_____no_output_____
MIT
Cluster.ipynb
CaseOLAP/IonChannel
Barplot
protein_cluster_df.plot.barh(stacked=True,figsize=(10,20)) plt.gca().invert_yaxis() plt.legend(fontsize =10) plt.savefig('plots/cluster-bar.pdf') plt.savefig('plots/cluster-bar.png') with open("data/id2name.json","r")as f: id2name = json.load(f) names = [] for item in protein_cluster_df.index: names.append(id2...
_____no_output_____
MIT
Cluster.ipynb
CaseOLAP/IonChannel
Mount my google drive, where I stored the dataset.
from google.colab import drive drive.mount('/content/drive')
_____no_output_____
MIT
Mobilenetv2 Tuning/MobileNetV2 Baseline.ipynb
vlad-danaila/Mobilenetv2_Ensemble_for_Cervical_Precancerous_Lesions_Classification
**Download dependencies**
!pip3 install sklearn matplotlib GPUtil !pip3 install torch torchvision
Collecting torch [?25l Downloading https://files.pythonhosted.org/packages/88/95/90e8c4c31cfc67248bf944ba42029295b77159982f532c5689bcfe4e9108/torch-1.3.1-cp36-cp36m-manylinux1_x86_64.whl (734.6MB)  |████████████████████████████████| 734.6MB 56kB/s s eta 0:00:01 |▉ | 18.6MB 3.0MB...
MIT
Mobilenetv2 Tuning/MobileNetV2 Baseline.ipynb
vlad-danaila/Mobilenetv2_Ensemble_for_Cervical_Precancerous_Lesions_Classification
**Download Data** In order to acquire the dataset please navigate to:https://ieee-dataport.org/documents/cervigram-image-datasetUnzip the dataset into the folder "dataset".For your environment, please adjust the paths accordingly.
!rm -vrf "dataset" !mkdir "dataset" # !cp -r "/content/drive/My Drive/Studiu doctorat leziuni cervicale/cervigram-image-dataset-v2.zip" "dataset/cervigram-image-dataset-v2.zip" !cp -r "cervigram-image-dataset-v2.zip" "dataset/cervigram-image-dataset-v2.zip" !unzip "dataset/cervigram-image-dataset-v2.zip" -d "dataset"
removed directory 'dataset' Archive: dataset/cervigram-image-dataset-v2.zip creating: dataset/data/ creating: dataset/data/test/ creating: dataset/data/test/0/ creating: dataset/data/test/0/20151103002/ inflating: dataset/data/test/0/20151103002/20151103113458.jpg inflating: dataset/data/test/0/20151...
MIT
Mobilenetv2 Tuning/MobileNetV2 Baseline.ipynb
vlad-danaila/Mobilenetv2_Ensemble_for_Cervical_Precancerous_Lesions_Classification
**Constants** For your environment, please modify the paths accordingly.
# TRAIN_PATH = '/content/dataset/data/train/' # TEST_PATH = '/content/dataset/data/test/' TRAIN_PATH = 'dataset/data/train/' TEST_PATH = 'dataset/data/test/' CROP_SIZE = 260 IMAGE_SIZE = 224 BATCH_SIZE = 100
_____no_output_____
MIT
Mobilenetv2 Tuning/MobileNetV2 Baseline.ipynb
vlad-danaila/Mobilenetv2_Ensemble_for_Cervical_Precancerous_Lesions_Classification
**Imports**
import torch as t import torchvision as tv import numpy as np import PIL as pil import matplotlib.pyplot as plt from torchvision.datasets import ImageFolder from torch.utils.data import DataLoader from torch.nn import Linear, BCEWithLogitsLoss import sklearn as sk import sklearn.metrics from os import listdir import ti...
_____no_output_____
MIT
Mobilenetv2 Tuning/MobileNetV2 Baseline.ipynb
vlad-danaila/Mobilenetv2_Ensemble_for_Cervical_Precancerous_Lesions_Classification