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 |
|---|---|---|---|---|---|
**Expected Output**: **v["dW1"]** [[ 0. 0. 0.] [ 0. 0. 0.]] **v["db1"]** [[ 0.] [ 0.]] **v["dW2"]** [[ 0. 0. 0.] [ 0. 0. 0.] [ 0. 0. 0.]] **v["db2"]** [[ 0.] [ 0.] [ 0.]] **s["d... | # GRADED FUNCTION: update_parameters_with_adam
def update_parameters_with_adam(parameters, grads, v, s, t, learning_rate = 0.01,
beta1 = 0.9, beta2 = 0.999, epsilon = 1e-8):
"""
Update parameters using Adam
Arguments:
parameters -- python dictionary containing your... | W1 = [[ 1.63178673 -0.61919778 -0.53561312]
[-1.08040999 0.85796626 -2.29409733]]
b1 = [[ 1.75225313]
[-0.75376553]]
W2 = [[ 0.32648046 -0.25681174 1.46954931]
[-2.05269934 -0.31497584 -0.37661299]
[ 1.14121081 -1.09244991 -0.16498684]]
b2 = [[-0.88529979]
[ 0.03477238]
[ 0.57537385]]
v["dW1"] = [[-0.11006192 ... | Apache-2.0 | Week2/Optimization+methods.ipynb | softwarebrahma/Deep-Learning-Specialization-Improving-Deep-Neural-Network-Hyperparam-TuneRegularizationOptimization |
**Expected Output**: **W1** [[ 1.63178673 -0.61919778 -0.53561312] [-1.08040999 0.85796626 -2.29409733]] **b1** [[ 1.75225313] [-0.75376553]] **W2** [[ 0.32648046 -0.25681174 1.46954931] [-2.05269934 -0.31497584 -0.37661299] [ 1.141... | train_X, train_Y = load_dataset() | _____no_output_____ | Apache-2.0 | Week2/Optimization+methods.ipynb | softwarebrahma/Deep-Learning-Specialization-Improving-Deep-Neural-Network-Hyperparam-TuneRegularizationOptimization |
We have already implemented a 3-layer neural network. You will train it with: - Mini-batch **Gradient Descent**: it will call your function: - `update_parameters_with_gd()`- Mini-batch **Momentum**: it will call your functions: - `initialize_velocity()` and `update_parameters_with_momentum()`- Mini-batch **Adam**... | def model(X, Y, layers_dims, optimizer, learning_rate = 0.0007, mini_batch_size = 64, beta = 0.9,
beta1 = 0.9, beta2 = 0.999, epsilon = 1e-8, num_epochs = 10000, print_cost = True):
"""
3-layer neural network model which can be run in different optimizer modes.
Arguments:
X -- input data... | _____no_output_____ | Apache-2.0 | Week2/Optimization+methods.ipynb | softwarebrahma/Deep-Learning-Specialization-Improving-Deep-Neural-Network-Hyperparam-TuneRegularizationOptimization |
You will now run this 3 layer neural network with each of the 3 optimization methods. 5.1 - Mini-batch Gradient descentRun the following code to see how the model does with mini-batch gradient descent. | # train 3-layer model
layers_dims = [train_X.shape[0], 5, 2, 1]
parameters = model(train_X, train_Y, layers_dims, optimizer = "gd")
# Predict
predictions = predict(train_X, train_Y, parameters)
# Plot decision boundary
plt.title("Model with Gradient Descent optimization")
axes = plt.gca()
axes.set_xlim([-1.5,2.5])
ax... | Cost after epoch 0: 0.690736
Cost after epoch 1000: 0.685273
Cost after epoch 2000: 0.647072
Cost after epoch 3000: 0.619525
Cost after epoch 4000: 0.576584
Cost after epoch 5000: 0.607243
Cost after epoch 6000: 0.529403
Cost after epoch 7000: 0.460768
Cost after epoch 8000: 0.465586
Cost after epoch 9000: 0.464518
| Apache-2.0 | Week2/Optimization+methods.ipynb | softwarebrahma/Deep-Learning-Specialization-Improving-Deep-Neural-Network-Hyperparam-TuneRegularizationOptimization |
5.2 - Mini-batch gradient descent with momentumRun the following code to see how the model does with momentum. Because this example is relatively simple, the gains from using momemtum are small; but for more complex problems you might see bigger gains. | # train 3-layer model
layers_dims = [train_X.shape[0], 5, 2, 1]
parameters = model(train_X, train_Y, layers_dims, beta = 0.9, optimizer = "momentum")
# Predict
predictions = predict(train_X, train_Y, parameters)
# Plot decision boundary
plt.title("Model with Momentum optimization")
axes = plt.gca()
axes.set_xlim([-1.... | Cost after epoch 0: 0.690741
Cost after epoch 1000: 0.685341
Cost after epoch 2000: 0.647145
Cost after epoch 3000: 0.619594
Cost after epoch 4000: 0.576665
Cost after epoch 5000: 0.607324
Cost after epoch 6000: 0.529476
Cost after epoch 7000: 0.460936
Cost after epoch 8000: 0.465780
Cost after epoch 9000: 0.464740
| Apache-2.0 | Week2/Optimization+methods.ipynb | softwarebrahma/Deep-Learning-Specialization-Improving-Deep-Neural-Network-Hyperparam-TuneRegularizationOptimization |
5.3 - Mini-batch with Adam modeRun the following code to see how the model does with Adam. | # train 3-layer model
layers_dims = [train_X.shape[0], 5, 2, 1]
parameters = model(train_X, train_Y, layers_dims, optimizer = "adam")
# Predict
predictions = predict(train_X, train_Y, parameters)
# Plot decision boundary
plt.title("Model with Adam optimization")
axes = plt.gca()
axes.set_xlim([-1.5,2.5])
axes.set_yli... | Cost after epoch 0: 0.690552
Cost after epoch 1000: 0.185567
Cost after epoch 2000: 0.150852
Cost after epoch 3000: 0.074454
Cost after epoch 4000: 0.125936
Cost after epoch 5000: 0.104235
Cost after epoch 6000: 0.100552
Cost after epoch 7000: 0.031601
Cost after epoch 8000: 0.111709
Cost after epoch 9000: 0.197648
| Apache-2.0 | Week2/Optimization+methods.ipynb | softwarebrahma/Deep-Learning-Specialization-Improving-Deep-Neural-Network-Hyperparam-TuneRegularizationOptimization |
YOLOv3 - Functions changing the pipeline to functions to make the implementation easier | import os.path
import cv2
import numpy as np
import requests
yolo_config = 'yolov3.cfg'
if not os.path.isfile(yolo_config):
url = 'https://raw.githubusercontent.com/pjreddie/darknet/master/cfg/yolov3.cfg'
r = requests.get(url)
with open(yolo_config, 'wb') as f:
f.write(r.content)
# Download YOLO n... | _____no_output_____ | MIT | Research Papers/YOLOv3_scripts.ipynb | Hira63S/DeepLearningResearch |
After we get the network outputs, we have to pre-process the network outputs and apply non-max suppression over them to produce the final set of detected objects | def get_boxes(outs):
class_ids = []
confidences = []
boxes = []
for out in outs:
# iterate over the anchor boxes for each class
for detection in out:
center_x = int(detection[0] * image.shape[1])
center_y = int(detection[1] * image.shape[0])
... | _____no_output_____ | MIT | Research Papers/YOLOv3_scripts.ipynb | Hira63S/DeepLearningResearch |
2 Protein Visualization ***For the purposes of this tutorial, we will use the HIV-1 protease structure (PDB ID: 1HSG). It is a homodimer with two chains of 99 residues each. Before starting to perform any simulations and data analysis, we need to observe and familiarize with the protein of interest.There are various ... | # Import NGLView
import nglview
# Select as your protein the 1HSG pdb entry
protein_view = nglview.show_pdbid('1hsg')
protein_view.gui_style = 'ngl'
#Uncomment the command below to add a hyperball representation of the crystal water oxygens in grey
#protein_view.add_hyperball('HOH', color='grey', opacity=1.0)
#Uncom... | _____no_output_____ | BSD-3-Clause | tutorials/MD/02_Protein_Visualization.ipynb | bigginlab/OxCompBio |
Image features exercise*Complete and hand in this completed worksheet (including its outputs and any supporting code outside of the worksheet) with your assignment submission. For more details see the [assignments page](http://vision.stanford.edu/teaching/cs231n/assignments.html) on the course website.*We have seen th... | import random
import numpy as np
from cs231n.data_utils import load_CIFAR10
import matplotlib.pyplot as plt
%matplotlib inline
plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots
plt.rcParams['image.interpolation'] = 'nearest'
plt.rcParams['image.cmap'] = 'gray'
# for auto-reloading extenrnal modu... | _____no_output_____ | MIT | assignments2016/assignment1/features.ipynb | janlukasschroeder/Stanford-cs231n |
Load dataSimilar to previous exercises, we will load CIFAR-10 data from disk. | from cs231n.features import color_histogram_hsv, hog_feature
def get_CIFAR10_data(num_training=49000, num_validation=1000, num_test=1000):
# Load the raw CIFAR-10 data
cifar10_dir = 'cs231n/datasets/cifar-10-batches-py'
X_train, y_train, X_test, y_test = load_CIFAR10(cifar10_dir)
# Subsample the data
mask... | _____no_output_____ | MIT | assignments2016/assignment1/features.ipynb | janlukasschroeder/Stanford-cs231n |
Extract FeaturesFor each image we will compute a Histogram of OrientedGradients (HOG) as well as a color histogram using the hue channel in HSVcolor space. We form our final feature vector for each image by concatenatingthe HOG and color histogram feature vectors.Roughly speaking, HOG should capture the texture of the... | from cs231n.features import *
num_color_bins = 10 # Number of bins in the color histogram
feature_fns = [hog_feature, lambda img: color_histogram_hsv(img, nbin=num_color_bins)]
X_train_feats = extract_features(X_train, feature_fns, verbose=True)
X_val_feats = extract_features(X_val, feature_fns)
X_test_feats = extract... | _____no_output_____ | MIT | assignments2016/assignment1/features.ipynb | janlukasschroeder/Stanford-cs231n |
Train SVM on featuresUsing the multiclass SVM code developed earlier in the assignment, train SVMs on top of the features extracted above; this should achieve better results than training SVMs directly on top of raw pixels. | # Use the validation set to tune the learning rate and regularization strength
from cs231n.classifiers.linear_classifier import LinearSVM
learning_rates = [1e-9, 1e-8, 1e-7]
regularization_strengths = [1e5, 1e6, 1e7]
results = {}
best_val = -1
best_svm = None
pass
###################################################... | _____no_output_____ | MIT | assignments2016/assignment1/features.ipynb | janlukasschroeder/Stanford-cs231n |
Inline question 1:Describe the misclassification results that you see. Do they make sense? Neural Network on image featuresEarlier in this assigment we saw that training a two-layer neural network on raw pixels achieved better classification performance than linear classifiers on raw pixels. In this notebook we have ... | print X_train_feats.shape
from cs231n.classifiers.neural_net import TwoLayerNet
input_dim = X_train_feats.shape[1]
hidden_dim = 500
num_classes = 10
net = TwoLayerNet(input_dim, hidden_dim, num_classes)
best_net = None
################################################################################
# TODO: Train a t... | _____no_output_____ | MIT | assignments2016/assignment1/features.ipynb | janlukasschroeder/Stanford-cs231n |
Nuclear Fuel Cycle OverviewThe nuclear fuel cycle is the technical and economic system traversed by nuclear fuel during the generation of nuclear power. Learning ObjectivesBy the end of this lesson, you should be able to:- Categorize types of fission reactors by their fuels and coolants.- Summarize the history and key... | from IPython.display import IFrame
IFrame("https://embed.polleverywhere.com/free_text_polls/YWUBNMDynR0yeiu?controls=none&short_poll=true", width="1000", height="700", frameBorder="0")
from IPython.display import IFrame
IFrame("https://embed.polleverywhere.com/free_text_polls/rhvKnG3a6nKaNdU?controls=none&short_poll=tr... | _____no_output_____ | CC-BY-4.0 | introduction/02-nfc-overview.ipynb | abachma2/npre412 |
A really good summary, with images, can be found [here](https://www.theiet.org/media/1275/nuclear-reactors.pdf). |
from IPython.display import IFrame
IFrame("https://www.theiet.org/media/1275/nuclear-reactors.pdf", width=1000, height=700) | _____no_output_____ | CC-BY-4.0 | introduction/02-nfc-overview.ipynb | abachma2/npre412 |
What about fusion?Fusion devices can use Tritium, Deuterium, Protium, $^3He$, $^4He$.
dot.node('A', 'Mine')
dot.node('B', 'Mill')
dot.node('C', 'Conversion')
dot.node('D', 'Enrichment')
dot.node('E', 'Fuel Fabrication')
dot.node(... | _____no_output_____ | CC-BY-4.0 | introduction/02-nfc-overview.ipynb | abachma2/npre412 |
Single Pass or Multi Pass RecycleTo add reprocessing or recycling, and all high level spent nuclear fuel is eventually destined for a geologic repository | dot.node('Z', 'Reprocessing')
dot.edge('H', 'Z', label='Cooled SNF')
dot.edge('G', 'Z', label='Cooled SNF')
dot.edge('Z', 'E', label='Pu')
dot.edge('Z', 'E', label='U')
dot.edge('Z', 'I', label='FP')
dot | _____no_output_____ | CC-BY-4.0 | introduction/02-nfc-overview.ipynb | abachma2/npre412 |
Namespace* 為了將你寫的程式碼轉換成可以執行的程式,Python語言使用翻譯器(interpreter)來辨別你的程式碼,它會把你命名的變數分在不同的範圍內,這些範圍就叫作Namespace。* 每次創建一個變數時,翻譯器會在Namespace裡面記錄變數名稱和變數存的東西的記憶體位置。當有新的變數名稱時,翻譯器會先看新變數要存的值有沒有在紀錄裡,有的話就直接將新變數指定到該位置,例如:```pythona = 2a = a + 1b = 2```* 翻譯器認定的範圍大致上可以分成以下三類: * Built-in: 開啟翻譯器時就會有的,裡面就是有預設的函數和以下會介紹的資料結構。 * Module: 要透過... | a = 2
print(id(a))
b = 2
print(id(b)) | 10919456
10919456
| MIT | assets/images/pandas/Python3_data_structure.ipynb | haochunchang/haochunchang.github.io |
--- Data Structures* 資料結構就是各種用來存放資料的"容器",並且可以很有效率地操作資料。 [Sequence](Sequence)> _immutable v.s. mutable_ * [Lists](Lists): mutable = 可以更改內容的 * [Tuples](Tuples): immuntable = 不可以更改內容的 * [Range](Range): immuntable [Dictionary](Dictionary) [Set](Set)--- Sequence基本操作:* 檢查東西在不在sequence裡面```pythonx in seqx not in seq... | marvel_hero = ["Steve Rogers", "Tony Stark", "Thor Odinson"]
print(type(marvel_hero), marvel_hero)
marvel_hero.append("Hulk")
marvel_hero.insert(2, "Bruce Banner") # insert "Bruce Banner" into index 2
print(marvel_hero)
print(marvel_hero.pop()) # default: pop last item
marvel_hero[0] = "Captain America"
print(marvel_he... | Hulk
['Captain America', 'Tony Stark', 'Bruce Banner', 'Thor Odinson']
| MIT | assets/images/pandas/Python3_data_structure.ipynb | haochunchang/haochunchang.github.io |
List comprehension: 可以直接在list裡面處理東西,不用再另外寫for-loop(但是花費時間差不多) | %timeit list_hero = [i.lower() if i.startswith('T') else i.upper() for i in marvel_hero]
print(list_hero)
%%timeit
list_hero = []
for i in marvel_hero:
if i.startswith('T'):
list_hero.append(i.lower())
else:
list_hero.append(i.upper())
print(list_hero) | ['BRUCE BANNER', 'CAPTAIN AMERICA', 'thor odinson', 'tony stark']
| MIT | assets/images/pandas/Python3_data_structure.ipynb | haochunchang/haochunchang.github.io |
List可以排序,排序所花的時間和List長度成正比 | marvel_hero.sort(reverse=False) # sort in-place
marvel_hero
list_hero_sorted = sorted(list_hero) # return a sorted list
print(list_hero_sorted) | ['BRUCE BANNER', 'CAPTAIN AMERICA', 'thor odinson', 'tony stark']
| MIT | assets/images/pandas/Python3_data_structure.ipynb | haochunchang/haochunchang.github.io |
**注意!如果要複製list,不能直接指定給新的變數,這樣只是幫同一個list重新命名而已*** 此行為被稱為 shallow copy | a = [1, 2, 3, 4, 5]
b = a
print(id(a), id(b), id(a) == id(b))
b[0] = 8888
print(a) | 140032783977672 140032783977672 True
[8888, 2, 3, 4, 5]
| MIT | assets/images/pandas/Python3_data_structure.ipynb | haochunchang/haochunchang.github.io |
--- Tuples``` tuples = item1, item2, item3, ...```* 通常用來存放不同種類但是有關聯的資料。* ',' 決定是不是tuples,但是通常會用()來區分function call。例如:```pythondef f(a, b=0): return a1*a2 + bf((87, 2)) return 87*2 + 0``` | love_iron = ("Iron Man", 3000)
cap = "Captain America",
print(type(love_iron), love_iron)
print(love_iron + cap)
print("Does {} in the \"love_iron\" tuples?: {}".format("Iron", 'Iron' in love_iron))
print("Length of cap: {}".format(len(cap)))
max(love_iron) | _____no_output_____ | MIT | assets/images/pandas/Python3_data_structure.ipynb | haochunchang/haochunchang.github.io |
* ```enumerate()``` 用在for-loop裡面可以依次輸出(i, 第i個項目),這樣就不用另外去記錄你跑到第幾個項目 | for e in enumerate(love_iron + cap):
print(e, type(e)) | (0, 'Iron Man') <class 'tuple'>
(1, 3000) <class 'tuple'>
(2, 'Captain America') <class 'tuple'>
| MIT | assets/images/pandas/Python3_data_structure.ipynb | haochunchang/haochunchang.github.io |
--- Range* 產生一串**整數**,通常用在for-loop裡面來記錄次數或是當作index。* 如果要產生一串浮點數,就要用numpy.arange()。```range(start, stop[, step])``` | even_number = [x for x in range(0, 30, 2)]
for i in range(2, 10, 2):
print("The {}th even number is {}".format(i, even_number[i-1])) | The 2th even number is 2
The 4th even number is 6
The 6th even number is 10
The 8th even number is 14
| MIT | assets/images/pandas/Python3_data_structure.ipynb | haochunchang/haochunchang.github.io |
--- Dictionary``` {key1:value1, key2:value2, key3:value3, ...}```* 用來存放具有對應關係的資料。* ```key``` 不能重複,而且必須是hashable * 兩個條件: 1. 建立之後不會更改數值(immutable) 2. 可以和其他東西比較是不是一樣* 實際長相:hash table * 電腦透過一個叫hash的函數將key編碼成一串固定長度的數字,然後用這串數字當作value的index。 * 理想上,每串數字都不重複,這樣可以讓查詢速度在平均上不受裡面的東西數量影響。* [圖片來源](https://en.wikipedia.... | hero_id = {"Steve Rogers": 1,
"Tony Stark": 666,
"Thor Odinson": 999
}
hero_code = dict(zip(hero_id.keys(), ["Captain America", "God of Thunder", "Iron Man"]))
print(type(hero_code), hero_code)
# dict[key]: 輸出相對應的value,如果key not in dict則輸出 KeyError
# dict.get(key, default=None): 輸出相對... | {'Bruce Banner': 87, 'Thor Odinson': 999, 'Steve Rogers': 1, 'Tony Stark': 666}
| MIT | assets/images/pandas/Python3_data_structure.ipynb | haochunchang/haochunchang.github.io |
Dictionary View* 用來看dict裡面目前的值是什麼,可以放在for-loop一個一個處理: * dict.keys() 會輸出keys * dict.values() 會輸出values * dict.items() 會輸出(key, value)的 tuples> **注意!輸出的順序不一定代表加入dictionary的順序!**> 但是key和value的對應順序會一樣。* 如果想要固定輸出的順序,就要用list或是[collections.OrderedDict](https://docs.python.org/3.6/library/collections.htmlcollections.... | print(hero_id.keys())
print(hero_id.values())
print(hero_id.items())
for name, code in hero_code.items():
print("{} is {}".format(name, code)) | Steve Rogers is Captain America
Thor Odinson is God of Thunder
Tony Stark is Iron Man
| MIT | assets/images/pandas/Python3_data_structure.ipynb | haochunchang/haochunchang.github.io |
--- Set``` set = {item1, item2, item3, ...}```* 用來存放不重複的資料,放進重複的資料也只會保存一個。* set可以更改內容,frozenset不能更改內容(immuntable)。* 可以操作的動作和數學上的set很像:([圖片來源](https://www.learnbyexample.org/python-set/)) * union (```A | B```) * intersection (```A & B```) * difference (```A - B```) * symmetric difference (```A ^ B```) * s... | set_example = {"o", 7, 7, 7, 7, 7, 7, 7}
print(type(set_example), set_example)
A = set("Shin Shin ba fei jai")
B = set("Ni may yo may may")
print(A)
print(B)
A ^ B
a = set([[1],2,3,3,3,3])
a | _____no_output_____ | MIT | assets/images/pandas/Python3_data_structure.ipynb | haochunchang/haochunchang.github.io |
----- Numpy Array* 以分析資料來說,常見的形式就是矩陣(array),python有一個package叫做numpy。* 這個package可以讓我們更快更方便的處理矩陣。* Full documentation: https://docs.scipy.org/doc/* 快速教學:http://cs231n.github.io/python-numpy-tutorial/numpy-arrays```bash 安裝它只要一個步驟:pip3 install numpy``` | import numpy as np
b = np.array([[1,2,3],[4,5,6]]) # 2D array
print(b)
print(b.shape, b.dtype)
print(b[0, 0], b[0, 1], b[1, 0]) # array[row_index, col_index] | [[1 2 3]
[4 5 6]]
(2, 3) int64
1 2 4
| MIT | assets/images/pandas/Python3_data_structure.ipynb | haochunchang/haochunchang.github.io |
有許多方便建立矩陣的函數* 像是全部數值為0、全部數值為1、Identity等等,更多函數都在[這裡](https://docs.scipy.org/doc/numpy/reference/routines.array-creation.htmlroutines-array-creation)。 | z = np.zeros((8,7))
z | _____no_output_____ | MIT | assets/images/pandas/Python3_data_structure.ipynb | haochunchang/haochunchang.github.io |
取出array中的row或是column* 可以跟list一樣用```1:5```的語法。* 也可以用boolean的方式選取部分的數值。 | yeee = np.fromfile(join("data", "numpy_sample.txt"), sep=' ')
yeee = yeee.reshape((4,4))
print(yeee)
print(yeee[:2,0]) # 取出第一個column的前兩個row
print(yeee[-1,:]) # 取出最後一個row
yeee[yeee > 6] | _____no_output_____ | MIT | assets/images/pandas/Python3_data_structure.ipynb | haochunchang/haochunchang.github.io |
矩陣運算* ``` + - * / ``` 都是element-wise,也就是矩陣內每個數值各自獨立運算。* 矩陣相乘要用 ```dot```* 更多數學運算在[這裡](https://docs.scipy.org/doc/numpy/reference/routines.math.html)。 | x = np.array([[1,2],[3,4]])
y = np.array([[5,6],[7,8]])
print(x.dot(y) == np.dot(x, y)) | [[ True True]
[ True True]]
| MIT | assets/images/pandas/Python3_data_structure.ipynb | haochunchang/haochunchang.github.io |
Broadcasting* 在numpy中,如果我們要對不同形狀的矩陣進行運算,我們可以直接在形狀相同的地方直接進行運算。 | x = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
v = np.array([1, 0, 1])
y = x + v
print(y) # v 分別加在x的每一個row | [[ 2 2 4]
[ 5 5 7]
[ 8 8 10]
[11 11 13]]
| MIT | assets/images/pandas/Python3_data_structure.ipynb | haochunchang/haochunchang.github.io |
如果想要使用兩個數值一樣的矩陣,必須注意shallow copy的問題。* 用```x[:]```拿出的東西是x的一個View,也就是說,看到的其實是x的data,更動View就是更動x。* 如果要真正複製一份出來,就要用```.copy()```。 | x = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
shallow = x[:]
deep = x.copy()
shallow[0, 0] = 9487
deep[0, 0] = 5566
print(x) | [[9487 2 3]
[ 4 5 6]
[ 7 8 9]
[ 10 11 12]]
| MIT | assets/images/pandas/Python3_data_structure.ipynb | haochunchang/haochunchang.github.io |
---- Files* 知道如何在程式裡面存放資料後,還需要知道怎麼存檔和讀檔。* 每打開一個檔案時,需要跟電腦說哪一種模式:| Access mode | access_flag | detail ||:------------|:-----|:-------|| Read only | r | 從檔案開頭讀取 || Write only | w | 寫進去的東西會從頭開始寫,如果本來有內容,會覆蓋過去 || Append only | a | 寫進去的東西會接在檔案後面 || Enhance | + | 讀+寫或是讀+append |* f是個負責處理該檔案的管理者,可以透過f對檔案做事情。 * f記錄著現在讀取到檔案的哪... | from os.path import join
with open(join("data", "heyhey.txt"), 'r', encoding='utf-8') as f:
print(f.read() + '\n')
print(f.readlines())
f.seek(0) # 回到檔案開頭
readlines = f.readlines(1)
print(readlines, type(readlines)) # 以 '\n'為界線,一行一行讀
single_line = f.readline()
print(single_line, type(s... | Shin Shin ba fei jai
| MIT | assets/images/pandas/Python3_data_structure.ipynb | haochunchang/haochunchang.github.io |
Perform fCUBT on the data | # Load packages
import matplotlib
import matplotlib.pyplot as plt
import pickle
from FDApy.clustering.fcubt import Node, FCUBT
from FDApy.representation.functional_data import DenseFunctionalData
from FDApy.preprocessing.dim_reduction.fpca import UFPCA
from matplotlib import colors as mcolors
COLORS = ['#377eb8', '#f... | _____no_output_____ | MIT | scenario_1/021-fcubt_review.ipynb | StevenGolovkine/fcubt |
Plotting very large datasets meaningfully, using `datashader`There are a variety of approaches for plotting large datasets, but most of them are very unsatisfactory. Here we first show some of the issues, then demonstrate how the `datashader` library helps make large datasets truly practical. We'll use part of the we... | import pandas as pd
%time df = pd.read_csv('../data/nyc_taxi.csv',usecols= \
['pickup_x', 'pickup_y', 'dropoff_x','dropoff_y', 'passenger_count','tpep_pickup_datetime'])
df.tail() | _____no_output_____ | MIT | datashader-work/datashader-examples/topics/nyc_taxi.ipynb | ventureBorbot/Data-Analysis |
As you can see, this file contains about 12 million pickup and dropoff locations (in Web Mercator coordinates), with passenger counts. Define a simple plot | from bokeh.models import BoxZoomTool
from bokeh.plotting import figure, output_notebook, show
output_notebook()
NYC = x_range, y_range = ((-8242000,-8210000), (4965000,4990000))
plot_width = int(750)
plot_height = int(plot_width//1.2)
def base_plot(tools='pan,wheel_zoom,reset',plot_width=plot_width, plot_height=pl... | _____no_output_____ | MIT | datashader-work/datashader-examples/topics/nyc_taxi.ipynb | ventureBorbot/Data-Analysis |
1000-point scatterplot: undersamplingAny plotting program should be able to handle a plot of 1000 datapoints. Here the points are initially overplotting each other, but if you hit the Reset button (top right of plot) to zoom in a bit, nearly all of them should be clearly visible in the following Bokeh plot of a rando... | %%time
from bokeh.tile_providers import STAMEN_TERRAIN
samples = df.sample(n=1000)
p = base_plot()
p.add_tile(STAMEN_TERRAIN)
p.circle(x=samples['dropoff_x'], y=samples['dropoff_y'], **options)
show(p) | _____no_output_____ | MIT | datashader-work/datashader-examples/topics/nyc_taxi.ipynb | ventureBorbot/Data-Analysis |
10,000-point scatterplot: overplottingWe can of course plot more points to reduce the amount of undersampling. However, even if we only try to plot 0.1% of the data, ignoring the other 99.9%, we will find major problems with *overplotting*, such that the true density of dropoffs in central Manhattan is impossible to ... | %%time
samples = df.sample(n=10000)
p = base_plot()
p.circle(x=samples['dropoff_x'], y=samples['dropoff_y'], **options)
show(p) | _____no_output_____ | MIT | datashader-work/datashader-examples/topics/nyc_taxi.ipynb | ventureBorbot/Data-Analysis |
Overplotting is reduced if you zoom in on a particular region (may need to click to enable the wheel-zoom tool in the upper right of the plot first, then use the scroll wheel). However, then the problem switches to back to serious undersampling, as the too-sparsely sampled datapoints get revealed for zoomed-in regions... | import datashader as ds
from datashader import transfer_functions as tf
from datashader.colors import Greys9
Greys9_r = list(reversed(Greys9))[:-2]
%%time
cvs = ds.Canvas(plot_width=plot_width, plot_height=plot_height, x_range=x_range, y_range=y_range)
agg = cvs.points(df, 'dropoff_x', 'dropoff_y', ds.count('passenger... | _____no_output_____ | MIT | datashader-work/datashader-examples/topics/nyc_taxi.ipynb | ventureBorbot/Data-Analysis |
The resulting image is similar to the 100,000-point Bokeh plot above, but (a) makes use of all 12 million datapoints, (b) is computed in only a tiny fraction of the time, (c) does not require any magic-number parameters like size and alpha, and (d) automatically ensures that there is no saturation or overplotting: | img | _____no_output_____ | MIT | datashader-work/datashader-examples/topics/nyc_taxi.ipynb | ventureBorbot/Data-Analysis |
This plot renders the count at every pixel as a color from the specified range (here from white to dark blue), mapped linearly. If your display device were linear, and the data were distributed evenly across this color range, then the result of such linear, auto-ranged processing would be an effective, parameter-free w... | import numpy as np
def histogram(x,colors=None):
hist,edges = np.histogram(x, bins=100)
p = figure(y_axis_label="Pixels",
tools='', height=130, outline_line_color=None,
min_border=0, min_border_left=0, min_border_right=0,
min_border_top=0, min_border_bottom=0)
p... | _____no_output_____ | MIT | datashader-work/datashader-examples/topics/nyc_taxi.ipynb | ventureBorbot/Data-Analysis |
Clearly, most of the pixels have very low counts (under 3000), while a very few pixels have much larger counts (up to 22000, in this case). When these values are mapped into colors for display, nearly all of the pixels will end up being colored with the lowest colors in the range, i.e. white or nearly white, while the... | histogram(np.log1p(agg.values))
tf.shade(agg, cmap=Greys9_r, how='log') | _____no_output_____ | MIT | datashader-work/datashader-examples/topics/nyc_taxi.ipynb | ventureBorbot/Data-Analysis |
We can now see that there is rich structure throughout this dataset -- geographic features like streets and buildings are clearly modulating the values in both the high-dropoff regions in Manhattan and the relatively low-dropoff regions in the surrounding areas. Still, this choice is arbitrary -- why the log function ... | histogram(tf.eq_hist(agg.values))
tf.shade(agg, cmap=Greys9_r, how='eq_hist') | _____no_output_____ | MIT | datashader-work/datashader-examples/topics/nyc_taxi.ipynb | ventureBorbot/Data-Analysis |
The histogram is now fully flat (apart from the spacing of bins caused by the discrete nature of integer counting). Effectively, the visualization now shows a rank-order or percentile distribution of the data. I.e., pixels are now colored according to where their corresponding counts fall in the distribution of all co... | import datashader as ds
from datashader.bokeh_ext import InteractiveImage
from functools import partial
from datashader.utils import export_image
from datashader.colors import colormap_select, Greys9, Hot, inferno
background = "black"
export = partial(export_image, export_path="export", background=background)
cm = par... | _____no_output_____ | MIT | datashader-work/datashader-examples/topics/nyc_taxi.ipynb | ventureBorbot/Data-Analysis |
You can now zoom in interactively to this plot, seeing all the points available in that viewport, without ever needing to change the plot parameters for that specific zoom level. Each time you zoom or pan, a new image is rendered (which takes a few seconds for large datasets), and displayed overlaid any other plot ele... | import numpy as np
from functools import partial
def create_image90(x_range, y_range, w=plot_width, h=plot_height):
cvs = ds.Canvas(plot_width=w, plot_height=h, x_range=x_range, y_range=y_range)
agg = cvs.points(df, 'dropoff_x', 'dropoff_y', ds.count('passenger_count'))
img = tf.shade(agg.where(agg>np.per... | _____no_output_____ | MIT | datashader-work/datashader-examples/topics/nyc_taxi.ipynb | ventureBorbot/Data-Analysis |
If you zoom in to the plot above, you can see that the 90th-percentile criterion at first highlights the most active areas in the entire dataset, and then highlights the most active areas in each subsequent viewport. Here yellow has been chosen to highlight the strongest peaks, and if you zoom in on one of those peaks... | def merged_images(x_range, y_range, w=plot_width, h=plot_height, how='log'):
cvs = ds.Canvas(plot_width=w, plot_height=h, x_range=x_range, y_range=y_range)
picks = cvs.points(df, 'pickup_x', 'pickup_y', ds.count('passenger_count'))
drops = cvs.points(df, 'dropoff_x', 'dropoff_y', ds.count('passenger_count... | _____no_output_____ | MIT | datashader-work/datashader-examples/topics/nyc_taxi.ipynb | ventureBorbot/Data-Analysis |
Now you can see that pickups are more common on major roads, as you'd expect, and dropoffs are more common on side streets. In Manhattan, roads running along the island are more common for pickups. If you zoom in to any location, the data will be re-aggregated to the new resolution automatically, again calculating for... | df['hour'] = pd.to_datetime(df['tpep_pickup_datetime']).dt.hour.astype('category')
colors = ["#FF0000","#FF3F00","#FF7F00","#FFBF00","#FFFF00","#BFFF00","#7FFF00","#3FFF00",
"#00FF00","#00FF3F","#00FF7F","#00FFBF","#00FFFF","#00BFFF","#007FFF","#003FFF",
"#0000FF","#3F00FF","#7F00FF","#BF00FF","#FF0... | _____no_output_____ | MIT | datashader-work/datashader-examples/topics/nyc_taxi.ipynb | ventureBorbot/Data-Analysis |
During Private Multiplication , we require the parties to be able to communicate with each other.We make sure that our Actions are **Idempotent** and **Atomic** such that when a given action is not able to execute, it requeues itself to the back of the queue.We set a maximum amount of retries,until eventually failing, ... | out = tensor_1 + tensor_2
out2 = out > 3
out2.block.reconstruct()
mpc_1 = tensor_1 * tensor_2
mpc_2 = tensor_2 * tensor_3
mpc = mpc_1 * mpc_2 * 3
mpc.block.reconstruct()
mpc_1 = tensor_1 + tensor_2
mpc_2 = tensor_2 + tensor_3
mpc3 = mpc_1 + mpc_2 + 3
mpc3.block.reconstruct() | _____no_output_____ | Apache-2.0 | notebooks/smpc/Private Mul Tensor Abstraction.ipynb | Noob-can-Compile/PySyft |
mlconfig | from mlrun import mlconf
import os
mlconf.dbpath = mlconf.dbpath or 'http://mlrun-api:8080'
mlconf.artifact_path = mlconf.artifact_path or os.path.abspath('./') | _____no_output_____ | Apache-2.0 | describe/describe.ipynb | michaelk-igz/functions |
save | from mlrun import code_to_function
# create job function object from notebook code
fn = code_to_function("describe", handler="summarize",
description="describe and visualizes dataset stats",
categories=["analysis"],
labels = {"author": "yjb"},
... | > 2020-07-23 07:46:39,543 [info] function spec saved to path: function.yaml
| Apache-2.0 | describe/describe.ipynb | michaelk-igz/functions |
tests | from mlrun.platforms import auto_mount
fn.apply(auto_mount())
from mlrun import NewTask, run_local
#DATA_URL = "https://iguazio-sample-data.s3.amazonaws.com/datasets/classifier-data.csv"
DATA_URL = 'https://iguazio-sample-data.s3.amazonaws.com/datasets/iris_dataset.csv'
task = NewTask(
name="tasks-describe",
... | _____no_output_____ | Apache-2.0 | describe/describe.ipynb | michaelk-igz/functions |
run locally | run = run_local(task) | > 2020-07-22 09:00:32,582 [debug] Validating field against patterns: {'field_name': 'run.metadata.name', 'field_value': 'tasks-describe', 'pattern': ['^.{0,63}$', '^(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])?$']}
> 2020-07-22 09:00:32,598 [info] starting run tasks-describe uid=f30656601819462c892a9365dd175f72 -> http:... | Apache-2.0 | describe/describe.ipynb | michaelk-igz/functions |
run remotely | fn.run(task, inputs={"table": DATA_URL}) | > 2020-07-22 09:00:39,154 [debug] Validating field against patterns: {'field_name': 'run.metadata.name', 'field_value': 'tasks-describe', 'pattern': ['^.{0,63}$', '^(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])?$']}
> 2020-07-22 09:00:39,161 [info] starting run tasks-describe uid=d8edd5e4b8004437927f0810d2ad1658 -> http:... | Apache-2.0 | describe/describe.ipynb | michaelk-igz/functions |
Taller Presencial --- Programación en Python=== El algoritmo MapReduce de Hadoop se presenta en la siguiente figura. Se desea escribir un programa que realice el conteo de palabras usando el algoritmo MapReduce. | #
# A continuación se crea las carpetas /tmp/input, /tmp/output y tres archivos de prueba
#
!rm -rf /tmp/input /tmp/output
!mkdir /tmp/input
!mkdir /tmp/output
%%writefile /tmp/input/text0.txt
Analytics is the discovery, interpretation, and communication of meaningful patterns
in data. Especially valuable in areas ric... | _____no_output_____ | MIT | notebooks/ciencia_de_los_datos/taller_presencial-programacion_en_python.ipynb | driverava/datalabs |
_Lambda School Data Science Unit 2_ Classification & Validation Sprint Challenge Follow the instructions for each numbered part to earn a score of 2. See the bottom of the notebook for a list of ways you can earn a score of 3. For this Sprint Challenge, you'll predict whether a person's income exceeds $50k/yr, bas... | !pip install category_encoders
import category_encoders as ce
from sklearn.metrics import accuracy_score, confusion_matrix, roc_auc_score
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.linear_model import LogisticRegression
from sklearn.prep... | _____no_output_____ | MIT | DS_Unit_2_Sprint_Challenge_3_Classification_Validation.ipynb | mkirby1995/DS-Unit-2-Sprint-3-Classification-Validation |
Part 1 — Begin with baselinesSplit the data into an **X matrix** (all the features) and **y vector** (the target).(You _don't_ need to split the data into train and test sets here. You'll be asked to do that at the _end_ of Part 1.) | df['income'].value_counts()
X = df.drop(columns='income')
Y = df['income'].replace({'<=50K':0, '>50K':1}) | _____no_output_____ | MIT | DS_Unit_2_Sprint_Challenge_3_Classification_Validation.ipynb | mkirby1995/DS-Unit-2-Sprint-3-Classification-Validation |
What **accuracy score** would you get here with a **"majority class baseline"?** (You can answer this question either with a scikit-learn function or with a pandas function.) | majority_class = Y.mode()[0]
majority_class_prediction = [majority_class] * len(Y)
accuracy_score(Y, majority_class_prediction) | _____no_output_____ | MIT | DS_Unit_2_Sprint_Challenge_3_Classification_Validation.ipynb | mkirby1995/DS-Unit-2-Sprint-3-Classification-Validation |
What **ROC AUC score** would you get here with a **majority class baseline?**(You can answer this question either with a scikit-learn function or with no code, just your understanding of ROC AUC.) | roc_auc_score(Y, majority_class_prediction) | _____no_output_____ | MIT | DS_Unit_2_Sprint_Challenge_3_Classification_Validation.ipynb | mkirby1995/DS-Unit-2-Sprint-3-Classification-Validation |
In this Sprint Challenge, you will use **"Cross-Validation with Independent Test Set"** for your model validaton method.First, **split the data into `X_train, X_test, y_train, y_test`**. You can include 80% of the data in the train set, and hold out 20% for the test set. | X_train, X_test, Y_train, Y_test = train_test_split(X,Y, test_size=.2, random_state=42) | _____no_output_____ | MIT | DS_Unit_2_Sprint_Challenge_3_Classification_Validation.ipynb | mkirby1995/DS-Unit-2-Sprint-3-Classification-Validation |
Part 2 — Modeling with Logistic Regression! - You may do exploratory data analysis and visualization, but it is not required.- You may **use all the features, or select any features** of your choice, as long as you select at least one numeric feature and one categorical feature.- **Scale your numeric features**, using... | pipeline = make_pipeline(ce.OneHotEncoder(use_cat_names=True),
StandardScaler(),
LogisticRegression(solver='lbfgs', max_iter=1000))
scores = cross_val_score(pipeline, X_train, Y_train, scoring='accuracy', cv=10, n_jobs=1, verbose=10)
print('Cross-Validation accuracy sco... | Cross-Validation accuracy scores: [0.8452975 0.85105566 0.84683301 0.85412668 0.84683301 0.85143954
0.84952015 0.85143954 0.84754224 0.86059908]
Average: 0.8504686426610766
| MIT | DS_Unit_2_Sprint_Challenge_3_Classification_Validation.ipynb | mkirby1995/DS-Unit-2-Sprint-3-Classification-Validation |
Part 3 — Modeling with Tree Ensembles!Part 3 is the same as Part 2, except this time, use a **Random Forest** or **Gradient Boosting** classifier. You may use scikit-learn, xgboost, or any other library. Then, print your model's cross-validation accuracy score. | pipeline = make_pipeline(ce.OneHotEncoder(use_cat_names=True),
StandardScaler(),
RandomForestClassifier(max_depth=2, n_estimators=40))
scores = cross_val_score(pipeline, X_train, Y_train, scoring='accuracy', cv=10, n_jobs=1, verbose=10)
print('Cross-Validation accuracy ... | Cross-Validation accuracy scores: [0.76084453 0.77044146 0.76506718 0.76852207 0.7596929 0.77044146
0.76583493 0.77274472 0.76228879 0.77688172]
Average: 0.7672759758351984
| MIT | DS_Unit_2_Sprint_Challenge_3_Classification_Validation.ipynb | mkirby1995/DS-Unit-2-Sprint-3-Classification-Validation |
Part 4 — Calculate classification metrics from a confusion matrixSuppose this is the confusion matrix for your binary classification model: Predicted Negative Positive Actual Negative 85 58 Positive 8 36 | true_neg = 85
true_pos = 36
false_neg = 8
false_pos = 58
pred_neg = true_neg + false_neg
pred_pos = true_pos + false_pos
actual_pos = false_neg + true_pos
actual_neg = false_pos + true_neg | _____no_output_____ | MIT | DS_Unit_2_Sprint_Challenge_3_Classification_Validation.ipynb | mkirby1995/DS-Unit-2-Sprint-3-Classification-Validation |
Calculate accuracy | accuracy = (true_neg + true_pos)/ (pred_neg + pred_pos)
accuracy | _____no_output_____ | MIT | DS_Unit_2_Sprint_Challenge_3_Classification_Validation.ipynb | mkirby1995/DS-Unit-2-Sprint-3-Classification-Validation |
Calculate precision | precision = (true_pos) / (pred_pos)
precision | _____no_output_____ | MIT | DS_Unit_2_Sprint_Challenge_3_Classification_Validation.ipynb | mkirby1995/DS-Unit-2-Sprint-3-Classification-Validation |
Calculate recall | recall = true_pos / actual_pos
recall | _____no_output_____ | MIT | DS_Unit_2_Sprint_Challenge_3_Classification_Validation.ipynb | mkirby1995/DS-Unit-2-Sprint-3-Classification-Validation |
**author**: lukethompson@gmail.com**date**: 7 Oct 2017**language**: Python 3.5**license**: BSD3 alpha_diversity_90bp_100bp_150bp.ipynb | import pandas as pd
import math
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from empcolors import get_empo_cat_color
%matplotlib inline | _____no_output_____ | BSD-3-Clause | code/05-alpha-diversity/alpha_diversity_90bp_100bp_150bp.ipynb | justinshaffer/emp |
*** Choose 2k or qc-filtered subset (one or the other) *** | path_map = '../../data/mapping-files/emp_qiime_mapping_subset_2k.tsv' # already has 90bp alpha-div data
version = '2k'
path_map = '../../data/mapping-files/emp_qiime_mapping_qc_filtered.tsv' # already has 90bp alpha-div data
version = 'qc' | _____no_output_____ | BSD-3-Clause | code/05-alpha-diversity/alpha_diversity_90bp_100bp_150bp.ipynb | justinshaffer/emp |
*** Merged mapping file and alpha-div *** | path_adiv100 = '../../data/alpha-div/emp.100.min25.deblur.withtax.onlytree_5000.txt'
path_adiv150 = '../../data/alpha-div/emp.150.min25.deblur.withtax.onlytree_5000.txt'
df_map = pd.read_csv(path_map, sep='\t', index_col=0)
df_adiv100 = pd.read_csv(path_adiv100, sep='\t', index_col=0)
df_adiv150 = pd.read_csv(path_adiv... | _____no_output_____ | BSD-3-Clause | code/05-alpha-diversity/alpha_diversity_90bp_100bp_150bp.ipynb | justinshaffer/emp |
*** Removing all samples without 150bp alpha-div results *** | df1 = df_merged[['empo_3', 'adiv_observed_otus', 'adiv_observed_otus_100bp', 'adiv_observed_otus_150bp']]
df1.columns = ['empo_3', 'observed_tag_sequences_90bp', 'observed_tag_sequences_100bp', 'observed_tag_sequences_150bp']
df1.dropna(axis=0, inplace=True)
g = sns.PairGrid(df1, hue='empo_3', palette=get_empo_cat_colo... | _____no_output_____ | BSD-3-Clause | code/05-alpha-diversity/alpha_diversity_90bp_100bp_150bp.ipynb | justinshaffer/emp |
Value Investing Indicators from SEC Filings Data Source: https://www.sec.gov/dera/data/financial-statement-data-sets.html | import pandas as pd
import os
import shutil
import glob
import sys
import warnings
import functools
from functools import reduce
import os
pd.set_option('display.max_columns', 999)
warnings.simplefilter("ignore")
os.chdir("..")
dir_root = os.getcwd()
dir_raw = dir_root + u"/sec_filings/Raw"
cik_lookup = pd.read_... | _____no_output_____ | BSD-3-Clause | explore/tags_filter.ipynb | cpc-azimuths/azimuth-rain |
Benjamin Graham Formulas:* NCAVPS = CurrentAssets - (Total Liabilities + Preferred Stock) ÷ Shares Outstanding * Less than 1.10 * Debt to Assets = Current Assets / Current Liabilities * Greater than 1.50* Price / Earnings per Share ratio * Less than 9.0* PRICE TO BOOK VALUE = (P/BV) * Where BV = (Total ... |
sec_df['NCAVPS'] = sec_df['AssetsCurrent'] - (sec_df['Liabilities'] + sec_df[
'PreferredStockValue']) / sec_df['CommonStockSharesOutstanding']
sec_df['DebtToAssets'] = sec_df['AssetsCurrent'] / sec_df['LiabilitiesCurrent']
sec_df['PE'] = sec_df['SharePrice'] / sec_df['EarningsPerShareBasic']
sec_df['PBV'] = sec_df... | _____no_output_____ | BSD-3-Clause | explore/tags_filter.ipynb | cpc-azimuths/azimuth-rain |
Warren Buffet Rules Formulas* Debt/Equity= Total Liabilities / Total Shareholders’ Equity * Less than 1 and ROE is greater than 10%* Return on Earnings = (Net Income / Stock Holders Equity) * Is Positive* Gross Profit Margin = Gross Profit / Revenue * Greater than 40% * Quarter over Quarter EPS * Grea... |
sec_df['DebtEquity'] = sec_df['Liabilities'] / sec_df['StockholdersEquity']
sec_df['ReturnEarnings'] = sec_df['NetIncomeLoss'] / sec_df['StockholdersEquity']
sec_df["GrossProfitMargin"] = sec_df['GrossProfit'] / sec_df['SalesRevenueNet']
sec_df["EPS"] = sec_df["EarningsPerShareBasic"]
sec_df["StockBuybacks"] = sec... | _____no_output_____ | BSD-3-Clause | explore/tags_filter.ipynb | cpc-azimuths/azimuth-rain |
Modeling@Author: Bruno VieiraGoals: Create a classification model able to identify a BOT account on twitter, using only profile-based features. | # Libs
import os
import numpy as np
import pandas as pd
from sklearn.pipeline import Pipeline
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.metrics import classification_report, precision_score, recall_score, roc_auc_score, average_precision_score, f1_score
from skl... | _____no_output_____ | MIT | notebooks/modeling.ipynb | brunocvs7/bot_detection_twitter_profile_features |
1) Training | X_train = df_twitter_train.drop('label', axis=1)
y_train = df_twitter_train['label']
cat_columns = df_twitter_train.select_dtypes(include=['bool', 'object']).columns.tolist()
num_columns = df_twitter_train.select_dtypes(include=['int32','int64','float32', 'float64']).columns.tolist()
num_columns.remove('label')
skf = ... | _____no_output_____ | MIT | notebooks/modeling.ipynb | brunocvs7/bot_detection_twitter_profile_features |
2) Evaluation 2.1) Cross Validation | cross_validation_results = pd.DataFrame(cross_validation_results)
cross_validation_results
1.96*cross_validation_results['train_average_precision'].std()
print(f"Avg Train Avg Precision:{np.round(cross_validation_results['train_average_precision'].mean(), 2)} +/- {np.round(1.96*cross_validation_results['train_average_p... | ROC - AUC Train:0.69 +/- 0.01
ROC - AUC Test:0.68 +/- 0.11
| MIT | notebooks/modeling.ipynb | brunocvs7/bot_detection_twitter_profile_features |
2.2) Test Set | def build_features(df):
list_columns_colors = df.filter(regex='color').columns.tolist()
df = df.replace({'false':'FALSE', 'true':'TRUE', False:'FALSE', True:'TRUE'})
df['name'] = df['name'].apply(lambda x: len(x) if x is not np.nan else 0)
df['profile_location'] = df['profile_location'].apply(lambda x: ... | _____no_output_____ | MIT | notebooks/modeling.ipynb | brunocvs7/bot_detection_twitter_profile_features |
2.3) Metrics | y_train_predict = pipe_model.predict_proba(X_train)
y_test_predict = pipe_model.predict_proba(X_test)
df_metrics_train = mdl.eval_thresh(y_real = y_train, y_proba = y_train_predict[:,1])
df_metrics_test = mdl.eval_thresh(y_real = y_test, y_proba = y_test_predict[:,1])
importlib.reload(mdl)
mdl.plot_metrics(df_metrics_... | _____no_output_____ | MIT | notebooks/modeling.ipynb | brunocvs7/bot_detection_twitter_profile_features |
2.4) Learning Curve | train_sizes, train_scores, validation_scores = learning_curve(estimator = pipe_model,
X = X_train,
y = y_train,
cv = 5,
... | _____no_output_____ | MIT | notebooks/modeling.ipynb | brunocvs7/bot_detection_twitter_profile_features |
2.5) Ordering 2.6) Callibration 3) Saving the Model | with open(os.path.join('..', MODEL_OUTPUT_PATH, MODEL_NAME), 'wb') as f:
cloudpickle.dump(pipe_model, f) | _____no_output_____ | MIT | notebooks/modeling.ipynb | brunocvs7/bot_detection_twitter_profile_features |
Load Data | def mnist_data():
compose = transforms.Compose(
[transforms.ToTensor(),
transforms.Normalize((.5, .5, .5), (.5, .5, .5))
])
out_dir = '{}/dataset'.format(DATA_FOLDER)
return datasets.MNIST(root=out_dir, train=True, transform=compose, download=True)
data = mnist_data()
batch_size = 1... | _____no_output_____ | MIT | Online-Courses/gans/Vanilla GAN PyTorch.ipynb | gopala-kr/ds-notebooks |
Networks | class DiscriminativeNet(torch.nn.Module):
"""
A two hidden-layer discriminative neural network
"""
def __init__(self):
super(DiscriminativeNet, self).__init__()
n_features = 784
n_out = 1
self.hidden0 = nn.Sequential(
nn.Linear(n_features, 1024),
... | _____no_output_____ | MIT | Online-Courses/gans/Vanilla GAN PyTorch.ipynb | gopala-kr/ds-notebooks |
Optimization | # Optimizers
d_optimizer = Adam(discriminator.parameters(), lr=0.0002)
g_optimizer = Adam(generator.parameters(), lr=0.0002)
# Loss function
loss = nn.BCELoss()
# Number of steps to apply to the discriminator
d_steps = 1 # In Goodfellow et. al 2014 this variable is assigned to 1
# Number of epochs
num_epochs = 200 | _____no_output_____ | MIT | Online-Courses/gans/Vanilla GAN PyTorch.ipynb | gopala-kr/ds-notebooks |
Training | def real_data_target(size):
'''
Tensor containing ones, with shape = size
'''
data = Variable(torch.ones(size, 1))
if torch.cuda.is_available(): return data.cuda()
return data
def fake_data_target(size):
'''
Tensor containing zeros, with shape = size
'''
data = Variable(torch.ze... | _____no_output_____ | MIT | Online-Courses/gans/Vanilla GAN PyTorch.ipynb | gopala-kr/ds-notebooks |
Generate Samples for Testing | num_test_samples = 16
test_noise = noise(num_test_samples) | _____no_output_____ | MIT | Online-Courses/gans/Vanilla GAN PyTorch.ipynb | gopala-kr/ds-notebooks |
Start training | logger = Logger(model_name='VGAN', data_name='MNIST')
for epoch in range(num_epochs):
for n_batch, (real_batch,_) in enumerate(data_loader):
# 1. Train Discriminator
real_data = Variable(images_to_vectors(real_batch))
if torch.cuda.is_available(): real_data = real_data.cuda()
# Gen... | _____no_output_____ | MIT | Online-Courses/gans/Vanilla GAN PyTorch.ipynb | gopala-kr/ds-notebooks |
Correlation MatrixThis notebook shows how to calculate a correlation matrix to explore if there are correlations any pair of columns in a datafram. The correlation coefficient can be Pearson's, Kendall's, or Spearmans. | # import some modules
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import scipy.stats as stats
import seaborn as sns
# read in some data
data = pd.read_csv('corr.csv')
print(data.shape)
data.head(6)
# you can find the correlation coefficients between columns on a data frame using the .corr met... | _____no_output_____ | MIT | notebooks/demos/correlation_matrix.ipynb | prof-groff/evns-462 |
Self-Driving Car Engineer Nanodegree Project: **Finding Lane Lines on the Road** ***In this project, you will use the tools you learned about in the lesson to identify lane lines on the road. You can develop your pipeline on a series of individual images, and later apply the result to a video stream (really just a se... | #importing some useful packages
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
import cv2
%matplotlib inline | _____no_output_____ | MIT | P1.ipynb | Abhishek-Balaji/CarND-LaneLines-P1 |
Read in an Image | #reading in an image
image = mpimg.imread('test_images/solidWhiteRight.jpg')
#printing out some stats and plotting
print('This image is:', type(image), 'with dimensions:', image.shape)
plt.imshow(image) # if you wanted to show a single color channel image called 'gray', for example, call as plt.imshow(gray, cmap='gra... | This image is: <class 'numpy.ndarray'> with dimensions: (540, 960, 3)
| MIT | P1.ipynb | Abhishek-Balaji/CarND-LaneLines-P1 |
Ideas for Lane Detection Pipeline **Some OpenCV functions (beyond those introduced in the lesson) that might be useful for this project are:**`cv2.inRange()` for color selection `cv2.fillPoly()` for regions selection `cv2.line()` to draw lines on an image given endpoints `cv2.addWeighted()` to coadd / overlay two i... | import math
def grayscale(img):
"""Applies the Grayscale transform
This will return an image with only one color channel
but NOTE: to see the returned image as grayscale
(assuming your grayscaled image is called 'gray')
you should call plt.imshow(gray, cmap='gray')"""
return cv2.cvtColor(img, c... | _____no_output_____ | MIT | P1.ipynb | Abhishek-Balaji/CarND-LaneLines-P1 |
Test ImagesBuild your pipeline to work on the images in the directory "test_images" **You should make sure your pipeline works well on these images before you try the videos.** | import os
os.listdir("test_images/") | _____no_output_____ | MIT | P1.ipynb | Abhishek-Balaji/CarND-LaneLines-P1 |
Build a Lane Finding Pipeline Build the pipeline and run your solution on all test_images. Make copies into the `test_images_output` directory, and you can use the images in your writeup report.Try tuning the various parameters, especially the low and high Canny thresholds as well as the Hough lines parameters. | def draw(image):
gray=grayscale(image)
blur=gaussian_blur(gray,5)
edge=canny(blur,50,150)
imshape=image.shape
vertices = np.array([[(0, imshape[0]),((43/96) * imshape[1], (33/54) * imshape[0]), ((54/96) * imshape[1], (33/54) * imshape[0]), (imshape[1],imshape[0])]], dtype=np.int32)
masked_edges ... | _____no_output_____ | MIT | P1.ipynb | Abhishek-Balaji/CarND-LaneLines-P1 |
Test on VideosYou know what's cooler than drawing lanes over images? Drawing lanes over video!We can test our solution on two provided videos:`solidWhiteRight.mp4``solidYellowLeft.mp4`**Note: if you get an import error when you run the next cell, try changing your kernel (select the Kernel menu above --> Change Kernel... | # Import everything needed to edit/save/watch video clips
from moviepy.editor import VideoFileClip
from IPython.display import HTML
def process_image(image):
# NOTE: The output you return should be a color image (3 channel) for processing video below
# TODO: put your pipeline here,
# you should return the f... | _____no_output_____ | MIT | P1.ipynb | Abhishek-Balaji/CarND-LaneLines-P1 |
Let's try the one with the solid white lane on the right first ... | white_output = 'test_videos_output/solidWhiteRight.mp4'
## To speed up the testing process you may want to try your pipeline on a shorter subclip of the video
## To do so add .subclip(start_second,end_second) to the end of the line below
## Where start_second and end_second are integer values representing the start and... | t: 1%|▏ | 3/221 [00:00<00:09, 22.45it/s, now=None] | MIT | P1.ipynb | Abhishek-Balaji/CarND-LaneLines-P1 |
Play the video inline, or if you prefer find the video in your filesystem (should be in the same directory) and play it in your video player of choice. | HTML("""
<video width="960" height="540" controls>
<source src="{0}">
</video>
""".format(white_output)) | _____no_output_____ | MIT | P1.ipynb | Abhishek-Balaji/CarND-LaneLines-P1 |
Improve the draw_lines() function**At this point, if you were successful with making the pipeline and tuning parameters, you probably have the Hough line segments drawn onto the road, but what about identifying the full extent of the lane and marking it clearly as in the example video (P1_example.mp4)? Think about de... | yellow_output = 'test_videos_output/solidYellowLeft.mp4'
## To speed up the testing process you may want to try your pipeline on a shorter subclip of the video
## To do so add .subclip(start_second,end_second) to the end of the line below
## Where start_second and end_second are integer values representing the start an... | _____no_output_____ | MIT | P1.ipynb | Abhishek-Balaji/CarND-LaneLines-P1 |
Writeup and SubmissionIf you're satisfied with your video outputs, it's time to make the report writeup in a pdf or markdown file. Once you have this Ipython notebook ready along with the writeup, it's time to submit for review! Here is a [link](https://github.com/udacity/CarND-LaneLines-P1/blob/master/writeup_templat... | challenge_output = 'test_videos_output/challenge.mp4'
## To speed up the testing process you may want to try your pipeline on a shorter subclip of the video
## To do so add .subclip(start_second,end_second) to the end of the line below
## Where start_second and end_second are integer values representing the start and e... | _____no_output_____ | MIT | P1.ipynb | Abhishek-Balaji/CarND-LaneLines-P1 |
Read the data | X, y = load_svmlight_file('data/heart')
X = X.toarray().astype(np.float32)
y[y==-1] = 0
features = [f'f{i+1}' for i in range(X.shape[1])]
df = pd.DataFrame(X, columns=features)
df.head() | _____no_output_____ | BSD-3-Clause | examples/bias/Bias.ipynb | dabrze/similarity_forest |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.