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 |
|---|---|---|---|---|---|
Делаем симлинк скрытой папки с временными файлами и настройками ботана случай если придется что-то редактировать или вынимать оттуда наживую, иначе ее не будет видно в браузере файлов слева | !ln -s ~/.ScreamingFrogSEOSpider ~/ScreamingFrogSEOSpider | _____no_output_____ | MIT | Running_screamingfrog_SEO_spider_in_Colab_notebook.ipynb | danzerzine/seospider-colab |
Даем команду боту в headless режиме прописываем все нужные флаги для экспорта, настроек, отчетов, выгрузок и так далее | #@title Crawl settings { vertical-output: true }
url_start = "" #@param {type:"string"}
use_gcs = "" #@param ["", "--use-google-search-console \"account \""] {allow-input: true}
config_path = "" #@param {type:"string"}
output_folder = "" #@param {type:"string"}
!screamingfrogseospider --crawl "$url_start" $use_gcs --h... | _____no_output_____ | MIT | Running_screamingfrog_SEO_spider_in_Colab_notebook.ipynb | danzerzine/seospider-colab |
---- 베이즈 정리 - 데이터라는 조건이 주어졌을 때 조건부 확률을 구하는 공식 - $P(A|B) = \frac{P(B|A)P(A)}{P(B)}$ ---- - $P(A|B)$ : 사후확률(posterior). 사건 B가 발생한 후 갱신된 사건 A의 확률 - $P(A)$ : 사전확률 (prior). 사건 B가 발생하기 전에 가지고 있던 사건 A의 확률 - $P(B|A)$ : 가능도(likelihood). 사건 A가 발생한 경우 사건 B의 확률 - $P(B)$ : 정규화상수(normalizing constant) 또는 증거(evidence). 확률의... | round((0.99*0.002) / (0.99*0.002+0.05)*(1-0.002), 3) | _____no_output_____ | MIT | MATH/18_Bayesian_rule.ipynb | CATERINA-SEUL/Data-Science-School |
---- TabularCPD(variable, variable_card, value, evidence=None, evidence_card=None) - BayesianModel : 베이즈정리에 적용 - TabularCPD : 조건부확률을 구현 ---- - variable : 확률 변수의 이름 문자열 - variable_card : 확률변수가 가질 수 있는 경우의 수 - value : 조건부확률 배열. 하나의 열(column)이 동일 조건을 뜻하므로, 하나의 열의 확률 합은 1이어야 한다. - evidence : 조건이 되는 확률변수의 이름 문자열 리스트 - evid... | from pgmpy.factors.discrete import TabularCPD
cpd_X = TabularCPD('X', 2, [[1-0.002, 0.002]])
print(cpd_X) | +------+-------+
| X(0) | 0.998 |
+------+-------+
| X(1) | 0.002 |
+------+-------+
| MIT | MATH/18_Bayesian_rule.ipynb | CATERINA-SEUL/Data-Science-School |
양성반응이 나올 확률 $P(S) = P(Y = 1)$, 음성 반응이 나올 확률 $P(S^\complement) = P(Y=0)$ - 확률 변수 $Y$ 에 확률을 베이즈 모형에 넣을 때는 $P(Y|X)$의 형태로 넣어야한다. - evidence : 조건이 되는 확률변수가 누구냐 ! - evidence_card : 몇가지 조건이 존재하는가 ! | cpd_Y_on_X = TabularCPD('Y', 2, np.array(
[[0.95, 0.01], [0.05, 0.99]]), evidence=['X'], evidence_card=[2])
print(cpd_Y_on_X)
from pgmpy.models import BayesianModel | _____no_output_____ | MIT | MATH/18_Bayesian_rule.ipynb | CATERINA-SEUL/Data-Science-School |
BayesianModel(variables) - variables : 확률모형이 포함하는 확률변수 이름 문자열 리스트 - add_cpds() : 조건부확률 추가 - check_model() : 모형이 정상적인지 확인. True이면 정상모델 | model = BayesianModel([('X','Y')])
model.add_cpds(cpd_X,cpd_Y_on_X)
model.check_model()
from pgmpy.inference import VariableElimination | _____no_output_____ | MIT | MATH/18_Bayesian_rule.ipynb | CATERINA-SEUL/Data-Science-School |
VariableElimination (변수제거법) 을 사용한 추정을 제공 query(variables, evidences) - query() 를 통해 사후확률 계산---- - variables : 사후 확률을 계산할 확률변수의 이름 리스트 - evidences : 조건이 되는 확률변수의 값을 나타내는 딕셔너리 | inference = VariableElimination(model)
posterior = inference.query(['X'], evidence={'Y':1})
print(posterior) | +------+----------+
| X | phi(X) |
+======+==========+
| X(0) | 0.9618 |
+------+----------+
| X(1) | 0.0382 |
+------+----------+
| MIT | MATH/18_Bayesian_rule.ipynb | CATERINA-SEUL/Data-Science-School |
Machine Learning OverviewMachine learning is the ability of computers to take a dataset of objects and learn patterns about them. This dataset is structured as a table, where each row is a vector representing some object by encoding their properties as the values of the vector. The columns represent **features** - pro... | import pandas as pd
iris_dataset = pd.read_csv("../data/iris.csv")
iris_dataset.head() | _____no_output_____ | MIT | notebooks/ML.ipynb | samirelanduk/numberwang |
Here a dataset has been loaded from CSV into a pandas dataframe. Each row represents a flower, on which four measurements have been taken, and each flower belongs to one of three classes. A supervised learning model would take this dataset of 150 flowers and train such that any other flower for which the relevant measu... | simple_iris = iris_dataset.iloc[0:100, [0, 2, 4]]
simple_iris.head()
simple_iris.tail() | _____no_output_____ | MIT | notebooks/ML.ipynb | samirelanduk/numberwang |
Because this is just two dimensions, it can be easily visualised as a scatter plot. | import sys
sys.path.append("..")
import numerus.learning as ml
ml.plot_dataset(simple_iris) | _____no_output_____ | MIT | notebooks/ML.ipynb | samirelanduk/numberwang |
The data can be seen to be **linearly separable** - there is a line that can be drawn between them that would separate them perfectly.One of the simplest classifiers for supervised learning is the perceptron. Perceptrons have a weights vector which they dot with an input vector to get some level of activation. If the a... | train_simple_iris, test_simple_iris = ml.split_data(simple_iris)
ml.plot_dataset(train_simple_iris, title="Training Data")
perceptron = ml.Perceptron(train_simple_iris)
print(perceptron) | _____no_output_____ | MIT | notebooks/ML.ipynb | samirelanduk/numberwang |
_*Using Qiskit Aqua for clique problems*_This Qiskit Aqua Optimization notebook demonstrates how to use the VQE quantum algorithm to compute the clique of a given graph. The problem is defined as follows. A clique in a graph $G$ is a complete subgraph of $G$. That is, it is a subset $K$ of the vertices such that every... | import numpy as np
from qiskit import Aer
from qiskit_aqua import run_algorithm
from qiskit_aqua.input import EnergyInput
from qiskit_aqua.translators.ising import clique
from qiskit_aqua.algorithms import ExactEigensolver | _____no_output_____ | Apache-2.0 | community/aqua/optimization/clique.ipynb | Chibikuri/qiskit-tutorials |
first, let us have a look at the graph, which is in the adjacent matrix form. | K = 3 # K means the size of the clique
np.random.seed(100)
num_nodes = 5
w = clique.random_graph(num_nodes, edge_prob=0.8, weight_range=10)
print(w) | [[ 0. 4. 5. 3. -5.]
[ 4. 0. 7. 0. 6.]
[ 5. 7. 0. -4. 0.]
[ 3. 0. -4. 0. 8.]
[-5. 6. 0. 8. 0.]]
| Apache-2.0 | community/aqua/optimization/clique.ipynb | Chibikuri/qiskit-tutorials |
Let us try a brute-force method. Basically, we exhaustively try all the binary assignments. In each binary assignment, the entry of a vertex is either 0 (meaning the vertex is not in the clique) or 1 (meaning the vertex is in the clique). We print the binary assignment that satisfies the definition of the clique (Note ... | def brute_force():
# brute-force way: try every possible assignment!
def bitfield(n, L):
result = np.binary_repr(n, L)
return [int(digit) for digit in result]
L = num_nodes # length of the bitstring that represents the assignment
max = 2**L
has_sol = False
for i in range(max):
... | solution is [1, 0, 0, 1, 1]
| Apache-2.0 | community/aqua/optimization/clique.ipynb | Chibikuri/qiskit-tutorials |
Part I: run the optimization in the non-programming way | qubit_op, offset = clique.get_clique_qubitops(w, K)
algo_input = EnergyInput(qubit_op)
params = {
'problem': {'name': 'ising'},
'algorithm': {'name': 'ExactEigensolver'}
}
result = run_algorithm(params, algo_input)
x = clique.sample_most_likely(len(w), result['eigvecs'][0])
ising_sol = clique.get_graph_solution... | solution is [1. 0. 1. 1. 0.]
| Apache-2.0 | community/aqua/optimization/clique.ipynb | Chibikuri/qiskit-tutorials |
Part II: run the optimization in the programming way |
algo = ExactEigensolver(algo_input.qubit_op, k=1, aux_operators=[])
result = algo.run()
x = clique.sample_most_likely(len(w), result['eigvecs'][0])
ising_sol = clique.get_graph_solution(x)
if clique.satisfy_or_not(ising_sol, w, K):
print("solution is", ising_sol)
else:
print("no solution found for K=", K) | solution is [1. 0. 1. 1. 0.]
| Apache-2.0 | community/aqua/optimization/clique.ipynb | Chibikuri/qiskit-tutorials |
Part III: run the optimization with the VQE | algorithm_cfg = {
'name': 'VQE',
'operator_mode': 'matrix'
}
optimizer_cfg = {
'name': 'COBYLA'
}
var_form_cfg = {
'name': 'RY',
'depth': 5,
'entanglement': 'linear'
}
params = {
'problem': {'name': 'ising', 'random_seed': 10598},
'algorithm': algorithm_cfg,
'optimizer': optimizer... | solution is [1. 0. 1. 1. 0.]
| Apache-2.0 | community/aqua/optimization/clique.ipynb | Chibikuri/qiskit-tutorials |
Test shifting template experiments | %load_ext autoreload
%autoreload 2
import os
import sys
import pandas as pd
import numpy as np
import random
import umap
import glob
import pickle
import tensorflow as tf
from keras.models import load_model
from sklearn.decomposition import PCA
from plotnine import (ggplot,
labs,
... | _____no_output_____ | BSD-3-Clause | human_tests/Human_template_simulation.ipynb | ben-heil/ponyo |
Setup directories | utils.setup_dir(config_filename) | _____no_output_____ | BSD-3-Clause | human_tests/Human_template_simulation.ipynb | ben-heil/ponyo |
Pre-process data | train_vae_modules.normalize_expression_data(base_dir,
config_filename,
rpkm_data_filename,
normalized_data_filename) | input: dataset contains 50 samples and 5000 genes
Output: normalized dataset contains 50 samples and 5000 genes
| BSD-3-Clause | human_tests/Human_template_simulation.ipynb | ben-heil/ponyo |
Train VAE | # Directory containing log information from VAE training
vae_log_dir = os.path.join(
base_dir,
dataset_name,
"logs",
NN_architecture)
# Train VAE
train_vae_modules.train_vae(config_filename,
normalized_data_filename) | input dataset contains 50 samples and 5000 genes
WARNING:tensorflow:From /home/alexandra/anaconda3/envs/test_ponyo/lib/python3.7/site-packages/tensorflow_core/python/ops/resource_variable_ops.py:1630: calling BaseResourceVariable.__init__ (from tensorflow.python.ops.resource_variable_ops) with constraint is deprecated ... | BSD-3-Clause | human_tests/Human_template_simulation.ipynb | ben-heil/ponyo |
Shift template experiment | #tmp result dir
tmp = os.path.join(local_dir, "pseudo_experiment")
os.makedirs(tmp, exist_ok=True)
# Load pickled file
scaler = pickle.load(open(scaler_filename, "rb"))
# Run simulation
normalized_data = normalized_data = pd.read_csv(
normalized_data_filename, header=0, sep="\t", index_col=0
)
for run in r... | _____no_output_____ | BSD-3-Clause | human_tests/Human_template_simulation.ipynb | ben-heil/ponyo |
Visualize latent transform compendium | # Load VAE models
model_encoder_filename = glob.glob(os.path.join(
NN_dir,
"*_encoder_model.h5"))[0]
weights_encoder_filename = glob.glob(os.path.join(
NN_dir,
"*_encoder_weights.h5"))[0]
model_decoder_filename = glob.glob(os.path.join(
NN_dir,
"*_decoder_model.h5"))[0]
weights_decode... | _____no_output_____ | BSD-3-Clause | human_tests/Human_template_simulation.ipynb | ben-heil/ponyo |
选择 布尔类型、数值和表达式- 注意:比较运算符的相等是两个等到,一个等到代表赋值- 在Python中可以用整型0来代表False,其他数字来代表True- 后面还会讲到 is 在判断语句中的用发 | 1== true
while 1:
print('hahaha') | _____no_output_____ | Apache-2.0 | 9.12.ipynb | ljmzyl/Work |
字符串的比较使用ASCII值 | 'a'>True
0<10>100
num=eval(input('>>'))
if num>=90:
print('A')
elif 80<=num<90:
print('B')
else :
print('C') | >>80
B
| Apache-2.0 | 9.12.ipynb | ljmzyl/Work |
Markdown - https://github.com/younghz/Markdown EP:- - 输入一个数字,判断其实奇数还是偶数 产生随机数字- 函数random.randint(a,b) 可以用来产生一个a和b之间且包括a和b的随机整数 | import random
a=random.randint(1,5)
print(a)
while True:
num=eval(input('>>'))
if num == a:
print('Success')
break
elif num>a:
print('太大了')
elif num<a:
print('太小了') | 2
>>5
太大了
>>2
Success
| Apache-2.0 | 9.12.ipynb | ljmzyl/Work |
其他random方法- random.random 返回0.0到1.0之间前闭后开区间的随机浮点- random.randrange(a,b) 前闭后开 EP:- 产生两个随机整数number1和number2,然后显示给用户,使用户输入数字的和,并判定其是否正确- 进阶:写一个随机序号点名程序 | import random
a=random.randint(1,5)
b=random.randint(2,6)
print(a,b)
# num=eval(input('>>'))
# if num==a+b:
# print('Success')
# else :
# print('失败')
num=a+b
while 1:
input('>>')
if input == num:
print('Success')
break
else :
print('失败') | _____no_output_____ | Apache-2.0 | 9.12.ipynb | ljmzyl/Work |
if语句- 如果条件正确就执行一个单向if语句,亦即当条件为真的时候才执行if内部的语句- Python有很多选择语句:> - 单向if - 双向if-else - 嵌套if - 多向if-elif-else - 注意:当语句含有子语句的时候,那么一定至少要有一个缩进,也就是说如果有儿子存在,那么一定要缩进- 切记不可tab键和space混用,单用tab 或者 space- 当你输出的结果是无论if是否为真时都需要显示时,语句应该与if对齐 | a=eval(input('>>'))
if a<=30:
b=input('>>')
if b!='丑':
c=input('>>')
if c=='高':
d=input('>>')
if d=='是':
print('见')
else:
print('不见')
else :
print('不见')
else :
print('不见')
else:
print('too old... | >>25
>>帅
>>高
>>是
见
| Apache-2.0 | 9.12.ipynb | ljmzyl/Work |
EP:- 用户输入一个数字,判断其实奇数还是偶数- 进阶:可以查看下4.5实例研究猜生日 双向if-else 语句- 如果条件为真,那么走if内部语句,否则走else内部语句 EP:- 产生两个随机整数number1和number2,然后显示给用户,使用户输入数字,并判定其是否正确,如果正确打印“you‘re correct”,否则打印正确错误 嵌套if 和多向if-elif-else EP:- 提示用户输入一个年份,然后显示表示这一年的动物- 计算身体质量指数的程序- BMI = 以千克为单位的体重除以以米为单位的身高)
num=a%12
if num==0:
print('猴')
elif num == 1:
print('鸡')
elif num == 2:
print('狗')
elif num == 3:
print('猪')
elif num== 4:
print('鼠')
elif num== 5:
print('牛')
elif num== 6:
print('虎')
elif num== 7:
print('兔')
elif num== 8:
print('龙')
elif num== 9:
print('蛇')
e... | >>60,1.84
17.72211720226843
超轻
| Apache-2.0 | 9.12.ipynb | ljmzyl/Work |
逻辑运算符  | a=[1,2,3,4]
1 not in a | _____no_output_____ | Apache-2.0 | 9.12.ipynb | ljmzyl/Work |
EP:- 判定闰年:一个年份如果能被4整除但不能被100整除,或者能被400整除,那么这个年份就是闰年- 提示用户输入一个年份,并返回是否是闰年- 提示用户输入一个数字,判断其是否为水仙花数 | year=eval(input('>>'))
a=year%4==0
b=year%100!=0
c=year%400==0
if (a or c) and b :
print('闰年')
else :
print('非闰年')
n=eval(input('>>'))
a1=n//100
a2=n//10%10
a3=n%10
s=a1**3+a2**3+a3**3
if s == n:
print('是水仙花数')
else :
print('结束') | >>154
结束
| Apache-2.0 | 9.12.ipynb | ljmzyl/Work |
实例研究:彩票 | import random
a1=random.randint(0,9)
a2=random.randint(0,9)
print(a1,a2)
a=str(a1)+str(a2)
num=input('>>')
if num==a:
print('一等奖')
elif (num[0]==a[1] and (num[1]== a[0])):
print('二等奖')
elif ((num[0]==a[0]) or (num[1]==a[0]) or (num[0]==a[1]) or (num[1]==a[1])):
print('三等奖')
else :
('未中奖') | 8 4
>>48
二等奖
| Apache-2.0 | 9.12.ipynb | ljmzyl/Work |
Homework- 1 | import math
a,b,c=eval(input('>>'))
pan=b**2-4*a*c
r1=((-b)+math.sqrt(pan))/(2*a)
r2=((-b)-math.sqrt(pan))/(2*a)
if pan>0:
print(r1,r2)
elif pan==0:
print(r1)
else :
print('The equation has no real roots') | >>1,3,1
-0.3819660112501051 -2.618033988749895
| Apache-2.0 | 9.12.ipynb | ljmzyl/Work |
- 2 | import random
a1=random.randint(0,99)
a2=random.randint(0,99)
print(a1,a2)
num=eval(input('>>'))
number=a1+a2
if num == number:
print('True')
else :
print('False') | 93 42
>>12
False
| Apache-2.0 | 9.12.ipynb | ljmzyl/Work |
- 3 | day = eval(input('今天是哪一天(星期天是0,星期一是1,。。。,星期六是6):'))
days = eval(input('今天之后到未来某天的天数:'))
n = day + days
if day==0:
a='星期日'
elif day==1:
a='星期一'
elif day==2:
a='星期二'
elif day==3:
a='星期三'
elif day==4:
a='星期四'
elif day==5:
a='星期五'
elif day==6:
a='星期六'
if n%7 ==0:
print('今天是'+str(a)+'并且'+str(... | 今天是哪一天(星期天是0,星期一是1,。。。,星期六是6):1
今天之后到未来某天的天数:3
今天是星期一并且3天之后是星期四
| Apache-2.0 | 9.12.ipynb | ljmzyl/Work |
- 4 | a,b,c = eval(input('输入三个整数:'))
if a>=b and b>=c:
print(c,b,a)
elif a>=b and b<=c and a>=c:
print(b,c,a)
elif b>=a and a>=c :
print(c,a,b)
elif b>=a and a<=c and b>=c:
print(a,c,b)
elif c>=b and b>=a:
print(a,b,c)
elif c>=b and b<=a and c>=a:
print(b,a,c) | 输入三个整数:2,1,3
1 2 3
| Apache-2.0 | 9.12.ipynb | ljmzyl/Work |
- 5 | a1,a2=eval(input('输入第一种重量和价钱:'))
b1,b2=eval(input('输入第一种重量和价钱:'))
num1=a2/a1
num2=b2/b1
if num1>num2:
print('购买第二种更加合适')
else :
print('购买第一种更合适') | _____no_output_____ | Apache-2.0 | 9.12.ipynb | ljmzyl/Work |
- 6 | m,year=eval(input('输入月份和年'))
a=year%4==0
b=year%100!=0
c=year%400==0
r=[1,3,5,7,8,10,12]
if (a or c) and b and m==2:
print(str(year)+'年'+str(m)+'月有29天')
elif ((m==1) or (m==3) or (m==5) or (m==7) or (m==8) or (m==10) or (m==12)):
print(str(year)+'年'+str(m)+'月有31天')
elif ((m==4) or (m==6) or (m==9) or (m==11)):
... | _____no_output_____ | Apache-2.0 | 9.12.ipynb | ljmzyl/Work |
- 7 | import random
a=random.randint(0,1)
print(a)
num=eval(input('>>'))
if a==num:
print('正确')
else :
print('错误') | 0
>>1
错误
| Apache-2.0 | 9.12.ipynb | ljmzyl/Work |
- 8 | a=eval(input('输入1,2或0:'))
import random
d=random.randint(0,3)
if d==a:
print('平局')
elif a==0 and d==1:
print('你输了')
elif a==0 and d==2:
print('你赢了')
elif a==1 and d==0:
print('你赢了')
elif a==1 and d==2:
print('你输了')
elif a==2 and d==1:
print('你赢了')
elif a==2 and d==0:
print('你输了') | _____no_output_____ | Apache-2.0 | 9.12.ipynb | ljmzyl/Work |
- 9 | y = eval(input('请输入年份:'))
m = eval(input('请输入月份:'))
q = eval(input('请输入天数:'))
j = y//100//1
k = y%100
if m == 1:
m = 13
elif m == 2:
m = 14
h = (q + (26*(m+1))/10//1+k+k/4//1+j/4//1+5*j)%7
print(round(h)) | _____no_output_____ | Apache-2.0 | 9.12.ipynb | ljmzyl/Work |
- 10 | import random
size=['Ace',2,3,4,5,6,7,8,9,10,'Jack','Queen','King']
A=random.randint(0,len(size)-1)
color=['Diamond','Heart','Spade','Club']
B=random.randint(0,len(color)-1)
print('The card you picked is the ' + str(size[A]) + ' of ' + str(color[B])) | _____no_output_____ | Apache-2.0 | 9.12.ipynb | ljmzyl/Work |
- 11 | x = input('Enter a three-digit integer:')
if x[0] == x[2] :
print(str(x)+'is a palindrome')
else:
print(str(x)+'is not a palindrome') | _____no_output_____ | Apache-2.0 | 9.12.ipynb | ljmzyl/Work |
- 12 | lenght1,lenght2,lenght3, =eval(input('Enter three adges:'))
perimeter = lenght1 + lenght2 + lenght3
if lenght1 + lenght2 > lenght3 and lenght1 + lenght3 > lenght2 and lenght2 + lenght3 > lenght1:
print('The perimeter is',perimeter)
else:
print('The perimeter invalid') | _____no_output_____ | Apache-2.0 | 9.12.ipynb | ljmzyl/Work |
1. Деревья решений для классификации (продолжение)На прошлом занятии мы разобрали идею Деревьев решений:Давайте теперь разберемся **как происходит разделения в каждом узле** то есть как проходит этап **обучения модели**. Есть как минимум две причины в этом разобраться : во-первых это позволит... | def gini_impurity(y_current):
n = y_current.shape[0]
val, count = np.unique(y_current, return_counts=True)
gini = 1 - ((count/n)**2).sum()
return gini
def entropy(y_current):
gini = 1
n = y_current.shape[0]
val, count = np.unique(y_current, return_counts=True)
p = cou... | _____no_output_____ | MIT | seminar-5-dt-rf/5_1_dt_2_draft.ipynb | kurmukovai/iitp-ml-ds |
1.2. Пример работы Решающего дерева **Индекс Джини** и **Информационный критерий** это меры сбалансированности вектора (насколько значения объектов в наборе однородны). Максимальная неоднородность когда объектов разных классов поровну. Максимальная однородность когда в наборе объекты одного класса. Разбивая множество ... | from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier
iris = load_iris()
model = DecisionTreeClassifier()
model = model.fit(iris.data, iris.target)
feature_names = ['sepal length', 'sepal width', 'petal length', 'petal width']
target_names = ['setosa', 'versicolor', 'virginica']
mod... | _____no_output_____ | MIT | seminar-5-dt-rf/5_1_dt_2_draft.ipynb | kurmukovai/iitp-ml-ds |
Цифры. Интерпретируемость | from sklearn.datasets import load_digits
X, y = load_digits(n_class=2, return_X_y=True)
plt.figure(figsize=(12,12))
for i in range(9):
ax = plt.subplot(3,3,i+1)
ax.imshow(X[i].reshape(8,8), cmap='gray')
from sklearn.metrics import accuracy_score
model = DecisionTreeClassifier()
model.fit(X, y)
y_pred = model.p... | _____no_output_____ | MIT | seminar-5-dt-rf/5_1_dt_2_draft.ipynb | kurmukovai/iitp-ml-ds |
2.3. Решающие деревья легко обобщаются на задачу многоклассовой классификации Пример с рукописными цифрами | X, y = load_digits(n_class=10, return_X_y=True)
plt.figure(figsize=(12,12))
for i in range(9):
ax = plt.subplot(3,3,i+1)
ax.imshow(X[i].reshape(8,8), cmap='gray')
ax.set_title(y[i])
ax.set_xticks([])
ax.set_yticks([])
model = DecisionTreeClassifier()
model.fit(X, y)
y_pred = model.predict(X)
print(... | _____no_output_____ | MIT | seminar-5-dt-rf/5_1_dt_2_draft.ipynb | kurmukovai/iitp-ml-ds |
Вопрос: откуда мы получаем feature importance? 2.4. Пример на котором дерево решений строит очень сложную разделяющую кривуюПример взят отсюда https://habr.com/ru/company/ods/blog/322534/slozhnyy-sluchay-dlya-derevev-resheniy .Как мы помним Деревья используют одномерный предикат для разделени множества объектов.Это з... | from sklearn.tree import DecisionTreeClassifier
def form_linearly_separable_data(n=500, x1_min=0, x1_max=30, x2_min=0, x2_max=30):
data, target = [], []
for i in range(n):
x1, x2 = np.random.randint(x1_min, x1_max), np.random.randint(x2_min, x2_max)
if np.abs(x1 - x2) > 0.5:
data.ap... | _____no_output_____ | MIT | seminar-5-dt-rf/5_1_dt_2_draft.ipynb | kurmukovai/iitp-ml-ds |
Давайте посмотрим как данные выглядит в проекции на 1 ось | plt.figure(figsize=(15,5))
ax1 = plt.subplot(1,2,1)
ax1.set_title('Проекция на ось $X_0$')
ax1.hist(X[y==1, 0], alpha=.3);
ax1.hist(X[y==-1, 0], alpha=.6);
ax2 = plt.subplot(1,2,2)
ax2.set_title('Проекция на ось $X_1$')
ax2.hist(X[y==1, 1], alpha=.3);
ax2.hist(X[y==-1, 1], alpha=.6);
def get_grid(data, eps=0.01):
... | _____no_output_____ | MIT | seminar-5-dt-rf/5_1_dt_2_draft.ipynb | kurmukovai/iitp-ml-ds |
Kernel analysis | df = read_ods("./results.ods", "matmul-kernel")
expand_modes(df)
print(df["MODE"].unique())
#############################################
# Disregard the store result for the kernel #
#############################################
df.loc[df["MODE"] == "AD (volatile result)", "MODE"] = "AD"
order = ['DRAM', 'AD', 'AD (... | _____no_output_____ | CC0-1.0 | analysis/matmul-analysis.ipynb | bsc-dom/optanedc-miniapps |
Matmul results analysis | df = read_ods("./results.ods", "matmul-app")
expand_modes(df)
df
for bs in [1000, 7000]:
df.loc[(df.BLOCKSIZE == bs) & (df.MODE == "DRAM"), "ATOM_KERNEL"] = \
kernel_times.loc[(bs, "DRAM"), "TIMING"]
df.loc[(df.BLOCKSIZE == bs) & (df.MODE == "AD (volatile result)"), "ATOM_KERNEL"] = \
kernel_t... | _____no_output_____ | CC0-1.0 | analysis/matmul-analysis.ipynb | bsc-dom/optanedc-miniapps |
Article image generation | sns.set(style="whitegrid")
order = ['DRAM', 'AD (volatile result)', 'AD (store result)', 'AD (in-place FMA)',
'MM', 'DAOS (volatile result)', 'DAOS (store result)']
small = (
((df.BLOCKSIZE == 1000) & (df.MATRIX_SIDE == 42)) |
((df.BLOCKSIZE == 7000) & (df.MATRIX_SIDE == 6))
)
big = (
((df.BLOC... | _____no_output_____ | CC0-1.0 | analysis/matmul-analysis.ipynb | bsc-dom/optanedc-miniapps |
DASHBOARD LINKhttps://public.tableau.com/profile/altaf.lakhi2442!/vizhome/UnbankedExploration/Dashboard1 | import pandas as pd
import seaborn as sns
CPS_df = pd.read_csv("../data/processed/CPS_2009_2017_clean.csv")
ACS_df = pd.read_csv("../data/processed/ACS_2011_2017_clean.csv")
NFCS_df = pd.read_csv("../data/processed/NFCS_2009_2018_clean.csv")
frames = [CPS_df, ACS_df, NFCS_df]
#declaring STATE list
STATES = ["Alabama","... | _____no_output_____ | MIT | notebooks/Dashboard_Data.ipynb | Altaf410/An-Exploration-of-the-Unbanked-in-the-US |
Aggregatting CPS Data | pop_prop = pd.read_csv("../data/interim/population_proportions")
pop_prop.head()
pop_prop = pop_prop[["YEAR", "BUNBANKED", "STATEFIP"]]
pop_prop
state_year_agg = []
for year in pop_prop.YEAR.unique():
holder = pop_prop[pop_prop.YEAR == year]
state_year_agg.append(holder)
#national_agg_sums = [pop_prop[pop... | _____no_output_____ | MIT | notebooks/Dashboard_Data.ipynb | Altaf410/An-Exploration-of-the-Unbanked-in-the-US |
---------------------------------------------------------------------------------------------- Aggregatting ACS Data | #ACS_df = pd.read_csv("../data/processed/ACS_2011_2017_clean")
#ACS_df["STATE"] = ACS_df.STATEFIP.map(STATE)
ACS_df.head()
ACS_df.HHWT
ACS_df = ACS_df.drop(columns = ['Unnamed: 0'])
filtering_columns = ACS_df.columns
filtering_columns = filtering_columns.drop(["STATE", "YEAR", "SAMPLE", "REGION", 'STATEFIP'])
filtering... | _____no_output_____ | MIT | notebooks/Dashboard_Data.ipynb | Altaf410/An-Exploration-of-the-Unbanked-in-the-US |
* HHINCOME = House Hold Income* MARST = Marital Status* OCC2010 = Occupation* CINETHH = Access to Internet* CILAPTOP = Laptop, desktop, or notebook computer* CISMRTPHN = Smartphone* CITABLET = Tablet or other portable wireless computer* CIHAND = Handheld Computer* CIHISPEED = Broadband (high speed) Internet service suc... | ACS_agg = pd.DataFrame()
ACS_agg["STATE"] = ACS_df.STATE
ACS_agg["OCC2010"] = ACS_df.OCC2010
ACS_agg["CINETHH"] = ACS_df.CINETHH
ACS_agg["CILAPTOP"] = ACS_df.CILAPTOP
ACS_agg["CISMRTPHN"] = ACS_df.CISMRTPHN
ACS_agg["CITABLET"] = ACS_df.CITABLET
ACS_agg["CIHAND"] = ACS_df.CIHAND
ACS_agg["CIHISPEED"] = ACS_df.CIHISPEED
A... | _____no_output_____ | MIT | notebooks/Dashboard_Data.ipynb | Altaf410/An-Exploration-of-the-Unbanked-in-the-US |
---------------------------------------------------------------------------------------------- Aggregating NFCS | NFCS_df.head()
NFCS_df.drop("Unnamed: 0", axis=1,inplace=True)
#declaring STATE list
STATES = ["Alabama","Alaska","Arizona","Arkansas","California","Colorado",
"Connecticut","Delaware","District of Columbia", "Florida","Georgia","Hawaii",
"Idaho","Illinois", "Indiana","Iowa","Kansas","Kentucky","Lou... | _____no_output_____ | MIT | notebooks/Dashboard_Data.ipynb | Altaf410/An-Exploration-of-the-Unbanked-in-the-US |
Copyright (c) Microsoft Corporation. All rights reserved.Licensed under the MIT License.  Configuration_**Setting up your Azure Machine Learning services workspace and configuring your notebook... | import azureml.core
print("This notebook was created using version 1.0.74.1 of the Azure ML SDK")
print("You are currently using version", azureml.core.VERSION, "of the Azure ML SDK") | _____no_output_____ | MIT | aml/configuration.ipynb | kawo123/azure-e2e-ml |
Configure your Azure ML workspace Workspace parametersTo use an AML Workspace, you will need to import the Azure ML SDK and supply the following information:* Your subscription id* A resource group name* (optional) The region that will host your workspace* A name for your workspaceYou can get your subscription ID from... | import os
subscription_id = os.getenv("SUBSCRIPTION_ID", default="<my-subscription-id>")
resource_group = os.getenv("RESOURCE_GROUP", default="<my-resource-group>")
workspace_name = os.getenv("WORKSPACE_NAME", default="<my-workspace-name>")
workspace_region = os.getenv("WORKSPACE_REGION", default="eastus2") | _____no_output_____ | MIT | aml/configuration.ipynb | kawo123/azure-e2e-ml |
Access your workspaceThe following cell uses the Azure ML SDK to attempt to load the workspace specified by your parameters. If this cell succeeds, your notebook library will be configured to access the workspace from all notebooks using the `Workspace.from_config()` method. The cell can fail if the specified worksp... | from azureml.core import Workspace
try:
ws = Workspace(subscription_id = subscription_id, resource_group = resource_group, workspace_name = workspace_name)
# write the details of the workspace to a configuration file to the notebook library
ws.write_config()
print("Workspace configuration succeeded. Sk... | _____no_output_____ | MIT | aml/configuration.ipynb | kawo123/azure-e2e-ml |
This notebook was prepared by [Donne Martin](https://github.com/donnemartin). Source and license info is on [GitHub](https://github.com/donnemartin/interactive-coding-challenges). Challenge Notebook Problem: Given an array of (unix_timestamp, num_people, EventType.ENTER or EventType.EXIT), find the busiest period.* [... | from enum import Enum
class Data(object):
def __init__(self, timestamp, num_people, event_type):
self.timestamp = timestamp
self.num_people = num_people
self.event_type = event_type
def __lt__(self, other):
return self.timestamp < other.timestamp
class Period(object):
... | _____no_output_____ | Apache-2.0 | online_judges/busiest_period/busiest_period_challenge.ipynb | benkeesey/interactive-coding-challenges |
Unit Test **The following unit test is expected to fail until you solve the challenge.** | # %load test_find_busiest_period.py
import unittest
class TestSolution(unittest.TestCase):
def test_find_busiest_period(self):
solution = Solution()
self.assertRaises(TypeError, solution.find_busiest_period, None)
self.assertEqual(solution.find_busiest_period([]), None)
data = [
... | _____no_output_____ | Apache-2.0 | online_judges/busiest_period/busiest_period_challenge.ipynb | benkeesey/interactive-coding-challenges |
$ \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]{\my... | #
# your code is here
#
| _____no_output_____ | Apache-2.0 | classical-systems/CS16_Probabilistic_States.ipynb | dev-aditya/QWorld_Summer_School_2021 |
click for our solution Vector representation Suppose that we have a system with 4 distiguishable states: $ s_1 $, $s_2 $, $s_3$, and $s_4$. We expect the system to be in one of them at any moment. By speaking with probabilities, we say that the system is in one of the states with probability 1, and in any other state... | #
# your solution is here
#
| _____no_output_____ | Apache-2.0 | classical-systems/CS16_Probabilistic_States.ipynb | dev-aditya/QWorld_Summer_School_2021 |
click for our solution Task 4 [extra] As given in the hint for Task 3, you may pick your random numbers between 0 and $ 10^k $. For better precision, you may take bigger values of $ k $.Write a function that randomly creates a probabilisitic state of size $ n $ with a precision up to $ k $ digits. Test your function. | #
# your solution is here
#
| _____no_output_____ | Apache-2.0 | classical-systems/CS16_Probabilistic_States.ipynb | dev-aditya/QWorld_Summer_School_2021 |
Sentiment Analysis: Data Gathering 1 (Vader)The original sentiments of domain dataset are unclean, especially for the neutral sentiment. Instead of manually going through and correcting sentiments by hand certain techniques are employed to assist this process. This notebook implements the first data annotation pipelin... | import nltk
nltk.download('vader_lexicon')
nltk.download('punkt')
import re
import pandas as pd
import seaborn as sns; sns.set()
from nltk.sentiment.vader import SentimentIntensityAnalyzer
sns.set(style='white', context='notebook', palette='deep')
from google.colab import drive
drive.mount('/content/drive')
PROJECT_PA... | _____no_output_____ | MIT | notebooks/ma02_data_sa_vader.ipynb | CouchCat/ma-zdash-nlp |
Linear independence | import numpy as np
from sympy.solvers import solve
from sympy import Symbol
x = Symbol('x')
y = Symbol('y')
z = Symbol('z') | _____no_output_____ | MIT | juypter/notebooks/linear-algebra/3_linear_independence.ipynb | JamesMcGuigan/ecosystem-research |
The set of vectors are called linearly independent because each of the vectors in the set {V0, V1, …, Vn−1} cannot be written as a combination of the others in the set. Linear Independent Arrays | A = np.array([1,1,1])
B = np.array([0,1,1])
C = np.array([0,0,1])
Z = np.array([0,0,0])
np.array_equal(
Z,
0*A + 0*B + 0*C
)
solve(x*A + y*B + z*C) | _____no_output_____ | MIT | juypter/notebooks/linear-algebra/3_linear_independence.ipynb | JamesMcGuigan/ecosystem-research |
Linear Dependent Arrays | A = np.array([1,1,1])
B = np.array([0,0,1])
C = np.array([1,1,0])
1*A + -1*B + -1*C
solve(x*A + y*B + z*C)
A = np.array([1,2,3])
B = np.array([1,-4,-4])
C = np.array([3,0,2])
2*A + 1*B + -C
solve(x*A + y*B + z*C) | _____no_output_____ | MIT | juypter/notebooks/linear-algebra/3_linear_independence.ipynb | JamesMcGuigan/ecosystem-research |
Datasets and Neural NetworksThis notebook will step through the process of loading an arbitrary dataset in PyTorch, and creating a simple neural network for regression. DatasetsWe will first work through loading an arbitrary dataset in PyTorch. For this project, we chose the delve abalone dataset. First, download and... | import math
from tqdm import tqdm
import torch
import torch.nn as nn
import torch.optim as optim
import torch.utils.data as data
import torch.nn.functional as F
import pandas as pd
from torch.utils.data import Dataset, DataLoader | _____no_output_____ | MIT | models/dataset_nn/dataset_neural_nets.ipynb | TreeHacks/hackpack-ml |
Pandas is a data manipulation library that works really well with structured data. We can use Pandas DataFrames to load the dataset. | col_names = ['sex', 'length', 'diameter', 'height', 'whole_weight',
'shucked_weight', 'viscera_weight', 'shell_weight', 'rings']
abalone_df = pd.read_csv('../data/Dataset.data', sep=' ', names=col_names)
abalone_df.head(n=3) | _____no_output_____ | MIT | models/dataset_nn/dataset_neural_nets.ipynb | TreeHacks/hackpack-ml |
We define a subclass of PyTorch Dataset for our Abalone dataset. | class AbaloneDataset(data.Dataset):
"""Abalone dataset. Provides quick iteration over rows of data."""
def __init__(self, csv):
"""
Args: csv (string): Path to the Abalone dataset.
"""
self.features = ['sex', 'length', 'diameter', 'height', 'whole_weight',
... | _____no_output_____ | MIT | models/dataset_nn/dataset_neural_nets.ipynb | TreeHacks/hackpack-ml |
Neural NetworksThe task is to predict the age (number of rings) of abalone from physical measurements. We build a simple neural network with one hidden layer to model the regression. | class Net(nn.Module):
def __init__(self, feature_size):
super(Net, self).__init__()
# feature_size input channels (8), 1 output channels
self.fc1 = nn.Linear(feature_size, 4)
self.fc2 = nn.Linear(4, 1)
def forward(self, x):
x = F.relu(self.fc1(x))
x = self.fc2(x... | _____no_output_____ | MIT | models/dataset_nn/dataset_neural_nets.ipynb | TreeHacks/hackpack-ml |
We instantiate an Abalone dataset instance and create DataLoaders for train and test sets. | dataset = AbaloneDataset('../data/Dataset.data')
train_split, test_split = math.floor(len(dataset) * 0.8), math.ceil(len(dataset) * 0.2)
trainset = [dataset[i] for i in range(train_split)]
testset = [dataset[train_split + j] for j in range(test_split)]
batch_sz = len(trainset) # Compact data allows for big batch size
... | _____no_output_____ | MIT | models/dataset_nn/dataset_neural_nets.ipynb | TreeHacks/hackpack-ml |
Now, we can initialize our network and define train and test functions | net = Net(len(dataset.features))
loss_fn = nn.MSELoss()
optimizer = optim.Adam(net.parameters(), lr=0.1)
device = 'cuda' if torch.cuda.is_available() else 'cpu'
gpu_ids = [0] # On Colab, we have access to one GPU. Change this value as you see fit
def train(epoch):
"""
Trains our net on data from the trainloade... | _____no_output_____ | MIT | models/dataset_nn/dataset_neural_nets.ipynb | TreeHacks/hackpack-ml |
Now that everything is prepared, it's time to train! | test_freq = 5 # Frequency to run model on validation data
for epoch in range(0, 200):
train(epoch)
if epoch % test_freq == 0:
test(epoch) | _____no_output_____ | MIT | models/dataset_nn/dataset_neural_nets.ipynb | TreeHacks/hackpack-ml |
We use the network's eval mode to do a sample prediction to see how well it does. | net.eval()
sample = testset[0]
predicted_age = net(sample[0])
true_age = sample[1]
print(f'Input features: {sample[0]}')
print(f'Predicted age: {predicted_age.item()}, True age: {true_age[0]}') | _____no_output_____ | MIT | models/dataset_nn/dataset_neural_nets.ipynb | TreeHacks/hackpack-ml |
Optimization with equality constraints | import math
import numpy as np
from scipy import optimize as opt | _____no_output_____ | MIT | 00-pre-requisitos/2-math/otimização-II.ipynb | sn3fru/datascience_course |
maximize $.4\,\log(x_1)+.6\,\log(x_2)$ s.t. $x_1+3\,x_2=50$. | I = 50
p = np.array([1, 3])
U = lambda x: (.4*math.log(x[0])+.6*math.log(x[1]))
x0 = (I/len(p))/np.array(p)
budget = ({'type': 'eq', 'fun': lambda x: I-np.sum(np.multiply(x, p))})
opt.minimize(lambda x: -U(x), x0, method='SLSQP', constraints=budget, tol=1e-08,
options={'disp': True, 'ftol': 1e-0... | _____no_output_____ | MIT | 00-pre-requisitos/2-math/otimização-II.ipynb | sn3fru/datascience_course |
Cost function | # Production function
F = lambda x: (x[0]**.8)*(x[1]**.2)
w = np.array([5, 4])
y = 1
constraint = ({'type': 'eq', 'fun': lambda x: y-F(x)})
x0 = np.array([.5, .5])
cost = opt.minimize(lambda x: w@x, x0, method='SLSQP', constraints=constraint, tol=1e-08,
options={'disp': True, 'ftol': 1e-08})
F(c... | _____no_output_____ | MIT | 00-pre-requisitos/2-math/otimização-II.ipynb | sn3fru/datascience_course |
Exercise | a = 2
u = lambda c: -np.exp(-a*c)
R = 2
Z2 = np.array([.72, .92, 1.12, 1.32])
Z3 = np.array([.86, .96, 1.06, 1.16])
def U(x):
states = len(Z2)*len(Z3)
U = u(x[0])
for z2 in Z2:
for z3 in Z3:
U += (1/states)*u(x[1]*R+x[2]*z2+x[3]*z3)
return U
p = np.array([1, 1, .5, .5])
I =... | _____no_output_____ | MIT | 00-pre-requisitos/2-math/otimização-II.ipynb | sn3fru/datascience_course |
Optimization with inequality constraints | f = lambda x: -x[0]**3+x[1]**2-2*x[0]*(x[2]**2)
constraints =({'type': 'eq', 'fun': lambda x: 2*x[0]+x[1]**2+x[2]-5},
{'type': 'ineq', 'fun': lambda x: 5*x[0]**2-x[1]**2-x[2]-2})
constraints =({'type': 'eq', 'fun': lambda x: x[0]**3-x[1]})
x0 = np.array([.5, .5, 2])
opt.minimize(f, x0, method='SLSQP', co... | Optimization terminated successfully. (Exit mode 0)
Current function value: -19.000000000000256
Iterations: 11
Function evaluations: 56
Gradient evaluations: 11
| MIT | 00-pre-requisitos/2-math/otimização-II.ipynb | sn3fru/datascience_course |
Params: | aggregate_by_state = False
outcome_type = 'cases' | _____no_output_____ | MIT | modeling/basic_model_framework.ipynb | rahul263-stack/covid19-severity-prediction |
Basic Data Visualization | # Just something to quickly summarize the number of cases and distributions each day
# 'deaths' and 'cases' contain the time-series of the outbreak
df = load_data.load_county_level(data_dir = '../data/')
df = df.sort_values('#Deaths_3/30/2020', ascending=False)
# outcome_cases = load_data.outcome_cases # most recent da... | _____no_output_____ | MIT | modeling/basic_model_framework.ipynb | rahul263-stack/covid19-severity-prediction |
Clean data | # Remove counties with zero cases
max_cases = [max(v) for v in df['cases']]
df['max_cases'] = max_cases
max_deaths = [max(v) for v in df['deaths']]
df['max_deaths'] = max_deaths
df = df[df['max_cases'] > 0]
| _____no_output_____ | MIT | modeling/basic_model_framework.ipynb | rahul263-stack/covid19-severity-prediction |
Predict data from model: | method_keys = []
# clear predictions
for m in method_keys:
del df[m]
# target_day = np.array([1])
# # Trains model on train_df and produces predictions for the final day for test_df and writes prediction
# # to a new column for test_df
# # fit_and_predict(df, method='exponential', outcome=outcome_type, mode='... | _____no_output_____ | MIT | modeling/basic_model_framework.ipynb | rahul263-stack/covid19-severity-prediction |
Ensemble predictions | exponential = {'model_type':'exponential'}
shared_exponential = {'model_type':'shared_exponential'}
demographics = {'model_type':'shared_exponential', 'demographic_vars':very_important_vars}
linear = {'model_type':'linear'}
# import fit_and_predict
# for d in [1, 2, 3]:
# df = fit_and_predict.fit_and_predict_ensemb... | _____no_output_____ | MIT | modeling/basic_model_framework.ipynb | rahul263-stack/covid19-severity-prediction |
Evaluate and visualize models Compute MSE and log MSE on relevant cases | # TODO: add average rank as metric
# Computes the mse in log space and non-log space for all columns
def l1(arr1,arr2,norm=True):
"""
arr2 ground truth
arr1 predictions
"""
if norm:
sum_percent_dif = 0
for i in range(len(arr1)):
sum_percent_dif += np.abs(arr2[i]-arr1[i])/... | Raw l1 for predicted_cases_ensemble_1
15.702192279696032
Raw l1 for predicted_cases_ensemble_3
56.27341453693248
| MIT | modeling/basic_model_framework.ipynb | rahul263-stack/covid19-severity-prediction |
Plot residuals | # TODO: Create bounds automatically, create a plot function and call it instead of copying code, figure out way
# to plot more than two things at once cleanly
# Creates residual plots log scaled and raw
# We only look at cases with number of deaths greater than 5
def method_name_to_pretty_name(key):
# TODO: hacky,... | _____no_output_____ | MIT | modeling/basic_model_framework.ipynb | rahul263-stack/covid19-severity-prediction |
Graph Visualizations | # Here we visualize predictions on a per county level.
# The blue lines are the true number of deaths, and the dots are our predictions for each model for those days.
def plot_prediction(row):
"""
Plots model predictions vs actual
row: dataframe row
window: autoregressive window size
"""
gold_ke... | _____no_output_____ | MIT | modeling/basic_model_framework.ipynb | rahul263-stack/covid19-severity-prediction |
0) Carregamento as bibliotecas | # Mostra múltiplos resultados em uma única saída:
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
from IPython.display import Math
import pandas as pd
import numpy as np
import geopandas as gpd
import os
import pysal
from pyproj import CRS
from shapely.geometry... | C:\Users\Jorge\Anaconda3\lib\site-packages\pysal\explore\segregation\network\network.py:16: UserWarning: You need pandana and urbanaccess to work with segregation's network module
You can install them with `pip install urbanaccess pandana` or `conda install -c udst pandana urbanaccess`
"You need pandana and urbanacc... | MIT | NT02-Bahia (NRS Sul).ipynb | pedreirajr/GeoCombatCOVID19 |
1) Leitura dos Banco de Dados: **(a) Dados SIH 2019:** | df = pd.read_csv("NT02 - Bahia/SIH/sih_17-19.csv")
#pickle.dump(df, open('sih_2019', 'wb'))
#df = pickle.load(open('sih_2019','rb'))
df.info()
df.head()
df.rename(columns={'MES_CMPT':'Mes','DT_INTER':'DT_Inter','DT_SAIDA':'DT_Saida','MUNIC_RES':'Cod_Municipio_Res',
'MUNIC_MOV':'Cod_Municipio','DIAG_P... | _____no_output_____ | MIT | NT02-Bahia (NRS Sul).ipynb | pedreirajr/GeoCombatCOVID19 |
* **Formatação para datas:** | from datetime import datetime
df['DT_Inter'] = df['DT_Inter'].apply(lambda x: pd.to_datetime(x, format = '%Y%m%d'))
df['DT_Saida'] = df['DT_Saida'].apply(lambda x: pd.to_datetime(x, format = '%Y%m%d'))
pickle.dump(df, open('sih', 'wb'))
df = pickle.load(open('sih','rb'))
df2 = df.drop_duplicates(subset ="N_AIH",keep = ... | _____no_output_____ | MIT | NT02-Bahia (NRS Sul).ipynb | pedreirajr/GeoCombatCOVID19 |
**(b) Shape municípios:** | mun = gpd.read_file("NT02 - Bahia/mun_br.shp")
mun = mun.to_crs(CRS("WGS84"));
mun.crs
mun.info()
mun.head()
mun.plot();
plt.show();
mun_ba = mun[mun['GEOCODIGO'].str.startswith('29')].copy()
mun_ba.head()
mun_ba[mun_ba['GEOCODIGO'].str.startswith('290160')]
mun_ba[mun_ba['NOME']=='Sítio do Quinto']
mun_ba[mun_ba['NOME... | _____no_output_____ | MIT | NT02-Bahia (NRS Sul).ipynb | pedreirajr/GeoCombatCOVID19 |
**Adicionando a população de 2019 (IBGE):** | pop = gpd.read_file('NT02 - Bahia/IBGE - Estimativa popul 2019.shp')
pop.head()
mun_ba['Pop'] = 0
for i, row in mun_ba.iterrows():
mun_ba.loc[i,'Pop'] = pop[pop['Codigo']==row['GEOCODIGO']]['p_pop_2019'].values[0] | _____no_output_____ | MIT | NT02-Bahia (NRS Sul).ipynb | pedreirajr/GeoCombatCOVID19 |
**Adicionando Casos até 24/04:** | casos = gpd.read_file('NT02 - Bahia/Evolução/data_shape_ba_mod(1).shp')
casos.info()
mun_ba['c20200424'] = 0
for i, row in mun_ba.iterrows():
mun_ba.loc[i,'c20200424'] = casos[casos['Codigo']==row['GEOCODIGO']]['2020-04-24'].values[0]
mun_ba['c20200424'] = mun_ba['c20200424'].fillna(0) | _____no_output_____ | MIT | NT02-Bahia (NRS Sul).ipynb | pedreirajr/GeoCombatCOVID19 |
**Calculando prevalências (com base em 24/04):** | mun_ba['prev'] = (mun_ba['c20200424']/mun_ba['Pop'])*100000
mun_ba.sort_values(by='prev', ascending = False) | _____no_output_____ | MIT | NT02-Bahia (NRS Sul).ipynb | pedreirajr/GeoCombatCOVID19 |
(2) Internações nos Hospitais BA **(a) Quantidade de indivíduos:** | mun_ba['Qtd_Tot'] = 0
mun_ba['Qtd_Fora'] = 0
mun_ba['Qtd_CplxM'] = 0
mun_ba['Qtd_CplxA'] = 0
mun_ba['Dia_Tot'] = 0
mun_ba['Dia_CplxM'] = 0
mun_ba['Dia_CplxA'] = 0 | _____no_output_____ | MIT | NT02-Bahia (NRS Sul).ipynb | pedreirajr/GeoCombatCOVID19 |
**Período de 01/07/2018 a 30/06/2019:** | from datetime import date
per = pd.date_range(date(2018,7,1), periods=365).tolist()
per[0]
per[-1]
# Entraram em alguma data até 30/06/2019 e saíram entre 01/07/2018 até 30/06/2019
df_BA = df2[(df2['DT_Inter'] <= per[-1]) & (df2['DT_Saida'] >= per[0]) & (df2['DT_Saida'] <= per[-1])]
#df_BA = df2[(df2['Cod_Municipio'].s... | _____no_output_____ | MIT | NT02-Bahia (NRS Sul).ipynb | pedreirajr/GeoCombatCOVID19 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.