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]) # add i as a friend of j
users[j]["friends"].append(users[i]) # add j as a friend of i
print users[0] | {'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': 'Hicks'}, {'friends': [{...}, {'friends': [{'friends': [{...}, {...}], 'id': 6, 'name': 'Hicks'}, {...}, {'friends': [{...}], 'id': 9, 'name': 'Klein'}], 'id': 8, 'name': 'Kate'}], 'id': 7, 'name': 'Devin'}], 'id': 5, 'name': 'Clive'}], 'id': 4, 'name': 'Thor'}], 'id': 3, 'name': 'Chi'}], 'id': 2, 'name': 'Sue'}, {'friends': [{...}, {'friends': [{...}, {...}, {...}], 'id': 2, 'name': 'Sue'}, {'friends': [{...}, {'friends': [{...}, {'friends': [{...}, {'friends': [{...}, {'friends': [{...}, {...}], 'id': 7, 'name': 'Devin'}, {'friends': [{...}], 'id': 9, 'name': 'Klein'}], 'id': 8, 'name': 'Kate'}], 'id': 6, 'name': 'Hicks'}, {'friends': [{...}, {'friends': [{'friends': [{...}, {...}], 'id': 6, 'name': 'Hicks'}, {...}, {'friends': [{...}], 'id': 9, 'name': 'Klein'}], 'id': 8, 'name': 'Kate'}], 'id': 7, 'name': 'Devin'}], 'id': 5, 'name': 'Clive'}], 'id': 4, 'name': 'Thor'}], 'id': 3, 'name': 'Chi'}], 'id': 1, 'name': 'Dunn'}, {'friends': [{...}, {'friends': [{...}, {...}, {'friends': [{...}, {...}, {'friends': [{...}, {'friends': [{...}, {'friends': [{...}, {'friends': [{...}, {'friends': [{...}, {...}], 'id': 7, 'name': 'Devin'}, {'friends': [{...}], 'id': 9, 'name': 'Klein'}], 'id': 8, 'name': 'Kate'}], 'id': 6, 'name': 'Hicks'}, {'friends': [{...}, {'friends': [{'friends': [{...}, {...}], 'id': 6, 'name': 'Hicks'}, {...}, {'friends': [{...}], 'id': 9, 'name': 'Klein'}], 'id': 8, 'name': 'Kate'}], 'id': 7, 'name': 'Devin'}], 'id': 5, 'name': 'Clive'}], 'id': 4, 'name': 'Thor'}], 'id': 3, 'name': 'Chi'}], 'id': 1, 'name': 'Dunn'}, {'friends': [{'friends': [{...}, {...}, {...}], 'id': 1, 'name': 'Dunn'}, {...}, {'friends': [{...}, {'friends': [{...}, {'friends': [{...}, {'friends': [{...}, {'friends': [{...}, {...}], 'id': 7, 'name': 'Devin'}, {'friends': [{...}], 'id': 9, 'name': 'Klein'}], 'id': 8, 'name': 'Kate'}], 'id': 6, 'name': 'Hicks'}, {'friends': [{...}, {'friends': [{'friends': [{...}, {...}], 'id': 6, 'name': 'Hicks'}, {...}, {'friends': [{...}], 'id': 9, 'name': 'Klein'}], 'id': 8, 'name': 'Kate'}], 'id': 7, 'name': 'Devin'}], 'id': 5, 'name': 'Clive'}], 'id': 4, 'name': 'Thor'}], 'id': 3, 'name': 'Chi'}], 'id': 2, 'name': 'Sue'}], 'id': 0, 'name': 'Hero'}
| 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__ import division # integer division is lame
num_users = len(users) # length of the users list
print num_users
avg_connections = total_connections / num_users # 2.4
print avg_connections | 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 smallest
# each pair is (user_id, num_friends)
# [(1, 3), (2, 3), (3, 3), (5, 3), (8, 3),
# (0, 2), (4, 2), (6, 2), (7, 2), (9, 1)] | [(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's not_the_same as all the people in user["friends"]"""
return all(not_the_same(friend, other_user)
for friend in user["friends"])
def friends_of_friend_ids(user):
return Counter(foaf["id"]
for friend in user["friends"] # for each of my friends
for foaf in friend["friends"] # count *their* friends
if not_the_same(user, foaf) # who aren't me
and not_friends(user, foaf)) # and aren't my friends
print friends_of_friend_ids(users[3]) # Counter({0: 2, 5: 1}) | 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, you manage to get your hands on this data, as a list ofpairs (user_id, interest): | 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"),
(3, "statistics"), (3, "regression"), (3, "probability"),
(4, "machine learning"), (4, "regression"), (4, "decision trees"),
(4, "libsvm"), (5, "Python"), (5, "R"), (5, "Java"), (5, "C++"),
(5, "Haskell"), (5, "programming languages"), (6, "statistics"),
(6, "probability"), (6, "mathematics"), (6, "theory"),
(7, "machine learning"), (7, "scikit-learn"), (7, "Mahout"),
(7, "neural networks"), (8, "neural networks"), (8, "deep learning"),
(8, "Big Data"), (8, "artificial intelligence"), (9, "Hadoop"),
(9, "Java"), (9, "MapReduce"), (9, "Big Data")
] | _____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_ids, values are lists of interests for that user_id
interests_by_user_id = defaultdict(list)
for user_id, interest in interests:
interests_by_user_id[user_id].append(interest)
print interests_by_user_id | 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', 'regression', 'decision trees', 'libsvm'], 5: ['Python', 'R', 'Java', 'C++', 'Haskell', 'programming languages'], 6: ['statistics', 'probability', 'mathematics', 'theory'], 7: ['machine learning', 'scikit-learn', 'Mahout', 'neural networks'], 8: ['neural networks', 'deep learning', 'Big Data', 'artificial intelligence'], 9: ['Hadoop', 'Java', 'MapReduce', 'Big Data']})
| 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.5), (76000, 7.5),
(60000, 2.5), (83000, 10),
(48000, 1.9), (63000, 4.2)] | _____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 = {
tenure : sum(salaries) / len(salaries)
for tenure, salaries in salary_by_tenure.items()
}
print average_salary_by_tenure | 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, values are lists of salaries for that bucket
salary_by_tenure_bucket = defaultdict(list)
for salary, tenure in salaries_and_tenures:
bucket = tenure_bucket(tenure)
salary_by_tenure_bucket[bucket].append(salary)
# And finally compute the average salary for each group:
# keys are tenure buckets, values are average salary for that bucket
average_salary_by_bucket = {
tenure_bucket : sum(salaries) / len(salaries)
for tenure_bucket, salaries in salary_by_tenure_bucket.iteritems()
}
print average_salary_by_bucket | {'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, 'artificial': 1, 'storm': 1, 'mongodb': 1, 'intelligence': 1, 'mathematics': 1, 'numpy': 1, 'pandas': 1, 'postgres': 1, 'libsvm': 1, 'trees': 1, 'scipy': 1, 'spark': 1, 'mapreduce': 1, 'c++': 1, 'theory': 1, 'statsmodels': 1, 'mahout': 1})
| 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(wctm_num):
sub_df = df[df['wheezy-copper-turtle-magic'] == wctm_num]
sub_features = [f for f in features if sub_df[f].std() > 1.5]
lofo_imp = LOFOImportance(sub_df, target="target",
features=sub_features,
cv=StratifiedKFold(n_splits=4, random_state=42, shuffle=True), scoring="roc_auc",
model=get_model(), n_jobs=4)
return lofo_imp.get_importance()
plot_importance(get_lofo_importance(0), 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 = 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])
print("Potential gain (AUC):", np.round(np.mean(potential_gain), 5))
features_to_remove | _____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 import tqdm
from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis
from sklearn.pipeline import Pipeline
from sklearn.metrics import roc_auc_score
from sklearn.feature_selection import VarianceThreshold
train = pd.read_csv('../input/train.csv')
test = pd.read_csv('../input/test.csv')
oof_svnu = np.zeros(len(train))
pred_te_svnu = np.zeros(len(test))
oof_svc = np.zeros(len(train))
pred_te_svc = np.zeros(len(test))
oof_knn = np.zeros(len(train))
pred_te_knn = np.zeros(len(test))
oof_lr = np.zeros(len(train))
pred_te_lr = np.zeros(len(test))
oof_mlp = np.zeros(len(train))
pred_te_mlp = np.zeros(len(test))
oof_qda = np.zeros(len(train))
pred_te_qda = np.zeros(len(test))
default_cols = [c for c in train.columns if c not in ['id', 'target', 'wheezy-copper-turtle-magic']]
for i in range(512):
cols = [c for c in default_cols if c != features_to_remove[i]]
train2 = train[train['wheezy-copper-turtle-magic']==i]
test2 = test[test['wheezy-copper-turtle-magic']==i]
idx1 = train2.index; idx2 = test2.index
train2.reset_index(drop=True,inplace=True)
data = pd.concat([pd.DataFrame(train2[cols]), pd.DataFrame(test2[cols])])
data2 = StandardScaler().fit_transform(PCA(svd_solver='full',n_components='mle').fit_transform(data[cols]))
train3 = data2[:train2.shape[0]]; test3 = data2[train2.shape[0]:]
data2 = StandardScaler().fit_transform(VarianceThreshold(threshold=1.5).fit_transform(data[cols]))
train4 = data2[:train2.shape[0]]; test4 = data2[train2.shape[0]:]
# STRATIFIED K FOLD (Using splits=25 scores 0.002 better but is slower)
skf = StratifiedKFold(n_splits=5, random_state=42)
for train_index, test_index in skf.split(train2, train2['target']):
clf = NuSVC(probability=True, kernel='poly', degree=4, gamma='auto', random_state=4, nu=0.59, coef0=0.053)
clf.fit(train3[train_index,:],train2.loc[train_index]['target'])
oof_svnu[idx1[test_index]] = clf.predict_proba(train3[test_index,:])[:,1]
pred_te_svnu[idx2] += clf.predict_proba(test3)[:,1] / skf.n_splits
clf = neighbors.KNeighborsClassifier(n_neighbors=17, p=2.9)
clf.fit(train3[train_index,:],train2.loc[train_index]['target'])
oof_knn[idx1[test_index]] = clf.predict_proba(train3[test_index,:])[:,1]
pred_te_knn[idx2] += clf.predict_proba(test3)[:,1] / skf.n_splits
clf = linear_model.LogisticRegression(solver='saga',penalty='l1',C=0.1)
clf.fit(train3[train_index,:],train2.loc[train_index]['target'])
oof_lr[idx1[test_index]] = clf.predict_proba(train3[test_index,:])[:,1]
pred_te_lr[idx2] += clf.predict_proba(test3)[:,1] / skf.n_splits
clf = neural_network.MLPClassifier(random_state=3, activation='relu', solver='lbfgs', tol=1e-06, hidden_layer_sizes=(250, ))
clf.fit(train3[train_index,:],train2.loc[train_index]['target'])
oof_mlp[idx1[test_index]] = clf.predict_proba(train3[test_index,:])[:,1]
pred_te_mlp[idx2] += clf.predict_proba(test3)[:,1] / skf.n_splits
clf = svm.SVC(probability=True, kernel='poly', degree=4, gamma='auto', random_state=42)
clf.fit(train3[train_index,:],train2.loc[train_index]['target'])
oof_svc[idx1[test_index]] = clf.predict_proba(train3[test_index,:])[:,1]
pred_te_svc[idx2] += clf.predict_proba(test3)[:,1] / skf.n_splits
clf = QuadraticDiscriminantAnalysis(reg_param=0.111)
clf.fit(train4[train_index,:],train2.loc[train_index]['target'])
oof_qda[idx1[test_index]] = clf.predict_proba(train4[test_index,:])[:,1]
pred_te_qda[idx2] += clf.predict_proba(test4)[:,1] / skf.n_splits
print('lr', roc_auc_score(train['target'], oof_lr))
print('knn', roc_auc_score(train['target'], oof_knn))
print('svc', roc_auc_score(train['target'], oof_svc))
print('svcnu', roc_auc_score(train['target'], oof_svnu))
print('mlp', roc_auc_score(train['target'], oof_mlp))
print('qda', roc_auc_score(train['target'], oof_qda))
print('blend 1', roc_auc_score(train['target'], oof_svnu*0.7 + oof_svc*0.05 + oof_knn*0.2 + oof_mlp*0.05))
print('blend 2', roc_auc_score(train['target'], oof_qda*0.5+oof_svnu*0.35 + oof_svc*0.025 + oof_knn*0.1 + oof_mlp*0.025))
oof_svnu = oof_svnu.reshape(-1, 1)
pred_te_svnu = pred_te_svnu.reshape(-1, 1)
oof_svc = oof_svc.reshape(-1, 1)
pred_te_svc = pred_te_svc.reshape(-1, 1)
oof_knn = oof_knn.reshape(-1, 1)
pred_te_knn = pred_te_knn.reshape(-1, 1)
oof_mlp = oof_mlp.reshape(-1, 1)
pred_te_mlp = pred_te_mlp.reshape(-1, 1)
oof_lr = oof_lr.reshape(-1, 1)
pred_te_lr = pred_te_lr.reshape(-1, 1)
oof_qda = oof_qda.reshape(-1, 1)
pred_te_qda = pred_te_qda.reshape(-1, 1)
tr = np.concatenate((oof_svnu, oof_svc, oof_knn, oof_mlp, oof_lr, oof_qda), axis=1)
te = np.concatenate((pred_te_svnu, pred_te_svc, pred_te_knn, pred_te_mlp, pred_te_lr, pred_te_qda), axis=1)
print(tr.shape, te.shape)
oof_lrr = np.zeros(len(train))
pred_te_lrr = np.zeros(len(test))
skf = StratifiedKFold(n_splits=5, random_state=42)
for train_index, test_index in skf.split(tr, train['target']):
lrr = linear_model.LogisticRegression()
lrr.fit(tr[train_index], train['target'][train_index])
oof_lrr[test_index] = lrr.predict_proba(tr[test_index,:])[:,1]
pred_te_lrr += lrr.predict_proba(te)[:,1] / skf.n_splits
print('stack CV score =',round(roc_auc_score(train['target'],oof_lrr),6))
sub = pd.read_csv('../input/sample_submission.csv')
sub['target'] = pred_te_lrr
sub.to_csv('submission_stack.csv', index=False) | 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 pandasodf import ODFReader
import gcat
from htsworkflow.submission.encoded import Document
from htsworkflow.submission.aws_submission import run_aws_cp
# live server & control file
#server = ENCODED('www.encodeproject.org')
spreadsheet_name = "ENCODE_test_miRNA_experiments_01112018"
# test server & datafile
server = ENCODED('test.encodedcc.org')
#spreadsheet_name = os.path.expanduser('~diane/woldlab/ENCODE/C1-encode3-limb-2017-testserver.ods')
server.load_netrc()
validator = DCCValidator(server)
award = 'UM1HG009443' | _____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, atac_uuid)
#print(body['@id']) | _____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 created:
biosample.to_excel('/dev/shm/biosamples.xlsx', index=False) | _____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=False) | _____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.xlsx', index=False) | _____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/shm/replicates.xlsx', index=False) | _____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.* > data/music.zip ่งฃๅunzip data/music.zip -d music``` | %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-phoenix-01-ambient_teknology-0-29.mp3'
song = mp3_to_array(file)
plt.plot(song) | _____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_x.npy', test_x)
np.save('train_y.npy', train_y)
np.save('test_y.npy', test_y) | _____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.shape)
print(train_y.shape)
print(test_x.shape)
print(test_y.shape)
features = train_x.shape[1]
x_inputs = Input(shape=(features, 1), name='x_inputs')
x = Conv1D(128, 256, strides=256, padding='valid', activation='relu')(x_inputs) # strided conv
x = Conv1D(32, 8, activation='relu')(x)
x = MaxPooling1D(4)(x)
x = Conv1D(32, 8, activation='relu')(x)
x = MaxPooling1D(4)(x)
x = Conv1D(32, 8, activation='relu')(x)
x = MaxPooling1D(4)(x)
x = Conv1D(32, 8, activation='relu')(x)
x = MaxPooling1D(4)(x)
x = Flatten()(x)
x = Dense(100, activation='relu')(x)
x_outputs = Dense(50, activation='sigmoid', name='x_outputs')(x)
model = Model(inputs=x_inputs, outputs=x_outputs)
model.compile(optimizer='adam',
loss='categorical_crossentropy')
logger = CSVLogger('history.log')
checkpoint = ModelCheckpoint(
'model.{epoch:02d}-{val_loss:.3f}.h5',
monitor='val_loss',
verbose=1,
save_best_only=True,
mode='auto')
model.fit(train_x, train_y, batch_size=600, epochs=50,
validation_data=[test_x, test_y],
callbacks=[logger, checkpoint]) | _____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, test_y)) | 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 image.Using markers on the lower values will ensure that the segmented objects arefound.See Wikipedia_ for more details on the algorithm. | 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(image, disk(2))
# find continuous region (low gradient -
# where less than 10 for this image) --> markers
# disk(5) is used here to get a more smooth image
markers = rank.gradient(denoised, disk(5)) < 10
markers = ndi.label(markers)[0]
# local gradient (disk(2) is used to keep edges thin)
gradient = rank.gradient(denoised, disk(2))
# process the watershed
labels = watershed(gradient, markers)
# display results
fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(8, 8),
sharex=True, sharey=True)
ax = axes.ravel()
ax[0].imshow(image, cmap=plt.cm.gray)
ax[0].set_title("Original")
ax[1].imshow(gradient, cmap=plt.cm.nipy_spectral)
ax[1].set_title("Local Gradient")
ax[2].imshow(markers, cmap=plt.cm.nipy_spectral)
ax[2].set_title("Markers")
ax[3].imshow(image, cmap=plt.cm.gray)
ax[3].imshow(labels, cmap=plt.cm.nipy_spectral, alpha=.7)
ax[3].set_title("Segmented")
for a in ax:
a.axis('off')
fig.tight_layout()
plt.show() | _____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{\braket}[2]{\langle 1|2\rangle} $$ \newcommand{\dot}[2]{ 1 \cdot 2} $$ \newcommand{\biginner}[2]{\left\langle 1,2\right\rangle} $$ \newcommand{\mymatrix}[2]{\left( \begin{array}{1} 2\end{array} \right)} $$ \newcommand{\myvector}[1]{\mymatrix{c}{1}} $$ \newcommand{\myrvector}[1]{\mymatrix{r}{1}} $$ \newcommand{\mypar}[1]{\left( 1 \right)} $$ \newcommand{\mybigpar}[1]{ \Big( 1 \Big)} $$ \newcommand{\sqrttwo}{\frac{1}{\sqrt{2}}} $$ \newcommand{\dsqrttwo}{\dfrac{1}{\sqrt{2}}} $$ \newcommand{\onehalf}{\frac{1}{2}} $$ \newcommand{\donehalf}{\dfrac{1}{2}} $$ \newcommand{\hadamard}{ \mymatrix{rr}{ \sqrttwo & \sqrttwo \\ \sqrttwo & -\sqrttwo }} $$ \newcommand{\vzero}{\myvector{1\\0}} $$ \newcommand{\vone}{\myvector{0\\1}} $$ \newcommand{\stateplus}{\myvector{ \sqrttwo \\ \sqrttwo } } $$ \newcommand{\stateminus}{ \myrvector{ \sqrttwo \\ -\sqrttwo } } $$ \newcommand{\myarray}[2]{ \begin{array}{1}2\end{array}} $$ \newcommand{\X}{ \mymatrix{cc}{0 & 1 \\ 1 & 0} } $$ \newcommand{\I}{ \mymatrix{rr}{1 & 0 \\ 0 & 1} } $$ \newcommand{\Z}{ \mymatrix{rr}{1 & 0 \\ 0 & -1} } $$ \newcommand{\Htwo}{ \mymatrix{rrrr}{ \frac{1}{2} & \frac{1}{2} & \frac{1}{2} & \frac{1}{2} \\ \frac{1}{2} & -\frac{1}{2} & \frac{1}{2} & -\frac{1}{2} \\ \frac{1}{2} & \frac{1}{2} & -\frac{1}{2} & -\frac{1}{2} \\ \frac{1}{2} & -\frac{1}{2} & -\frac{1}{2} & \frac{1}{2} } } $$ \newcommand{\CNOT}{ \mymatrix{cccc}{1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & 0 & 1 \\ 0 & 0 & 1 & 0} } $$ \newcommand{\norm}[1]{ \left\lVert 1 \right\rVert } $$ \newcommand{\pstate}[1]{ \lceil \mspace{-1mu} 1 \mspace{-1.5mu} \rfloor } $ Solutions for Probabilistic Bit Task 2 Suppose that Fyodor hiddenly rolls a loaded (tricky) dice with the bias $$ Pr(1):Pr(2):Pr(3):Pr(4):Pr(5):Pr(6) = 7:5:4:2:6:1 . $$Represent your information on the result as a column vector. Remark that the size of your column should be 6.You may use python for your calculations. Solution | # 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 one portion is",one_portion)
print() # print an empty line
# now we can calculate the probabilities of rolling 1,2,3,4,5, and 6
for i in range(6):
print("the probability of rolling",(i+1),"is",(one_portion*all_portions[i])) | _____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 competition](https://www.kaggle.com/c/porto-seguro-safe-driver-prediction), the challenge is to build a model that predicts the probability that a driver will initiate an auto insurance claim in the next year. While Porto Seguro has used machine learning for the past 20 years, theyโre looking to Kaggleโs machine learning community to explore new, more powerful methods. A more accurate prediction will allow them to further tailor their prices, and hopefully make auto insurance coverage more accessible to more drivers.Lucky for you, a machine learning model was built to solve the Porto Seguro problem by the data scientist on your team. The solution notebook has steps to load data, split the data into test and train sets, train, evaluate and save a LightGBM model that will be used for the future challenges. Hint: use shift + enter to run the code cells below. Once the cell turns from [*] to [], you can be sure the cell has run. Import Needed PackagesImport the packages needed for this solution notebook. The most widely used packages for machine learning for [scikit-learn](https://scikit-learn.org/stable/), [pandas](https://pandas.pydata.org/docs/getting_started/index.htmlgetting-started), and [numpy](https://numpy.org/). These packages have various features, as well as a lot of clustering, regression and classification algorithms that make it a good choice for data mining and data analysis. In this notebook, we're using a training function from [lightgbm](https://lightgbm.readthedocs.io/en/latest/index.html). | 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 object youโre trying to analyze. Typically, features are the columns of the data that you are training your model with minus the label. In machine learning, a label (categorical) or target (regression) is the output you get from your model after training it. | 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(features_valid, label=labels_valid, free_raw_data=False) | _____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 scientist used an algorithm called [LightGBM](https://lightgbm.readthedocs.io/en/latest/), which primarily used for unbalanced datasets. AUC will be explained in the next cell. | 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,
valid_sets=valid_data,
num_boost_round=500,
early_stopping_rounds=20) | [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] valid_0's auc: 0.622278
[11] valid_0's auc: 0.622433
[12] valid_0's auc: 0.623423
[13] valid_0's auc: 0.623618
[14] valid_0's auc: 0.62414
[15] valid_0's auc: 0.624421
[16] valid_0's auc: 0.624512
[17] valid_0's auc: 0.625151
[18] valid_0's auc: 0.62529
[19] valid_0's auc: 0.625437
[20] valid_0's auc: 0.62563
[21] valid_0's auc: 0.625963
[22] valid_0's auc: 0.626147
[23] valid_0's auc: 0.626383
[24] valid_0's auc: 0.626618
[25] valid_0's auc: 0.626586
[26] valid_0's auc: 0.626839
[27] valid_0's auc: 0.626972
[28] valid_0's auc: 0.626935
[29] valid_0's auc: 0.626946
[30] valid_0's auc: 0.627204
[31] valid_0's auc: 0.627252
[32] valid_0's auc: 0.627302
[33] valid_0's auc: 0.627249
[34] valid_0's auc: 0.627517
[35] valid_0's auc: 0.627755
[36] valid_0's auc: 0.62766
[37] valid_0's auc: 0.627483
[38] valid_0's auc: 0.627578
[39] valid_0's auc: 0.627433
[40] valid_0's auc: 0.627573
[41] valid_0's auc: 0.627908
[42] valid_0's auc: 0.627968
[43] valid_0's auc: 0.628082
[44] valid_0's auc: 0.628398
[45] valid_0's auc: 0.628763
[46] valid_0's auc: 0.629011
[47] valid_0's auc: 0.629321
[48] valid_0's auc: 0.629341
[49] valid_0's auc: 0.629353
[50] valid_0's auc: 0.629291
[51] valid_0's auc: 0.629447
[52] valid_0's auc: 0.629507
[53] valid_0's auc: 0.629725
[54] valid_0's auc: 0.630048
[55] valid_0's auc: 0.630085
[56] valid_0's auc: 0.630035
[57] valid_0's auc: 0.630236
[58] valid_0's auc: 0.630486
[59] valid_0's auc: 0.630663
[60] valid_0's auc: 0.630787
[61] valid_0's auc: 0.630932
[62] valid_0's auc: 0.631004
[63] valid_0's auc: 0.631161
[64] valid_0's auc: 0.631407
[65] valid_0's auc: 0.631408
[66] valid_0's auc: 0.631515
[67] valid_0's auc: 0.631631
[68] valid_0's auc: 0.631628
[69] valid_0's auc: 0.631703
[70] valid_0's auc: 0.631781
[71] valid_0's auc: 0.631786
[72] valid_0's auc: 0.631779
[73] valid_0's auc: 0.632022
[74] valid_0's auc: 0.632086
[75] valid_0's auc: 0.632107
[76] valid_0's auc: 0.632201
[77] valid_0's auc: 0.632165
[78] valid_0's auc: 0.632335
[79] valid_0's auc: 0.632446
[80] valid_0's auc: 0.63254
[81] valid_0's auc: 0.632654
[82] valid_0's auc: 0.632663
[83] valid_0's auc: 0.632811
[84] valid_0's auc: 0.63291
[85] valid_0's auc: 0.632993
[86] valid_0's auc: 0.632962
[87] valid_0's auc: 0.632941
[88] valid_0's auc: 0.633062
[89] valid_0's auc: 0.633144
[90] valid_0's auc: 0.633242
[91] valid_0's auc: 0.633336
[92] valid_0's auc: 0.633453
[93] valid_0's auc: 0.633556
[94] valid_0's auc: 0.633648
[95] valid_0's auc: 0.633762
[96] valid_0's auc: 0.633831
[97] valid_0's auc: 0.633922
[98] valid_0's auc: 0.633908
[99] valid_0's auc: 0.633958
[100] valid_0's auc: 0.634122
[101] valid_0's auc: 0.634278
[102] valid_0's auc: 0.634301
[103] valid_0's auc: 0.634313
[104] valid_0's auc: 0.634366
[105] valid_0's auc: 0.634497
[106] valid_0's auc: 0.634442
[107] valid_0's auc: 0.634487
[108] valid_0's auc: 0.634578
[109] valid_0's auc: 0.634676
[110] valid_0's auc: 0.63479
[111] valid_0's auc: 0.634846
[112] valid_0's auc: 0.634918
[113] valid_0's auc: 0.63501
[114] valid_0's auc: 0.634965
[115] valid_0's auc: 0.635029
[116] valid_0's auc: 0.635077
[117] valid_0's auc: 0.635075
[118] valid_0's auc: 0.6352
[119] valid_0's auc: 0.635215
[120] valid_0's auc: 0.635231
[121] valid_0's auc: 0.635276
[122] valid_0's auc: 0.635268
[123] valid_0's auc: 0.635221
[124] valid_0's auc: 0.635178
[125] valid_0's auc: 0.635221
[126] valid_0's auc: 0.635288
[127] valid_0's auc: 0.635345
[128] valid_0's auc: 0.635348
[129] valid_0's auc: 0.635414
[130] valid_0's auc: 0.635418
[131] valid_0's auc: 0.635352
[132] valid_0's auc: 0.635402
[133] valid_0's auc: 0.635497
[134] valid_0's auc: 0.635545
[135] valid_0's auc: 0.63565
[136] valid_0's auc: 0.635622
[137] valid_0's auc: 0.635664
[138] valid_0's auc: 0.635781
[139] valid_0's auc: 0.635735
[140] valid_0's auc: 0.635719
[141] valid_0's auc: 0.635815
[142] valid_0's auc: 0.635799
[143] valid_0's auc: 0.63583
[144] valid_0's auc: 0.635898
[145] valid_0's auc: 0.635924
[146] valid_0's auc: 0.635885
[147] valid_0's auc: 0.635919
[148] valid_0's auc: 0.63598
[149] valid_0's auc: 0.636035
[150] valid_0's auc: 0.636087
[151] valid_0's auc: 0.636139
[152] valid_0's auc: 0.63617
[153] valid_0's auc: 0.636128
[154] valid_0's auc: 0.636096
[155] valid_0's auc: 0.636206
[156] valid_0's auc: 0.636259
[157] valid_0's auc: 0.636289
[158] valid_0's auc: 0.636283
[159] valid_0's auc: 0.636287
[160] valid_0's auc: 0.636293
[161] valid_0's auc: 0.636324
[162] valid_0's auc: 0.63633
[163] valid_0's auc: 0.636367
[164] valid_0's auc: 0.636438
[165] valid_0's auc: 0.636483
[166] valid_0's auc: 0.636577
[167] valid_0's auc: 0.636645
[168] valid_0's auc: 0.63659
[169] valid_0's auc: 0.636595
[170] valid_0's auc: 0.636672
[171] valid_0's auc: 0.636719
[172] valid_0's auc: 0.636755
[173] valid_0's auc: 0.636833
[174] valid_0's auc: 0.636908
[175] valid_0's auc: 0.636929
[176] valid_0's auc: 0.636928
[177] valid_0's auc: 0.636962
[178] valid_0's auc: 0.636969
[179] valid_0's auc: 0.636995
[180] valid_0's auc: 0.637059
[181] valid_0's auc: 0.637089
[182] valid_0's auc: 0.637085
[183] valid_0's auc: 0.637121
[184] valid_0's auc: 0.637131
[185] valid_0's auc: 0.637133
[186] valid_0's auc: 0.637144
[187] valid_0's auc: 0.637189
[188] valid_0's auc: 0.637173
[189] valid_0's auc: 0.63719
[190] valid_0's auc: 0.637205
[191] valid_0's auc: 0.637131
[192] valid_0's auc: 0.637159
[193] valid_0's auc: 0.637185
[194] valid_0's auc: 0.63719
[195] valid_0's auc: 0.637224
[196] valid_0's auc: 0.637219
[197] valid_0's auc: 0.637193
[198] valid_0's auc: 0.637297
[199] valid_0's auc: 0.637329
[200] valid_0's auc: 0.6373
[201] valid_0's auc: 0.637257
[202] valid_0's auc: 0.637253
[203] valid_0's auc: 0.637261
[204] valid_0's auc: 0.637252
[205] valid_0's auc: 0.637273
[206] valid_0's auc: 0.637297
[207] valid_0's auc: 0.637345
[208] valid_0's auc: 0.637401
[209] valid_0's auc: 0.637456
[210] valid_0's auc: 0.637392
[211] valid_0's auc: 0.637373
[212] valid_0's auc: 0.63741
[213] valid_0's auc: 0.637459
[214] valid_0's auc: 0.637496
[215] valid_0's auc: 0.637539
[216] valid_0's auc: 0.637546
[217] valid_0's auc: 0.637535
[218] valid_0's auc: 0.637511
[219] valid_0's auc: 0.6375
[220] valid_0's auc: 0.637502
[221] valid_0's auc: 0.637493
[222] valid_0's auc: 0.637431
[223] valid_0's auc: 0.637413
[224] valid_0's auc: 0.637421
[225] valid_0's auc: 0.637368
[226] valid_0's auc: 0.637374
[227] valid_0's auc: 0.637374
[228] valid_0's auc: 0.637413
[229] valid_0's auc: 0.637429
[230] valid_0's auc: 0.637437
[231] valid_0's auc: 0.637488
[232] valid_0's auc: 0.637531
[233] valid_0's auc: 0.637529
[234] valid_0's auc: 0.637567
[235] valid_0's auc: 0.637599
[236] valid_0's auc: 0.637624
[237] valid_0's auc: 0.637659
[238] valid_0's auc: 0.637586
[239] valid_0's auc: 0.637656
[240] valid_0's auc: 0.637684
[241] valid_0's auc: 0.637682
[242] valid_0's auc: 0.637751
[243] valid_0's auc: 0.637722
[244] valid_0's auc: 0.637714
[245] valid_0's auc: 0.637647
[246] valid_0's auc: 0.637679
[247] valid_0's auc: 0.637679
[248] valid_0's auc: 0.637735
[249] valid_0's auc: 0.6377
[250] valid_0's auc: 0.637738
[251] valid_0's auc: 0.637708
[252] valid_0's auc: 0.637688
[253] valid_0's auc: 0.637725
[254] valid_0's auc: 0.637697
[255] valid_0's auc: 0.637689
[256] valid_0's auc: 0.637714
[257] valid_0's auc: 0.637688
[258] valid_0's auc: 0.637732
[259] valid_0's auc: 0.637703
[260] valid_0's auc: 0.63775
[261] valid_0's auc: 0.637715
[262] valid_0's auc: 0.637711
Early stopping, best iteration is:
[242] valid_0's auc: 0.637751
| 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) ROC (Receiver Operating Characteristics) curve. It is one of the most important evaluation metrics for checking any classification modelโs performance.<img src="https://www.researchgate.net/profile/Oxana_Trifonova/publication/276079439/figure/fig2/AS:614187332034565@1523445079168/An-example-of-ROC-curves-with-good-AUC-09-and-satisfactory-AUC-065-parameters.png" alt="Markdown Monster icon" style="float: left; margin-right: 12px; width: 320px; height: 239px;" /> | 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','Current Value','KMs Driven','Year','max_power','Mileage','Engine','Gear Box']
i=0
while i < 8:
fig = plt.figure(figsize=[15,20])
plt.subplot(4,2,1)
sns.boxplot(x=num_cols[i], data=df)
i += 1
plt.subplot(4,2,2)
sns.boxplot(x=num_cols[i], data=df)
i += 1
| _____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_first=True)
sns.set(rc={'figure.figsize':(15,15)})
sns.heatmap(final_dataset.corr(),annot=True,cmap="RdBu")
final_dataset.corr()['Selling Price'].sort_values(ascending=False)
y = final_dataset['Selling Price']
X = final_dataset.drop('Selling Price',axis=1) | _____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_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1)
print("x train: ",X_train.shape)
print("x test: ",X_test.shape)
print("y train: ",y_train.shape)
print("y test: ",y_test.shape)
CV = []
R2_train = []
R2_test = []
MAE=[]
MSE=[]
RMSE=[]
def car_pred_model(model):
# R2 score of train set
y_pred_train = model.predict(X_train)
R2_train_model = r2_score(y_train,y_pred_train)
R2_train.append(round(R2_train_model,2))
# R2 score of test set
y_pred_test = model.predict(X_test)
R2_test_model = r2_score(y_test,y_pred_test)
R2_test.append(round(R2_test_model,2))
# R2 mean of train set using Cross validation
cross_val = cross_val_score(model ,X_train ,y_train ,cv=5)
cv_mean = cross_val.mean()
CV.append(round(cv_mean,2))
print("Train R2-score :",round(R2_train_model,2))
print("Test R2-score :",round(R2_test_model,2))
print("Train CV scores :",cross_val)
print("Train CV mean :",round(cv_mean,2))
MAE.append(metrics.mean_absolute_error(y_test, y_pred_test))
MSE.append(metrics.mean_squared_error(y_test, y_pred_test))
RMSE.append(np.sqrt(metrics.mean_squared_error(y_test, y_pred_test)))
print('MAE:', metrics.mean_absolute_error(y_test, y_pred_test))
print('MSE:', metrics.mean_squared_error(y_test, y_pred_test))
print('RMSE:', np.sqrt(metrics.mean_squared_error(y_test, y_pred_test)))
fig, ax = plt.subplots(1,2,figsize = (12,6))
ax[0].set_title('Residual Plot of Train samples')
sns.distplot((y_test-y_pred_test),hist = True,ax = ax[0])
ax[0].set_xlabel('y_train - y_pred_train')
# Y_test vs Y_train scatter plot
ax[1].set_title('y_test vs y_pred_test')
ax[1].scatter(x = y_test, y = y_pred_test)
ax[1].set_xlabel('y_test')
ax[1].set_ylabel('y_pred_test')
plt.show() | _____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 leaf node.
min_samples_leaf=[1,2,5,7]
# Number of fearures to be considered at each split
max_features=['auto','sqrt']
# Hyperparameters dict
param_grid = {"n_estimators":n_estimators,
"max_depth":max_depth,
"min_samples_split":min_samples_split,
"min_samples_leaf":min_samples_leaf,
"max_features":max_features}
rf_rs = RandomizedSearchCV(estimator = rf, param_distributions = param_grid,cv = 5, random_state=42, n_jobs = 1)
rf_rs.fit(X_train,y_train)
car_pred_model(rf_rs) | 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 node
min_samples_split=list(range(4,9,2))
# Minimum number of samples required to be at a leaf node.
min_samples_leaf=[1,2,5,7]
# Number of fearures to be considered at each split
max_features=['auto','sqrt']
# Hyperparameters dict
param_grid = {"learning_rate":learning_rate,
"n_estimators":n_estimators,
"max_depth":max_depth,
"min_samples_split":min_samples_split,
"min_samples_leaf":min_samples_leaf,
"max_features":max_features}
gb_rs = RandomizedSearchCV(estimator = gb, param_distributions = param_grid,cv = 5, random_state=42, n_jobs = 1)
gb_rs.fit(X_train,y_train)
car_pred_model(gb_rs)
gb_rs.best_params_
gb_rs.best_score_
Models = ["Linear Regression","Ridge","Lasso","RandomForest Regressor","GradientBoosting Regressor"]
score_comparison=pd.DataFrame({'Model': Models,'R Squared(Train)': R2_train,'R Squared(Test)': R2_test,'CV score mean(Train)': CV,
'Mean Absolute Error':MAE,'Mean Squared Error':MSE, 'Root Mean Squared Error':RMSE})
score_comparison
file = open('random_forest_regression_model.pkl', 'wb')
# dump information to that file
pickle.dump(rf_rs, file) | _____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[30]`็ไฝๆฐใๅ
ณ้ฎๆฏ`a`ๆฐๅๆฏไปไน่งๅพๅข๏ผๆ่ก็ไธ็ๅฐฑๆไบ๏ผๅ่ๆฏๆฐๅญฆๅคชๅฅฝ็ๆณไธๅบๆฅ๏ผๅ ไธบๅฎไธๆฏไปปไฝ็ๆฐๅญฆ่งๅพใ> ๅค่งๆฐๅ๏ผLook-and-say sequence๏ผ็ฌฌn้กนๆ่ฟฐไบ็ฌฌn-1้กน็ๆฐๅญๅๅธใๅฎไปฅ1ๅผๅง๏ผ> 1. 1๏ผ่ฏปไฝ1ไธชโ1โ๏ผๅณ11> 1. 11๏ผ่ฏปไฝ2ไธชโ1โ๏ผๅณ21> 1. 21๏ผ่ฏปไฝ1ไธชโ2โ๏ผ1ไธชโ1โ๏ผๅณ1211> 1. 1211๏ผ่ฏปไฝ1ไธชโ1โ๏ผ1ไธชโ2โ๏ผ2ไธชโ1โ๏ผๅณ111221> 1. 111221๏ผ่ฏปไฝ3ไธชโ1โ๏ผ2ไธชโ2โ๏ผ1ไธชโ1โ๏ผๅณ312211> > 1, 11, 21, 1211, 111221, 312211, 13112221, 1113213211, ... ๏ผOEISไธญ็ๆฐๅA005150๏ผ> From [wikipedia.org](https://zh.wikipedia.org/wiki/%E5%A4%96%E8%A7%80%E6%95%B8%E5%88%97)ๅบ่ฏไธๅค่ฏด๏ผ็ดๆฅไธไปฃ็ ๏ผ็จๆญฃๅๅบ่ฏฅไผๅฎนๆไธไบ๏ผ | 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 torch.utils.data import random_split
from torchsummary import summary
%matplotlib inline | _____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, num_workers=4, pin_memory=True)
test_loader = DataLoader(test_dataset, batch_size*2, num_workers=4, pin_memory=True) | _____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
loss = F.cross_entropy(out, labels) # Calculate loss
return loss
def validation_step(self, batch):
images, labels = batch
out = self(images) # Generate predictions
loss = F.cross_entropy(out, labels) # Calculate loss
acc = accuracy(out, labels) # Calculate accuracy
return {'val_loss': loss.detach(), 'val_acc': acc}
def validation_epoch_end(self, outputs):
batch_losses = [x['val_loss'] for x in outputs]
epoch_loss = torch.stack(batch_losses).mean() # Combine losses
batch_accs = [x['val_acc'] for x in outputs]
epoch_acc = torch.stack(batch_accs).mean() # Combine accuracies
return {'val_loss': epoch_loss.item(), 'val_acc': epoch_acc.item()}
def epoch_end(self, epoch, result):
print("Epoch [{}], val_loss: {:.4f}, val_acc: {:.4f}".format(epoch,
result['val_loss'], result['val_acc']))
def evaluate(model, val_loader):
outputs = [model.validation_step(batch) for batch in val_loader]
return model.validation_epoch_end(outputs)
def fit(epochs, lr, model, train_loader, val_loader, opt_func=torch.optim.SGD):
history = []
optimizer = opt_func(model.parameters(), lr)
for epoch in range(epochs):
# Training Phase
for batch in train_loader:
loss = model.training_step(batch)
loss.backward()
optimizer.step()
optimizer.zero_grad()
# Validation phase
result = evaluate(model, val_loader)
model.epoch_end(epoch, result)
history.append(result)
return history
torch.cuda.is_available()
def get_default_device():
"""Pick GPU if available, else CPU"""
if torch.cuda.is_available():
return torch.device('cuda')
else:
return torch.device('cpu')
device = get_default_device()
device
def to_device(data, device):
"""Move tensor(s) to chosen device"""
if isinstance(data, (list,tuple)):
return [to_device(x, device) for x in data]
return data.to(device, non_blocking=True)
class DeviceDataLoader():
"""Wrap a dataloader to move data to a device"""
def __init__(self, dl, device):
self.dl = dl
self.device = device
def __iter__(self):
"""Yield a batch of data after moving it to device"""
for b in self.dl:
yield to_device(b, self.device)
def __len__(self):
"""Number of batches"""
return len(self.dl)
def plot_losses(history):
losses = [x['val_loss'] for x in history]
plt.plot(losses, '-x')
plt.xlabel('epoch')
plt.ylabel('loss')
plt.title('Loss vs. No. of epochs')
train_loader = DeviceDataLoader(train_loader, device)
val_loader = DeviceDataLoader(val_loader, device)
test_loader = DeviceDataLoader(test_loader, device) | _____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):
# Flatten images into vectors
out = xb.view(xb.size(0), -1)
# Apply layers & activation functions
out = self.linear1(out)
out = F.relu(out)
out = self.linear2(out)
out = F.relu(out)
out = self.linear3(out)
return out
model = to_device(CIFAR10Model(), device)
summary(model, (3, 32, 32))
history = [evaluate(model, val_loader)]
history
history += fit(10, 1e-1, model, train_loader, val_loader)
history += fit(10, 1e-2, model, train_loader, val_loader)
history += fit(10, 1e-3, model, train_loader, val_loader)
plot_losses(history)
def plot_accuracies(history):
accuracies = [x['val_acc'] for x in history]
plt.plot(accuracies, '-x')
plt.xlabel('epoch')
plt.ylabel('accuracy')
plt.title('Accuracy vs. No. of epochs')
plot_accuracies(history)
## test set:
evaluate(model, test_loader) | _____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=root_path)
# ๊ฐ ํด๋์ค์ ๋์์ ํ์ผ์ ํ์์ผ๋ก ๋ง๋ ํด๋์ ๊ฒฝ๋ก๋ฅผ ์ทจ๋
for class_list_i in (class_list): # ํด๋์ค๋ณ๋ก ๋ฃจํ
# ํด๋์ค์ ํด๋ ๊ฒฝ๋ก๋ฅผ ์ทจ๋
class_path = os.path.join(root_path, class_list_i)
# ๊ฐ ํด๋์ค์ ํด๋ ๋ด ํ์ ํด๋๋ฅผ ์ทจ๋ํ๋ ๋ฃจํ
for file_name in os.listdir(class_path):
# ํ์ผ๋ช
๊ณผ ํ์ฅ์๋ก ๋ถํ
name, ext = os.path.splitext(file_name)
# mp4 ํ์ผ์ด ์๋๊ฑฐ๋, ํด๋ ๋ฑ์ ๋ฌด์
if ext == '.mp4':
continue
# ๋์์ ํ์ผ์ ํ์์ผ๋ก ๋ถํ ํด ์ ์ฅํ ํด๋์ ๊ฒฝ๋ก๋ฅผ ์ทจ๋
video_img_directory_path = os.path.join(class_path, name)
# vieo_list์ ์ถ๊ฐ
video_list.append(video_img_directory_path)
return video_list
# ๋์ ํ์ธ
root_path = './data/kinetics_videos/'
video_list = make_datapath_list(root_path)
print(video_list[0])
print(video_list[1])
| ./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() # ์ด๋ฒ์๋ ์๋ต
GroupResize(int(resize)), # ํ์์ ํ๊บผ๋ฒ์ ๋ฆฌ์ฌ์ด์ฆ
GroupCenterCrop(crop_size), # ํ์์ ํ๊บผ๋ฒ์ center crop
GroupToTensor(), # ๋ฐ์ดํฐ๋ฅผ PyTorch ํ
์๋ก
GroupImgNormalize(mean, std), # ๋ฐ์ดํฐ๋ฅผ ํ์คํ
Stack() # ์ฌ๋ฌ ํ์์ frames์ฐจ์์ผ๋ก ๊ฒฐํฉ์ํจ๋ค
]),
'val': torchvision.transforms.Compose([
GroupResize(int(resize)), # ํ์์ ํ๊บผ๋ฒ์ ๋ฆฌ์ฌ์ด์ฆ
GroupCenterCrop(crop_size), # ํ์์ ํ๊บผ๋ฒ์ center crop
GroupToTensor(), # ๋ฐ์ดํฐ๋ฅผ PyTorch ํ
์๋ก
GroupImgNormalize(mean, std), # ๋ฐ์ดํฐ๋ฅผ ํ์คํ
Stack() # ์ฌ๋ฌ ํ์์ frames์ฐจ์์ผ๋ก ๊ฒฐํฉ์ํจ๋ค
])
}
def __call__(self, img_group, phase):
"""
Parameters
----------
phase : 'train' or 'val'
์ ์ฒ๋ฆฌ ๋ชจ๋ ์ง์
"""
return self.data_transform[phase](img_group)
# ์ ์ฒ๋ฆฌ๋ก ์ฌ์ฉํ ํด๋์ค๋ค์ ์ ์
class GroupResize():
'''ํ์ ํฌ๊ธฐ๋ฅผ ํ๊บผ๋ฒ์ ์ฌ์กฐ์ (rescale)ํ๋ ํด๋์ค.
ํ์์ ์งง์ ๋ณ์ ๊ธธ์ด๊ฐ resize๋ก ๋ณํ๋๋ค.
ํ๋ฉด ๋น์จ์ ์ ์ง๋๋ค.
'''
def __init__(self, resize, interpolation=Image.BILINEAR):
'''rescale ์ฒ๋ฆฌ ์ค๋น'''
self.rescaler = torchvision.transforms.Resize(resize, interpolation)
def __call__(self, img_group):
'''img_group(๋ฆฌ์คํธ)์ ๊ฐ img์ rescale ์ค์'''
return [self.rescaler(img) for img in img_group]
class GroupCenterCrop():
'''ํ์์ ํ๊บผ๋ฒ์ center crop ํ๋ ํด๋์ค.
(crop_size, crop_size)์ ํ์์ ์๋ผ๋ธ๋ค.
'''
def __init__(self, crop_size):
'''center crop ์ฒ๋ฆฌ๋ฅผ ์ค๋น'''
self.ccrop = torchvision.transforms.CenterCrop(crop_size)
def __call__(self, img_group):
'''img_group(๋ฆฌ์คํธ)์ ๊ฐ img์ center crop ์ค์'''
return [self.ccrop(img) for img in img_group]
class GroupToTensor():
'''ํ์์ ํ๊บผ๋ฒ์ ํ
์๋ก ๋ง๋๋ ํด๋์ค.
'''
def __init__(self):
'''ํ
์ํํ๋ ์ฒ๋ฆฌ๋ฅผ ์ค๋น'''
self.to_tensor = torchvision.transforms.ToTensor()
def __call__(self, img_group):
'''img_group(๋ฆฌ์คํธ)์ ๊ฐ img์ ํ
์ํ ์ค์
0๋ถํฐ 1๊น์ง๊ฐ ์๋๋ผ, 0๋ถํฐ 255๊น์ง๋ฅผ ๋ค๋ฃจ๋ฏ๋ก, 255๋ฅผ ๊ณฑํด์ ๊ณ์ฐํ๋ค.
0๋ถํฐ 255๋ก ๋ค๋ฃจ๋ ๊ฒ์, ํ์ต๋ ๋ฐ์ดํฐ ํ์์ ๋ง์ถ๊ธฐ ์ํจ
'''
return [self.to_tensor(img)*255 for img in img_group]
class GroupImgNormalize():
'''ํ์์ ํ๊บผ๋ฒ์ ํ์คํํ๋ ํด๋์ค.
'''
def __init__(self, mean, std):
'''ํ์คํ ์ฒ๋ฆฌ๋ฅผ ์ค๋น'''
self.normlize = torchvision.transforms.Normalize(mean, std)
def __call__(self, img_group):
'''img_group(๋ฆฌ์คํธ)์ ๊ฐ img์ ํ์คํ ์ค์'''
return [self.normlize(img) for img in img_group]
class Stack():
'''ํ์์ ํ๋์ ํ
์๋ก ์ ๋ฆฌํ๋ ํด๋์ค.
'''
def __call__(self, img_group):
'''img_group์ torch.Size([3, 224, 224])๋ฅผ ์์๋ก ํ๋ ๋ฆฌ์คํธ
'''
ret = torch.cat([(x.flip(dims=[0])).unsqueeze(dim=0)
for x in img_group], dim=0) # frames ์ฐจ์์ผ๋ก ๊ฒฐํฉ
# x.flip(dims=[0])์ ์์ ์ฑ๋์ RGB์์ BGR์ผ๋ก ์์๋ฅผ ๋ฐ๊พธ๊ณ ์์ต๋๋ค(์๋์ ํ์ต ๋ฐ์ดํฐ๊ฐ BGR์ด์๊ธฐ ๋๋ฌธ์
๋๋ค)
# unsqueeze(dim=0)์ ์๋กญ๊ฒ frames์ฉ์ ์ฐจ์์ ์์ฑํ๊ณ ์์ต๋๋ค
return ret
| _____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.DictReader(f, delimiter=",", quotechar='"')
# 1ํ์ฉ ์ฝ์ด, ์ฌ์ ํ ๋ณ์์ ์ถ๊ฐํฉ๋๋ค
for row in reader:
label_id_dict.setdefault(
row["class_label"], int(row["label_id"])-1)
id_label_dict.setdefault(
int(row["label_id"])-1, row["class_label"])
return label_id_dict, id_label_dict
# ํ์ธ
label_dicitionary_path = './video_download/kinetics_400_label_dicitionary.csv'
label_id_dict, id_label_dict = get_label_id_dictionary(label_dicitionary_path)
label_id_dict
class VideoDataset(torch.utils.data.Dataset):
"""
๋์์ Dataset
"""
def __init__(self, video_list, label_id_dict, num_segments, phase, transform, img_tmpl='image_{:05d}.jpg'):
self.video_list = video_list # ๋์์ ํด๋์ ๊ฒฝ๋ก ๋ฆฌ์คํธ
self.label_id_dict = label_id_dict # ๋ผ๋ฒจ๋ช
์ id๋ก ๋ณํํ๋ ์ฌ์ ํ ๋ณ์
self.num_segments = num_segments # ๋์์์ ์ด๋ป๊ฒ ๋ถํ ํด ์ฌ์ฉํ ์ง๋ฅผ ๊ฒฐ์
self.phase = phase # train or val
self.transform = transform # ์ ์ฒ๋ฆฌ
self.img_tmpl = img_tmpl # ์ฝ์ด๋ค์ผ ํ์ ํ์ผ๋ช
์ ํ
ํ๋ฆฟ
def __len__(self):
'''๋์์ ์๋ฅผ ๋ฐํ'''
return len(self.video_list)
def __getitem__(self, index):
'''
์ ์ฒ๋ฆฌํ ํ์๋ค์ ๋ฐ์ดํฐ์ ๋ผ๋ฒจ, ๋ผ๋ฒจ ID๋ฅผ ์ทจ๋
'''
imgs_transformed, label, label_id, dir_path = self.pull_item(index)
return imgs_transformed, label, label_id, dir_path
def pull_item(self, index):
'''์ ์ฒ๋ฆฌํ ํ์๋ค์ ๋ฐ์ดํฐ์ ๋ผ๋ฒจ, ๋ผ๋ฒจ ID๋ฅผ ์ทจ๋'''
# 1. ํ์๋ค์ ๋ฆฌ์คํธ์์ ์ฝ๊ธฐ
dir_path = self.video_list[index] # ํ์์ด ์ ์ฅ๋ ํด๋
indices = self._get_indices(dir_path) # ์ฝ์ด๋ค์ผ ํ์ idx๋ฅผ ๊ตฌํ๊ธฐ
img_group = self._load_imgs(
dir_path, self.img_tmpl, indices) # ๋ฆฌ์คํธ๋ก ์ฝ๊ธฐ
# 2. ๋ผ๋ฒจ์ ์ทจ๋ํด id๋ก ๋ณํ
label = (dir_path.split('/')[3].split('/')[0])
label_id = self.label_id_dict[label] # id๋ฅผ ์ทจ๋
# 3. ์ ์ฒ๋ฆฌ ์ค์
imgs_transformed = self.transform(img_group, phase=self.phase)
return imgs_transformed, label, label_id, dir_path
def _load_imgs(self, dir_path, img_tmpl, indices):
'''ํ์์ ํ๊บผ๋ฒ์ ์ฝ์ด๋ค์ฌ, ๋ฆฌ์คํธํํ๋ ํจ์'''
img_group = [] # ํ์์ ์ ์ฅํ ๋ฆฌ์คํธ
for idx in indices:
# ํ์ ๊ฒฝ๋ก ์ทจ๋
file_path = os.path.join(dir_path, img_tmpl.format(idx))
# ํ์ ์ฝ๊ธฐ
img = Image.open(file_path).convert('RGB')
# ๋ฆฌ์คํธ์ ์ถ๊ฐ
img_group.append(img)
return img_group
def _get_indices(self, dir_path):
"""
๋์์ ์ ์ฒด๋ฅผ self.num_segment๋ก ๋ถํ ํ์ ๋์ ๋์์ idx์ ๋ฆฌ์คํธ๋ฅผ ์ทจ๋
"""
# ๋์์ ํ๋ ์ ์ ๊ตฌํ๊ธฐ
file_list = os.listdir(path=dir_path)
num_frames = len(file_list)
# ๋์์์ ๊ฐ๊ฒฉ์ ๊ตฌํ๊ธฐ
tick = (num_frames) / float(self.num_segments)
# 250 / 16 = 15.625
# ๋์์ ๊ฐ๊ฒฉ์ผ๋ก ๊บผ๋ผ ๋ idx๋ฅผ ๋ฆฌ์คํธ๋ก ๊ตฌํ๊ธฐ
indices = np.array([int(tick / 2.0 + tick * x)
for x in range(self.num_segments)])+1
# 250frame์์ 16frame ์ถ์ถ์ ๊ฒฝ์ฐ
# indices = [ 8 24 40 55 71 86 102 118 133 149 165 180 196 211 227 243]
return indices
# ๋์ ํ์ธ
# vieo_list ์์ฑ
root_path = './data/kinetics_videos/'
video_list = make_datapath_list(root_path)
# ์ ์ฒ๋ฆฌ ์ค์
resize, crop_size = 224, 224
mean, std = [104, 117, 123], [1, 1, 1]
video_transform = VideoTransform(resize, crop_size, mean, std)
# Dataset ์์ฑ
# num_segments๋ ๋์์์ ์ด๋ป๊ฒ ๋ถํ ํด ์ฌ์ฉํ ์ง ์ ํ๋ค
val_dataset = VideoDataset(video_list, label_id_dict, num_segments=16,
phase="val", transform=video_transform, img_tmpl='image_{:05d}.jpg')
# ๋ฐ์ดํฐ๋ฅผ ๊บผ๋ด๋ ์
# ์ถ๋ ฅ์ imgs_transformed, label, label_id, dir_path
index = 0
print(val_dataset.__getitem__(index)[0].shape) # ๋์์์ ํ
์
print(val_dataset.__getitem__(index)[1]) # ๋ผ๋ฒจ
print(val_dataset.__getitem__(index)[2]) # ๋ผ๋ฒจID
print(val_dataset.__getitem__(index)[3]) # ๋์์ ๊ฒฝ๋ก
# DataLoader๋ก ํฉ๋๋ค
batch_size = 8
val_dataloader = torch.utils.data.DataLoader(
val_dataset, batch_size=batch_size, shuffle=False)
# ๋์ ํ์ธ
batch_iterator = iter(val_dataloader) # ๋ฐ๋ณต์๋ก ๋ณํ
imgs_transformeds, labels, label_ids, dir_path = next(
batch_iterator) # 1๋ฒ์งธ ์์๋ฅผ ๊บผ๋ธ๋ค
print(imgs_transformeds.shape)
| 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 matematiฤke operacije nad kompleksnim brojevima: zbrajanje, oduzimanje, mnoลพenje i dijeljenje. Svi se rezultati prikazuju na odgovarajuฤem grafu, kao i u matematiฤkoj notaciji zasnovanoj na polarnom obliku kompleksnog broja.Kompleksnim brojevima moลพete manipulirati izravno na grafu (jednostavnim klikom) i / ili istovremeno koristiti odgovarajuฤa polja za unos modula i argumenta. Kako bi se osigurala bolja vidljivost vektora na grafu, modul kompleksnog broja je ograniฤen na $\pm10$. | %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', label='z2')
green_patch = mpatches.Patch(color='green', label='z1 + z2')
yellow_patch = mpatches.Patch(color='yellow', label='z1 - z2')
black_patch = mpatches.Patch(color='black', label='z1 * z2')
magenta_patch = mpatches.Patch(color='magenta', label='z1 / z2')
# Init values
XLIM = 5
YLIM = 5
vectors_index_first = False;
V = [None, None]
V_complex = [None, None]
# Complex plane
fig = plt.figure(num='Kompleksni brojevi u polarnom obliku')
ax = fig.add_subplot(1, 1, 1)
def get_interval(lim):
if lim <= 10:
return 1
if lim < 75:
return 5
if lim > 100:
return 25
return 10
def set_ticks():
XLIMc = int((XLIM / 10) + 1) * 10
YLIMc = int((YLIM / 10) + 1) * 10
if XLIMc > 150:
XLIMc += 10
if YLIMc > 150:
YLIMc += 10
xstep = get_interval(XLIMc)
ystep = get_interval(YLIMc)
#print(stepx, stepy)
major_ticks = np.arange(-XLIMc, XLIMc, xstep)
major_ticks_y = np.arange(-YLIMc, YLIMc, ystep)
ax.set_xticks(major_ticks)
ax.set_yticks(major_ticks_y)
ax.grid(which='both')
def clear_plot():
plt.cla()
set_ticks()
ax.set_xlabel('Re')
ax.set_ylabel('Im')
plt.ylim([-YLIM, YLIM])
plt.xlim([-XLIM, XLIM])
plt.legend(handles=[red_patch, blue_patch, green_patch, yellow_patch, black_patch, magenta_patch])
clear_plot()
set_ticks()
plt.show()
set_ticks()
# Conversion functions
def com_to_trig(real, im):
r = math.sqrt(real**2 + im**2)
if abs(real) <= 1e-6 and im > 0:
arg = 90
return r, arg
if abs(real) < 1e-6 and im < 0:
arg = 270
return r, arg
if abs(im) < 1e-6 and real > 0:
arg = 0
return r, arg
if abs(im) < 1e-6 and real < 0:
arg = 180
return r, arg
if im != 0 and real !=0:
arg = np.arctan(im / real) * 180 / np.pi
if im > 0 and real < 0:
arg += 180
if im < 0 and real > 0:
arg +=360
if im < 0 and real < 0:
arg += 180
return r, arg
if abs(im) < 1e-6 and abs(real) < 1e-6:
arg = 0
return r, arg
def trig_to_com(r, arg):
re = r * np.cos(arg * np.pi / 180.)
im = r * np.sin(arg * np.pi / 180.)
return (re, im)
# Set a complex number using direct manipulation on the plot
def set_vector(i, data_x, data_y):
clear_plot()
V.pop(i)
V.insert(i, (0, 0, round(data_x, 2), round(data_y, 2)))
V_complex.pop(i)
V_complex.insert(i, complex(round(data_x, 2), round(data_y, 2)))
if i == 0:
ax.arrow(*V[0], head_width=0.25, head_length=0.5, color="r", length_includes_head=True)
z, arg = com_to_trig(data_x, data_y)
a1.value = round(z, 2)
b1.value = round(arg, 2)
if V[1] != None:
ax.arrow(*V[1], head_width=0.25, head_length=0.5, color="b", length_includes_head=True)
elif i == 1:
ax.arrow(*V[1], head_width=0.25, head_length=0.5, color="b", length_includes_head=True)
z, arg = com_to_trig(data_x, data_y)
a2.value = round(z, 2)
b2.value = round(arg, 2)
if V[0] != None:
ax.arrow(*V[0], head_width=0.25, head_length=0.5, color="r", length_includes_head=True)
max_bound()
def onclick(event):
global vectors_index_first
vectors_index_first = not vectors_index_first
x = event.xdata
y = event.ydata
if (x > 10):
x = 10.0
if (x < - 10):
x = -10.0
if (y > 10):
y = 10.0
if (y < - 10):
y = -10.0
if vectors_index_first:
set_vector(0, x, y)
else:
set_vector(1, x, y)
fig.canvas.mpl_connect('button_press_event', onclick)
# Widgets
a1 = widgets.BoundedFloatText(layout=widgets.Layout(width='10%'), min = 0, max = 10, step = 0.5)
b1 = widgets.BoundedFloatText(layout=widgets.Layout(width='10%'), min = 0, max = 360, step = 10)
button_set_z1 = widgets.Button(description="Prikaลพi z1")
a2 = widgets.BoundedFloatText(layout=widgets.Layout(width='10%'), min = 0, max = 10, step = 0.5)
b2 = widgets.BoundedFloatText(layout=widgets.Layout(width='10%'), min = 0, max = 360, step = 10)
button_set_z2 = widgets.Button(description="Prikaลพi z2")
box_layout_z1 = widgets.Layout(border='solid red', padding='10px')
box_layout_z2 = widgets.Layout(border='solid blue', padding='10px')
box_layout_opers = widgets.Layout(border='solid black', padding='10px')
items_z1 = [widgets.Label("z1: Duljina (|z1|) = "), a1, widgets.Label("Kut (\u2221)= "), b1, button_set_z1]
items_z2 = [widgets.Label("z2: Duljina (|z2|) = "), a2, widgets.Label("Kut (\u2221)= "), b2, button_set_z2]
display(widgets.Box(children=items_z1, layout=box_layout_z1))
display(widgets.Box(children=items_z2, layout=box_layout_z2))
button_add = widgets.Button(description="Zbroji")
button_substract = widgets.Button(description="Oduzmi")
button_multiply = widgets.Button(description="Pomnoลพi")
button_divide = widgets.Button(description="Podijeli")
button_reset = widgets.Button(description="Resetiraj")
output = widgets.Output()
print('Operacije nad kompleksnim brojevima:')
items_operations = [button_add, button_substract, button_multiply, button_divide, button_reset]
display(widgets.Box(children=items_operations))
display(output)
# Set complex number using input widgets (Text and Button)
def on_button_set_z1_clicked(b):
z1_old = V[0];
re, im = trig_to_com(a1.value, b1.value)
z1_new = (0, 0, re, im)
if z1_old != z1_new:
set_vector(0, re, im)
change_lims()
def on_button_set_z2_clicked(b):
z2_old = V[1];
re, im = trig_to_com(a2.value, b2.value)
z2_new = (0, 0, re, im)
if z2_old != z2_new:
set_vector(1, re, im)
change_lims()
# Complex number operations:
def perform_operation(oper):
global XLIM, YLIM
if (V_complex[0] != None) and (V_complex[1] != None):
if (oper == '+'):
result = V_complex[0] + V_complex[1]
v_color = "g"
elif (oper == '-'):
result = V_complex[0] - V_complex[1]
v_color = "y"
elif (oper == '*'):
result = V_complex[0] * V_complex[1]
v_color = "black"
elif (oper == '/'):
result = V_complex[0] / V_complex[1]
v_color = "magenta"
result = complex(round(result.real, 2), round(result.imag, 2))
ax.arrow(0, 0, result.real, result.imag, head_width=0.25, head_length=0.15, color=v_color, length_includes_head=True)
if abs(result.real) > XLIM:
XLIM = round(abs(result.real) + 1)
if abs(result.imag) > YLIM:
YLIM = round(abs(result.imag) + 1)
change_lims()
with output:
z1, ang1 = com_to_trig(V_complex[0].real, V_complex[0].imag )
z2, ang2 = com_to_trig(V_complex[1].real, V_complex[1].imag)
z3, ang3 = com_to_trig(result.real, result.imag)
z1 = round(z1, 2)
ang1 = round(ang1, 2)
z2 = round(z2, 2)
ang2 = round(ang2, 2)
z3 = round(z3, 2)
ang3 = round(ang3, 2)
print("{}*(cos({}) + i*sin({}))".format(z1,ang1,ang1), oper,
"{}*(cos({}) + i*sin({}))".format(z2,ang2,ang2), "=",
"{}*(cos({}) + i*sin({}))".format(z3,ang3,ang3))
print('{} \u2221{}'.format(z1, ang1), oper,
'{} \u2221{}'.format(z2, ang2), "=",
'{} \u2221{}'.format(z3, ang3))
def on_button_add_clicked(b):
perform_operation("+")
def on_button_substract_clicked(b):
perform_operation("-")
def on_button_multiply_clicked(b):
perform_operation("*")
def on_button_divide_clicked(b):
perform_operation("/")
# Plot init methods
def on_button_reset_clicked(b):
global V, V_complex, XLIM, YLIM
with output:
output.clear_output()
clear_plot()
vectors_index_first = False;
V = [None, None]
V_complex = [None, None]
a1.value = 0
b1.value = 0
a2.value = 0
b2.value = 0
XLIM = 5
YLIM = 5
change_lims()
def clear_plot():
plt.cla()
set_ticks()
ax.set_xlabel('Re')
ax.set_ylabel('Im')
plt.ylim([-YLIM, YLIM])
plt.xlim([-XLIM, XLIM])
plt.legend(handles=[red_patch, blue_patch, green_patch, yellow_patch, black_patch, magenta_patch])
def change_lims():
set_ticks()
plt.ylim([-YLIM, YLIM])
plt.xlim([-XLIM, XLIM])
set_ticks()
def max_bound():
global XLIM, YLIM
mx = 0
my = 0
if V_complex[0] != None:
z = V_complex[0]
if abs(z.real) > mx:
mx = abs(z.real)
if abs(z.imag) > my:
my = abs(z.imag)
if V_complex[1] != None:
z = V_complex[1]
if abs(z.real) > mx:
mx = abs(z.real)
if abs(z.imag) > my:
my = abs(z.imag)
if mx > XLIM:
XLIM = round(mx + 1)
elif mx <=5:
XLIM = 5
if my > YLIM:
YLIM = round(my + 1)
elif my <=5:
YLIM = 5
change_lims()
# Button events
button_set_z1.on_click(on_button_set_z1_clicked)
button_set_z2.on_click(on_button_set_z2_clicked)
button_add.on_click(on_button_add_clicked)
button_substract.on_click(on_button_substract_clicked)
button_multiply.on_click(on_button_multiply_clicked)
button_divide.on_click(on_button_divide_clicked)
button_reset.on_click(on_button_reset_clicked)
| _____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:> [](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} = 100 \,\text{nm}$, and- thickness $l_{z} = 10 \,\text{nm}$.The material parameters (similar to permalloy) are:- exchange energy constant $A = 1.3 \times 10^{-11} \,\text{J/m}$,- magnetisation saturation $M_\text{s} = 8 \times 10^{5} \,\text{A/m}$.Dynamics parameters are: $\gamma_{0} = 2.211 \times 10^{5} \,\text{m}\,\text{A}^{-1}\,\text{s}^{-1}$ and Gilbert damping $\alpha=0.02$.In the standard problem 5, the system is firstly relaxed at zero external magnetic field, starting from the vortex state. Secondly spin-polarised current is applied in the $x$ direction with $u_{x} = -72.35$ and $\beta=0.05$.More detailed specification of Standard problem 5 can be found in Ref. 1. SimulationIn the first step, we import the required `discretisedfield` and `oommfc` modules. | 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 (LLG equation) parameters
gamma0 = 2.211e5 # gyromagnetic ratio (m/As)
alpha = 0.1 # Gilbert damping
ux = -72.35 # velocity in x direction
beta = 0.05 # non-adiabatic STT parameter | _____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 Hamiltonian. | 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_path = input('Please enter path to SentimentNewton_Log')
clf_log = joblib.load(clf_path)
vect_path = input('Please enter path to Vectorizer')
vectorizer = joblib.load(vect_path)
judge_data_path = input("Please enter the path to your judgement_data.csv file in your Google Drive.")
""" | _____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_cluster = []
for num in indx:
for i,ndx in enumerate(ndf.index):
if num == i:
protein_cluster.append({'id':i,"protein": ndx,\
'CM' : list(ndf.loc[ndx,:])[0],\
'ARR': list(ndf.loc[ndx,:])[1],\
'CHD' : list(ndf.loc[ndx,:])[2],\
'VD' : list(ndf.loc[ndx,:])[3],\
'IHD' : list(ndf.loc[ndx,:])[4],\
'CCS' : list(ndf.loc[ndx,:])[5],\
'VOO' : list(ndf.loc[ndx,:])[6],\
'OHD' : list(ndf.loc[ndx,:])[7]})
protein_cluster_df = pd.DataFrame(protein_cluster)
protein_cluster_df = protein_cluster_df.set_index("protein")
protein_cluster_df = protein_cluster_df.drop(["id"], axis = 1)
protein_cluster_df.head() | _____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(id2name[item])
protein_cluster_df['names'] =names
protein_cluster_df.head(1)
protein_cluster_df.to_csv("data/protein-cluster-bar-data.csv") | _____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)
[K |โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ| 734.6MB 56kB/s s eta 0:00:01 |โ | 18.6MB 3.0MB/s eta 0:03:57 |โ | 19.9MB 3.0MB/s eta 0:03:56 |โโโโโโโโ | 178.8MB 21.2MB/s eta 0:00:27 |โโโโโโโโโ | 190.0MB 21.2MB/s eta 0:00:26 |โโโโโโโโโ | 193.0MB 4.0MB/s eta 0:02:14 |โโโโโโโโโโโ | 237.8MB 16.2MB/s eta 0:00:31 |โโโโโโโโโโโ | 240.1MB 16.2MB/s eta 0:00:31 |โโโโโโโโโโโ | 244.9MB 16.2MB/s eta 0:00:31 |โโโโโโโโโโโ | 246.1MB 16.2MB/s eta 0:00:31 |โโโโโโโโโโโ | 254.7MB 26.0MB/s eta 0:00:19 |โโโโโโโโโโโโโโโ | 333.4MB 26.9MB/s eta 0:00:15 |โโโโโโโโโโโโโโโโโโโ | 429.2MB 12.5MB/s eta 0:00:25 |โโโโโโโโโโโโโโโโโโโโโโโ | 521.4MB 22.4MB/s eta 0:00:10 |โโโโโโโโโโโโโโโโโโโโโโโโโ | 563.3MB 18.3MB/s eta 0:00:10 |โโโโโโโโโโโโโโโโโโโโโโโโโโโ | 615.9MB 23.2MB/s eta 0:00:06 |โโโโโโโโโโโโโโโโโโโโโโโโโโโโ | 635.2MB 23.2MB/s eta 0:00:05 |โโโโโโโโโโโโโโโโโโโโโโโโโโโโ | 642.2MB 23.2MB/s eta 0:00:04 |โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ | 672.9MB 14.3MB/s eta 0:00:05 |โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ | 713.0MB 18.8MB/s eta 0:00:02
[?25hCollecting torchvision
[?25l Downloading https://files.pythonhosted.org/packages/9b/e2/2b1f88a363ae37b2ba52cfb785ddfb3dd5f7e7ec9459e96fd8299b84ae39/torchvision-0.4.2-cp36-cp36m-manylinux1_x86_64.whl (10.2MB)
[K |โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ| 10.2MB 15.3MB/s eta 0:00:01
[?25hRequirement already satisfied: numpy in /usr/local/lib/python3.6/dist-packages (from torch) (1.18.0)
Requirement already satisfied: six in /usr/local/lib/python3.6/dist-packages (from torchvision) (1.13.0)
Collecting pillow>=4.1.1
[?25l Downloading https://files.pythonhosted.org/packages/10/5c/0e94e689de2476c4c5e644a3bd223a1c1b9e2bdb7c510191750be74fa786/Pillow-6.2.1-cp36-cp36m-manylinux1_x86_64.whl (2.1MB)
[K |โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ| 2.1MB 21.9MB/s eta 0:00:01 |โโโ | 174kB 21.9MB/s eta 0:00:01
[?25hInstalling collected packages: torch, pillow, torchvision
Successfully installed pillow-6.2.1 torch-1.3.1 torchvision-0.4.2
| 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/20151103002/20151103113637.jpg
inflating: dataset/data/test/0/20151103002/20151103113659.jpg
inflating: dataset/data/test/0/20151103002/20151103113722.jpg
inflating: dataset/data/test/0/20151103002/20151103113752.jpg
inflating: dataset/data/test/0/20151103002/20151103113755.jpg
inflating: dataset/data/test/0/20151103002/20151103113833.jpg
creating: dataset/data/test/0/20151103005/
inflating: dataset/data/test/0/20151103005/20151103161719.jpg
inflating: dataset/data/test/0/20151103005/20151103161836.jpg
inflating: dataset/data/test/0/20151103005/20151103161908.jpg
inflating: dataset/data/test/0/20151103005/20151103161938.jpg
inflating: dataset/data/test/0/20151103005/20151103162027.jpg
inflating: dataset/data/test/0/20151103005/20151103162122.jpg
inflating: dataset/data/test/0/20151103005/20151103162254.jpg
creating: dataset/data/test/0/20151106002/
inflating: dataset/data/test/0/20151106002/20151106101644.jpg
inflating: dataset/data/test/0/20151106002/20151106101845.jpg
inflating: dataset/data/test/0/20151106002/20151106101905.jpg
inflating: dataset/data/test/0/20151106002/20151106101935.jpg
inflating: dataset/data/test/0/20151106002/20151106101957.jpg
inflating: dataset/data/test/0/20151106002/20151106102000.jpg
inflating: dataset/data/test/0/20151106002/20151106102110.jpg
creating: dataset/data/test/0/20151111002/
inflating: dataset/data/test/0/20151111002/20151111144157.jpg
inflating: dataset/data/test/0/20151111002/20151111144348.jpg
inflating: dataset/data/test/0/20151111002/20151111144420.jpg
inflating: dataset/data/test/0/20151111002/20151111144506.jpg
inflating: dataset/data/test/0/20151111002/20151111144511.jpg
inflating: dataset/data/test/0/20151111002/20151111144515.jpg
inflating: dataset/data/test/0/20151111002/20151111144654.jpg
creating: dataset/data/test/0/20151111004/
inflating: dataset/data/test/0/20151111004/20151111150820.jpg
inflating: dataset/data/test/0/20151111004/20151111151033.jpg
inflating: dataset/data/test/0/20151111004/20151111151104.jpg
inflating: dataset/data/test/0/20151111004/20151111151127.jpg
inflating: dataset/data/test/0/20151111004/20151111151152.jpg
inflating: dataset/data/test/0/20151111004/20151111151160.jpg
inflating: dataset/data/test/0/20151111004/20151111151245.jpg
creating: dataset/data/test/0/20151111007/
inflating: dataset/data/test/0/20151111007/20151111154450.jpg
inflating: dataset/data/test/0/20151111007/20151111154626.jpg
inflating: dataset/data/test/0/20151111007/20151111154652.jpg
inflating: dataset/data/test/0/20151111007/20151111154725.jpg
inflating: dataset/data/test/0/20151111007/20151111154740.jpg
inflating: dataset/data/test/0/20151111007/20151111154800.jpg
inflating: dataset/data/test/0/20151111007/20151111154900.jpg
creating: dataset/data/test/0/20151111010/
inflating: dataset/data/test/0/20151111010/20151111162830.jpg
inflating: dataset/data/test/0/20151111010/20151111162959.jpg
inflating: dataset/data/test/0/20151111010/20151111163012.jpg
inflating: dataset/data/test/0/20151111010/20151111163041.jpg
inflating: dataset/data/test/0/20151111010/20151111163105.jpg
inflating: dataset/data/test/0/20151111010/20151111163115.jpg
inflating: dataset/data/test/0/20151111010/20151111163257.jpg
creating: dataset/data/test/0/20151113012/
inflating: dataset/data/test/0/20151113012/20151113163733.jpg
inflating: dataset/data/test/0/20151113012/20151113163859.jpg
inflating: dataset/data/test/0/20151113012/20151113163928.jpg
inflating: dataset/data/test/0/20151113012/20151113164000.jpg
inflating: dataset/data/test/0/20151113012/20151113164028.jpg
inflating: dataset/data/test/0/20151113012/20151113164100.jpg
inflating: dataset/data/test/0/20151113012/20151113164201.jpg
creating: dataset/data/test/0/20151117005/
inflating: dataset/data/test/0/20151117005/20151117111950.jpg
inflating: dataset/data/test/0/20151117005/20151117112126.jpg
inflating: dataset/data/test/0/20151117005/20151117112146.jpg
inflating: dataset/data/test/0/20151117005/20151117112246.jpg
inflating: dataset/data/test/0/20151117005/20151117112314.jpg
inflating: dataset/data/test/0/20151117005/20151117112400.jpg
inflating: dataset/data/test/0/20151117005/20151117112508.jpg
creating: dataset/data/test/0/20151118006/
inflating: dataset/data/test/0/20151118006/20151118144223.jpg
inflating: dataset/data/test/0/20151118006/20151118144344.jpg
inflating: dataset/data/test/0/20151118006/20151118144414.jpg
inflating: dataset/data/test/0/20151118006/20151118144448.jpg
inflating: dataset/data/test/0/20151118006/20151118144519.jpg
inflating: dataset/data/test/0/20151118006/20151118144600.jpg
inflating: dataset/data/test/0/20151118006/20151118144610.jpg
creating: dataset/data/test/0/20151118009/
inflating: dataset/data/test/0/20151118009/20151118160649.jpg
inflating: dataset/data/test/0/20151118009/20151118160839.jpg
inflating: dataset/data/test/0/20151118009/20151118160853.jpg
inflating: dataset/data/test/0/20151118009/20151118160924.jpg
inflating: dataset/data/test/0/20151118009/20151118160952.jpg
inflating: dataset/data/test/0/20151118009/20151118160970.jpg
inflating: dataset/data/test/0/20151118009/20151118161030.jpg
creating: dataset/data/test/0/20151118011/
inflating: dataset/data/test/0/20151118011/20151118162920.jpg
inflating: dataset/data/test/0/20151118011/20151118163100.jpg
inflating: dataset/data/test/0/20151118011/20151118163137.jpg
inflating: dataset/data/test/0/20151118011/20151118163150.jpg
inflating: dataset/data/test/0/20151118011/20151118163215.jpg
inflating: dataset/data/test/0/20151118011/20151118163218.jpg
inflating: dataset/data/test/0/20151118011/20151118163318.jpg
creating: dataset/data/test/1/
creating: dataset/data/test/1/162231763/
inflating: dataset/data/test/1/162231763/162231763Image0.jpg
inflating: dataset/data/test/1/162231763/162231763Image2.jpg
inflating: dataset/data/test/1/162231763/162231763Image3.jpg
inflating: dataset/data/test/1/162231763/162231763Image5.jpg
inflating: dataset/data/test/1/162231763/162231763Image6.jpg
inflating: dataset/data/test/1/162231763/162231763Image7.jpg
inflating: dataset/data/test/1/162231763/162231763Image8.jpg
creating: dataset/data/test/1/163856190/
inflating: dataset/data/test/1/163856190/163856190Image0.jpg
inflating: dataset/data/test/1/163856190/163856190Image2.jpg
inflating: dataset/data/test/1/163856190/163856190Image3.jpg
inflating: dataset/data/test/1/163856190/163856190Image5.jpg
inflating: dataset/data/test/1/163856190/163856190Image6.jpg
inflating: dataset/data/test/1/163856190/163856190Image7.jpg
inflating: dataset/data/test/1/163856190/163856190Image9.jpg
creating: dataset/data/test/1/164145173/
inflating: dataset/data/test/1/164145173/164145173Image0.jpg
inflating: dataset/data/test/1/164145173/164145173Image2.jpg
inflating: dataset/data/test/1/164145173/164145173Image3.jpg
inflating: dataset/data/test/1/164145173/164145173Image4.jpg
inflating: dataset/data/test/1/164145173/164145173Image6.jpg
inflating: dataset/data/test/1/164145173/164145173Image7.jpg
inflating: dataset/data/test/1/164145173/164145173Image8.jpg
creating: dataset/data/test/1/165554510/
inflating: dataset/data/test/1/165554510/165554510Image0.jpg
inflating: dataset/data/test/1/165554510/165554510Image3.jpg
inflating: dataset/data/test/1/165554510/165554510Image4.jpg
inflating: dataset/data/test/1/165554510/165554510Image5.jpg
inflating: dataset/data/test/1/165554510/165554510Image6.jpg
inflating: dataset/data/test/1/165554510/165554510Image7.jpg
inflating: dataset/data/test/1/165554510/165554510Image8.jpg
creating: dataset/data/test/1/171212253/
inflating: dataset/data/test/1/171212253/171212253Image0.jpg
inflating: dataset/data/test/1/171212253/171212253Image3.jpg
inflating: dataset/data/test/1/171212253/171212253Image4.jpg
inflating: dataset/data/test/1/171212253/171212253Image5.jpg
inflating: dataset/data/test/1/171212253/171212253Image6.jpg
inflating: dataset/data/test/1/171212253/171212253Image8.jpg
inflating: dataset/data/test/1/171212253/171212253Image9.jpg
creating: dataset/data/test/1/20150729004/
inflating: dataset/data/test/1/20150729004/20150729142418.jpg
inflating: dataset/data/test/1/20150729004/20150729142536.jpg
inflating: dataset/data/test/1/20150729004/20150729142617.jpg
inflating: dataset/data/test/1/20150729004/20150729142638.jpg
inflating: dataset/data/test/1/20150729004/20150729142712.jpg
inflating: dataset/data/test/1/20150729004/20150729142728.jpg
inflating: dataset/data/test/1/20150729004/20150729143009.jpg
creating: dataset/data/test/1/20150731002/
inflating: dataset/data/test/1/20150731002/20150731164116.jpg
inflating: dataset/data/test/1/20150731002/20150731164301.jpg
inflating: dataset/data/test/1/20150731002/20150731164316.jpg
inflating: dataset/data/test/1/20150731002/20150731164344.jpg
inflating: dataset/data/test/1/20150731002/20150731164411.jpg
inflating: dataset/data/test/1/20150731002/20150731164418.jpg
inflating: dataset/data/test/1/20150731002/20150731164556.jpg
creating: dataset/data/test/1/20150812006/
inflating: dataset/data/test/1/20150812006/20150812143825.jpg
inflating: dataset/data/test/1/20150812006/20150812143943.jpg
inflating: dataset/data/test/1/20150812006/20150812144013.jpg
inflating: dataset/data/test/1/20150812006/20150812144047.jpg
inflating: dataset/data/test/1/20150812006/20150812144114.jpg
inflating: dataset/data/test/1/20150812006/20150812144206.jpg
inflating: dataset/data/test/1/20150812006/20150812144318.jpg
creating: dataset/data/test/1/20150818001/
inflating: dataset/data/test/1/20150818001/20150818113423.jpg
inflating: dataset/data/test/1/20150818001/20150818113549.jpg
inflating: dataset/data/test/1/20150818001/20150818113620.jpg
inflating: dataset/data/test/1/20150818001/20150818113649.jpg
inflating: dataset/data/test/1/20150818001/20150818113719.jpg
inflating: dataset/data/test/1/20150818001/20150818113721.jpg
inflating: dataset/data/test/1/20150818001/20150818113827.jpg
creating: dataset/data/test/1/20150819006/
inflating: dataset/data/test/1/20150819006/20150819152524.jpg
inflating: dataset/data/test/1/20150819006/20150819152652.jpg
inflating: dataset/data/test/1/20150819006/20150819152726.jpg
inflating: dataset/data/test/1/20150819006/20150819152755.jpg
inflating: dataset/data/test/1/20150819006/20150819152825.jpg
inflating: dataset/data/test/1/20150819006/20150819152827.jpg
inflating: dataset/data/test/1/20150819006/20150819152905.jpg
creating: dataset/data/test/1/20150819011/
inflating: dataset/data/test/1/20150819011/20150819163415.jpg
inflating: dataset/data/test/1/20150819011/20150819163538.jpg
inflating: dataset/data/test/1/20150819011/20150819163608.jpg
inflating: dataset/data/test/1/20150819011/20150819163638.jpg
inflating: dataset/data/test/1/20150819011/20150819163708.jpg
inflating: dataset/data/test/1/20150819011/20150819163778.jpg
inflating: dataset/data/test/1/20150819011/20150819163805.jpg
creating: dataset/data/test/1/20150826008/
inflating: dataset/data/test/1/20150826008/20150826153113.jpg
inflating: dataset/data/test/1/20150826008/20150826153241.jpg
inflating: dataset/data/test/1/20150826008/20150826153310.jpg
inflating: dataset/data/test/1/20150826008/20150826153340.jpg
inflating: dataset/data/test/1/20150826008/20150826153410.jpg
inflating: dataset/data/test/1/20150826008/20150826153425.jpg
inflating: dataset/data/test/1/20150826008/20150826153539.jpg
creating: dataset/data/test/2/
creating: dataset/data/test/2/162021000/
inflating: dataset/data/test/2/162021000/162021000Image0.jpg
inflating: dataset/data/test/2/162021000/162021000Image100.jpg
inflating: dataset/data/test/2/162021000/162021000Image3.jpg
inflating: dataset/data/test/2/162021000/162021000Image6.jpg
inflating: dataset/data/test/2/162021000/162021000Image70.jpg
inflating: dataset/data/test/2/162021000/162021000Image8.jpg
inflating: dataset/data/test/2/162021000/162021000Image9.jpg
creating: dataset/data/test/2/162334723/
inflating: dataset/data/test/2/162334723/162334723Image0.jpg
inflating: dataset/data/test/2/162334723/162334723Image10.jpg
inflating: dataset/data/test/2/162334723/162334723Image12.jpg
inflating: dataset/data/test/2/162334723/162334723Image2.jpg
inflating: dataset/data/test/2/162334723/162334723Image4.jpg
inflating: dataset/data/test/2/162334723/162334723Image8.jpg
inflating: dataset/data/test/2/162334723/162334723Image9.jpg
creating: dataset/data/test/2/162403397/
inflating: dataset/data/test/2/162403397/162403397Image0.jpg
inflating: dataset/data/test/2/162403397/162403397Image1.jpg
inflating: dataset/data/test/2/162403397/162403397Image100.jpg
inflating: dataset/data/test/2/162403397/162403397Image3.jpg
inflating: dataset/data/test/2/162403397/162403397Image4.jpg
inflating: dataset/data/test/2/162403397/162403397Image80.jpg
inflating: dataset/data/test/2/162403397/162403397Image9.jpg
creating: dataset/data/test/2/163138313/
inflating: dataset/data/test/2/163138313/163138313Image0.jpg
inflating: dataset/data/test/2/163138313/163138313Image2.jpg
inflating: dataset/data/test/2/163138313/163138313Image3.jpg
inflating: dataset/data/test/2/163138313/163138313Image4.jpg
inflating: dataset/data/test/2/163138313/163138313Image5.jpg
| 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 time
import random
import GPUtil | _____no_output_____ | MIT | Mobilenetv2 Tuning/MobileNetV2 Baseline.ipynb | vlad-danaila/Mobilenetv2_Ensemble_for_Cervical_Precancerous_Lesions_Classification |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.