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 |
|---|---|---|---|---|---|
Train the image classifierIn the following line of code, we will create an image classifier and we'll feed it with the training data we have. In this example, the image classifer's architecture will be a state-of-the-art Residual Network with 50 layers, also known as **ResNet-50**.Check out the official paper here: ht... | model = turi.image_classifier.create(trainingBuffers, target="foodType", model="resnet-50") | Resizing images...
Performing feature extraction on resized images...
Completed 270/270
PROGRESS: Creating a validation set from 5 percent of training data. This may take a while.
You can set ``validation_set=None`` to disable validation tracking.
| MIT | notebooks/Classify Image Example-ResNet50.ipynb | AFathi/TuriCreate-Notebook |
Evaluate the test data to determine the model accuracy | evaluations = model.evaluate(testingBuffers)
print evaluations["accuracy"] | 0.933333333333
| MIT | notebooks/Classify Image Example-ResNet50.ipynb | AFathi/TuriCreate-Notebook |
Save the Turi Create model to retrieve it later | model.save("egg_or_soup.model") | _____no_output_____ | MIT | notebooks/Classify Image Example-ResNet50.ipynb | AFathi/TuriCreate-Notebook |
Export the image classification model for Core ML | model.export_coreml("EggSoupClassifier.mlmodel") | _____no_output_____ | MIT | notebooks/Classify Image Example-ResNet50.ipynb | AFathi/TuriCreate-Notebook |
MAT281 Aplicaciones de la Matemática en la Ingeniería Módulo 02 Laboratorio Clase 06: Desarrollo de Algoritmos Instrucciones* Completa tus datos personales (nombre y rol USM) en siguiente celda.* La escala es de 0 a 4 considerando solo valores enteros.* Debes _pushear_ tus cambios a tu repositorio personal del curso... | import os
import numpy as np
import pandas as pd | _____no_output_____ | MIT | m02/m02_c06_lab/m02_c06_lab.ipynb | cristobal-montecino/mat281_portfolio |
Utilizaremos como ejemplo un dataset de gasto fiscal neto en Chile, obtenidos de una [datathon de DataCampfire](https://datacampfire.com/datathon/). | gasto_raw = pd.read_csv(os.path.join("data", "gasto_fiscal.csv"), sep=";")
gasto_raw.head() | _____no_output_____ | MIT | m02/m02_c06_lab/m02_c06_lab.ipynb | cristobal-montecino/mat281_portfolio |
Pasos a seguir:1. Renombra la columna `anio` por `year`.2. Crea la columna `month` utilizando el diccionario `es_month_dict` definido abajo. Hint: Usar un mapeo.3. Crea la columna `day` en que todos los registros sean igual a `1`.4. Crea la columna `dt_date` con la función `pd.to_datetime`. Lee la documentación!5. Fina... | es_month_dict = {
'enero': 1,
'febrero': 2,
'marzo': 3,
'abril': 4,
'mayo': 5,
'junio': 6,
'julio': 7,
'agosto': 8,
'septiembre': 9,
'octubre': 10,
'noviembre': 11,
'diciembre': 12
}
gasto = (
gasto_raw.rename(columns={'anio': 'year'})
.assign(
month=lamb... | _____no_output_____ | MIT | m02/m02_c06_lab/m02_c06_lab.ipynb | cristobal-montecino/mat281_portfolio |
Ejercicio 2 (1 pto.)Pivotea el dataframe `gasto_raw` tal que:- Los índices sean los ministerios (partidas).- Las columnas sean los años.- Cada celda sea la suma de los montos.- Rellenar las celdas vacías con `""`.¿Cuáles son las combinaciones de Año-Ministerio que no tienen gasto? | gasto_raw['anio'].sort_values().unique()
gasto_raw.pivot_table(
index='partida',
columns='anio',
values='monto',
aggfunc='sum',
fill_value='',
) | _____no_output_____ | MIT | m02/m02_c06_lab/m02_c06_lab.ipynb | cristobal-montecino/mat281_portfolio |
__Respuesta__:|Ministerio|Años||-|-||Ministerio De Energía|2009||Ministerio De La Mujer Y La Equidad De Género|2009-2015||Ministerio Del Deporte|2009-2013||Ministerio Del Medio Ambiente|2009||Servicio Electoral|2009 - 2016| Ejercicio 3 (1 pto.)Realiza los benchmarks del archivo `benchmark_loop.py` que se encuentra en ... | # %load fast_pandas/benchmark_loop.py
from fast_pandas.Benchmarker import Benchmarker
def iterrows_function(df):
for index, row in df.iterrows():
pass
def itertuples_function(df):
for row in df.itertuples():
pass
def df_values(df):
for row in df.values:
pass
params = {
"d... | Benchmarking function: df_values
Testing with a dataframe of size: 100
Result (seconds): 3.576299999622279e-05
Testing with a dataframe of size: 1000
Result (seconds): 0.0002777669999977661
Testing with a dataframe of size: 10000
Result (seconds): 0.002646879999974772
Testing with a dataframe of size: 10... | MIT | m02/m02_c06_lab/m02_c06_lab.ipynb | cristobal-montecino/mat281_portfolio |
VisualsThe `` element specifies the shape of the geometry for rendering. It is a child element from `` and a link can have multiple visual elements. | # Import the element creator
from pcg_gazebo.parsers.sdf import create_sdf_element
# The visual element is created with an empty geometry by default
visual = create_sdf_element('visual')
print(visual)
# To see the optional elements, use the method reset()
visual.reset(with_optional_elements=True)
print(visual)
# Settin... | <visual name="visual">
<geometry>
<box>
<size>2 3 4</size>
</box>
</geometry>
<cast_shadows>1</cast_shadows>
<pose frame="new_frame">0 0.2 0 0 0 0</pose>
</visual>
| ECL-2.0 | examples/sdf_parser_visuals.ipynb | argenos/pcg_gazebo |
requests 实例引入 | import requests
response = requests.get('https://www.baidu.com/')
print(type(response))
print(response.status_code)
print(type(response.text))
print(response.text)
print(response.cookies) | _____no_output_____ | MIT | ipy_notebook/requests.ipynb | NiroDu/python-tricks |
各种请求方式 | import requests
requests.post('http://httpbin.org/post')
requests.put('http://httpbin.org/put')
requests.delete('http://httpbin.org/delete')
requests.head('http://httpbin.org/get')
requests.options('http://httpbin.org/get') | _____no_output_____ | MIT | ipy_notebook/requests.ipynb | NiroDu/python-tricks |
请求 基本GET请求 基本写法 | import requests
response = requests.get('http://httpbin.org/get')
print(response.text) | _____no_output_____ | MIT | ipy_notebook/requests.ipynb | NiroDu/python-tricks |
带参数GET请求 | import requests
response = requests.get("http://httpbin.org/get?name=germey&age=22")
print(response.text)
import requests
data = {
'name': 'germey',
'age': 22
}
response = requests.get("http://httpbin.org/get", params=data)
print(response.text) | _____no_output_____ | MIT | ipy_notebook/requests.ipynb | NiroDu/python-tricks |
解析json | import requests
import json
response = requests.get("http://httpbin.org/get")
print(type(response.text))
print(response.json())
print(json.loads(response.text))
print(type(response.json())) | _____no_output_____ | MIT | ipy_notebook/requests.ipynb | NiroDu/python-tricks |
获取二进制数据 | import requests
response = requests.get("https://github.com/favicon.ico")
print(type(response.text), type(response.content))
print(response.text)
print(response.content)
import requests
response = requests.get("https://github.com/favicon.ico")
with open('favicon.ico', 'wb') as f:
f.write(response.content)
f.c... | _____no_output_____ | MIT | ipy_notebook/requests.ipynb | NiroDu/python-tricks |
添加headers | import requests
response = requests.get("https://www.zhihu.com/explore")
print(response.text)
import requests
headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36'
}
response = requests.get("https://www.zhihu.com/explo... | _____no_output_____ | MIT | ipy_notebook/requests.ipynb | NiroDu/python-tricks |
基本POST请求 | import requests
data = {'name': 'germey', 'age': '22'}
response = requests.post("http://httpbin.org/post", data=data)
print(response.text)
import requests
data = {'name': 'germey', 'age': '22'}
headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome... | _____no_output_____ | MIT | ipy_notebook/requests.ipynb | NiroDu/python-tricks |
响应 reponse属性 | import requests
response = requests.get('http://www.jianshu.com')
print(type(response.status_code), response.status_code)
print(type(response.headers), response.headers)
print(type(response.cookies), response.cookies)
print(type(response.url), response.url)
print(type(response.history), response.history) | _____no_output_____ | MIT | ipy_notebook/requests.ipynb | NiroDu/python-tricks |
状态码判断 | import requests
response = requests.get('http://www.jianshu.com/hello.html')
exit() if not response.status_code == requests.codes.not_found else print('404 Not Found')
import requests
response = requests.get('http://www.jianshu.com')
exit() if not response.status_code == 200 else print('Request Successfully') | _____no_output_____ | MIT | ipy_notebook/requests.ipynb | NiroDu/python-tricks |
下面的状态码,可以直接用string去表示,例如404可以是requests.codes.not_found,200可以是requests.codes.ok | 100: ('continue',),
101: ('switching_protocols',),
102: ('processing',),
103: ('checkpoint',),
122: ('uri_too_long', 'request_uri_too_long'),
200: ('ok', 'okay', 'all_ok', 'all_okay', 'all_good', '\\o/', '✓'),
201: ('created',),
202: ('accepted',),
203: ('non_authoritative_info', 'non_authoritative_information'),
204: ... | _____no_output_____ | MIT | ipy_notebook/requests.ipynb | NiroDu/python-tricks |
高级操作 文件上传 | import requests
files = {'file': open('favicon.ico', 'rb')}
response = requests.post("http://httpbin.org/post", files=files)
print(response.text) | _____no_output_____ | MIT | ipy_notebook/requests.ipynb | NiroDu/python-tricks |
获取cookie | import requests
response = requests.get("https://www.baidu.com")
print(response.cookies)
for key, value in response.cookies.items():
print(key + '=' + value) | _____no_output_____ | MIT | ipy_notebook/requests.ipynb | NiroDu/python-tricks |
会话维持 模拟登录 | 使用两次requests.get() 相当于打开了两次浏览器窗口,下面的例子第一次设置了cookies,第二次又重新打开了一个新对象去取cookies,所以取不到值。
import requests
requests.get('http://httpbin.org/cookies/set/number/123456789')
response = requests.get('http://httpbin.org/cookies')
print(response.text)
使用requests.Session()创建出的对象,用这个对象发起两次get请求,可以维持同一个对象通信。
import requests
s = requ... | _____no_output_____ | MIT | ipy_notebook/requests.ipynb | NiroDu/python-tricks |
证书验证 | import requests
response = requests.get('https://www.12306.cn')
print(response.status_code)
import requests
# from requests.packages import urllib3
# urllib3.disable_warnings()
response = requests.get('https://www.12306.cn', verify=False)
print(response.status_code)
import requests
response = requests.get('https://ww... | _____no_output_____ | MIT | ipy_notebook/requests.ipynb | NiroDu/python-tricks |
代理设置 | import requests
proxies = {
"http": "http://127.0.0.1:9743",
"https": "https://127.0.0.1:9743",
}
response = requests.get("https://www.taobao.com", proxies=proxies)
print(response.status_code)
import requests
proxies = {
"http": "http://user:password@127.0.0.1:9743/",
}
response = requests.get("https://www.t... | _____no_output_____ | MIT | ipy_notebook/requests.ipynb | NiroDu/python-tricks |
超时设置 | import requests
from requests.exceptions import ReadTimeout
try:
response = requests.get("http://httpbin.org/get", timeout = 0.5)
print(response.status_code)
except ReadTimeout:
print('Timeout') | _____no_output_____ | MIT | ipy_notebook/requests.ipynb | NiroDu/python-tricks |
认证设置 | 当网站需要输入用户名和密码才可以访问的时候,下面两种方式都可以模拟账号密码为参数的请求。
import requests
from requests.auth import HTTPBasicAuth
r = requests.get('http://120.27.34.24:9001', auth=HTTPBasicAuth('user', '123'))
print(r.status_code)
import requests
r = requests.get('http://120.27.34.24:9001', auth=('user', '123'))
print(r.status_code) | _____no_output_____ | MIT | ipy_notebook/requests.ipynb | NiroDu/python-tricks |
异常处理 [requests exceptions](https://requests.kennethreitz.org/en/master/api/exceptions) | import requests
from requests.exceptions import ReadTimeout, ConnectionError, RequestException
try:
response = requests.get("http://httpbin.org/get", timeout = 0.5)
print(response.status_code)
except ReadTimeout:
print('Timeout')
except ConnectionError:
print('Connection error')
except RequestException:... | Connection error
| MIT | ipy_notebook/requests.ipynb | NiroDu/python-tricks |
More To Come. Stay Tuned. !!If there are any suggestions/changes you would like to see in the Kernel please let me know :). Appreciate every ounce of help!**This notebook will always be a work in progress**. Please leave any comments about further improvements to the notebook! Any feedback or constructive criticism is... | import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
import IPython.display as ipd # To play sound in the notebook
from tqdm import tqdm_notebook
import wave
from scipy.io import wavfile
SAM... | _____no_output_____ | Apache-2.0 | notebooks/A Very Extensive Freesound Exploratory Analysis.ipynb | dhiraa/sabdha |
There is no missing data in training dataset Manually verified Audio | temp = train['manually_verified'].value_counts()
labels = temp.index
sizes = (temp / temp.sum())*100
trace = go.Pie(labels=labels, values=sizes, hoverinfo='label+percent')
layout = go.Layout(title='Manually varification of labels(0 - No, 1 - Yes)')
data = [trace]
fig = go.Figure(data=data, layout=layout)
py.iplot(fig) | _____no_output_____ | Apache-2.0 | notebooks/A Very Extensive Freesound Exploratory Analysis.ipynb | dhiraa/sabdha |
* Approximately 40 % labels are manually varified. | plt.figure(figsize=(12,8))
sns.distplot(train_data.nframes.values, bins=50, kde=False)
plt.xlabel('nframes', fontsize=12)
plt.title("Histogram of #frames")
plt.show()
plt.figure(figsize=(17,8))
boxplot = sns.boxplot(x="target", y="nframes", data=train_data)
boxplot.set(xlabel='', ylabel='')
plt.title('Distribution of a... | _____no_output_____ | Apache-2.0 | notebooks/A Very Extensive Freesound Exploratory Analysis.ipynb | dhiraa/sabdha |
Total number of labels are 41 | temp = train_data.sort_values(by='target')
temp.head() | _____no_output_____ | Apache-2.0 | notebooks/A Very Extensive Freesound Exploratory Analysis.ipynb | dhiraa/sabdha |
Now look at some labels waveform : 1. Acoustic_guitar 2. Applause 3. Bark 1. Acoustic_guitar | print("Acoustic_guitar : ")
fig, ax = plt.subplots(10, 4, figsize = (12, 16))
for i in range(40):
ax[i//4, i%4].plot(temp['time_series'][i])
ax[i//4, i%4].set_title(temp['file_name'][i][:-4])
ax[i//4, i%4].get_xaxis().set_ticks([])
fig.savefig("AudioWaveform", dpi=900) | _____no_output_____ | Apache-2.0 | notebooks/A Very Extensive Freesound Exploratory Analysis.ipynb | dhiraa/sabdha |
2. Applause | print("Applause : ")
fig, ax = plt.subplots(10, 4, figsize = (12, 16))
for i in range(40):
ax[i//4, i%4].plot(temp['time_series'][i+300])
ax[i//4, i%4].set_title(temp['file_name'][i+300][:-4])
ax[i//4, i%4].get_xaxis().set_ticks([]) | _____no_output_____ | Apache-2.0 | notebooks/A Very Extensive Freesound Exploratory Analysis.ipynb | dhiraa/sabdha |
3. Bark | print("Bark : ")
fig, ax = plt.subplots(10, 4, figsize = (12, 16))
for i in range(40):
ax[i//4, i%4].plot(temp['time_series'][i+600])
ax[i//4, i%4].set_title(temp['file_name'][i+600][:-4])
ax[i//4, i%4].get_xaxis().set_ticks([])
from wordcloud import WordCloud
wordcloud = WordCloud(max_font_size=50, width=6... | _____no_output_____ | Apache-2.0 | notebooks/A Very Extensive Freesound Exploratory Analysis.ipynb | dhiraa/sabdha |
Spectrogram | def log_specgram(audio, sample_rate, window_size=20,
step_size=10, eps=1e-10):
nperseg = int(round(window_size * sample_rate / 1e3))
noverlap = int(round(step_size * sample_rate / 1e3))
freqs, times, spec = signal.spectrogram(audio,
fs=sample_rate,
... | _____no_output_____ | Apache-2.0 | notebooks/A Very Extensive Freesound Exploratory Analysis.ipynb | dhiraa/sabdha |
Specgtrogram of "Hi-Hat" in 3d If we use spectrogram as an input features for NN, we have to remember to normalize features. | mean = np.mean(spectrogram, axis=0)
std = np.std(spectrogram, axis=0)
spectrogram = (spectrogram - mean) / std
data = [go.Surface(z=spectrogram.T)]
layout = go.Layout(
title='Specgtrogram of "Hi-Hat" in 3d',
scene = dict(
yaxis = dict(title='Frequencies', range=freqs),
xaxis = dict(title='Time', range=t... | _____no_output_____ | Apache-2.0 | notebooks/A Very Extensive Freesound Exploratory Analysis.ipynb | dhiraa/sabdha |
DemIntro02: Rational Expectations Agricultural Market Model Preliminary task:Load required modules | from compecon.quad import qnwlogn
from compecon.tools import discmoments
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style('dark')
%matplotlib notebook | _____no_output_____ | MIT | notebooks/old notebooks/demintro02.ipynb | snowdj/CompEcon-python |
Generate yield distribution | sigma2 = 0.2 ** 2
y, w = qnwlogn(25, -0.5 * sigma2, sigma2) | _____no_output_____ | MIT | notebooks/old notebooks/demintro02.ipynb | snowdj/CompEcon-python |
Compute rational expectations equilibrium using function iteration, iterating on acreage planted | A = lambda aa, pp: 0.5 + 0.5 * np.dot(w, np.maximum(1.5 - 0.5 * aa * y, pp))
ptarg = 1
a = 1
print('{:^6} {:^10} {:^10}\n{}'.format('iter', 'a', "|a' - a|",'-' * 27))
for it in range(50):
aold = a
a = A(a, ptarg)
print('{:^6} {:^10.4f} {:^10.1e}'.format(it, a, np.linalg.norm(a - aold)))
if np.linalg.no... | iter a |a' - a|
---------------------------
0 1.0198 2.0e-02
1 1.0171 2.7e-03
2 1.0175 3.7e-04
3 1.0174 5.0e-05
4 1.0174 6.8e-06
5 1.0174 9.3e-07
6 1.0174 1.3e-07
7 1.0174 1.7e-08
8 1.0174 2.3e-09
| MIT | notebooks/old notebooks/demintro02.ipynb | snowdj/CompEcon-python |
Intermediate outputs | q = a * y # quantity produced in each state
p = 1.5 - 0.5 * a * y # market price in each state
f = np.maximum(p, ptarg) # farm price in each state
r = f * q # farm revenue in each state
g = (f - p) * q #government expenditures | _____no_output_____ | MIT | notebooks/old notebooks/demintro02.ipynb | snowdj/CompEcon-python |
Print results | varnames = ['Market Price', 'Farm Price', 'Farm Revenue', 'Government Expenditures']
xavg, xstd = discmoments(w, np.vstack((p, f, r, g)))
print('\n{:^24} {:^8} {:^8}\n{}'.format('Variable', 'Expect', 'Std Dev','-'*42))
for varname, av, sd in zip(varnames, xavg, xstd):
print('{:24} {:8.4f} {:8.4f}'.format(varname, a... |
Variable Expect Std Dev
------------------------------------------
Market Price 0.9913 0.1028
Farm Price 1.0348 0.0506
Farm Revenue 1.0447 0.1773
Government Expenditures 0.0573 0.1038
| MIT | notebooks/old notebooks/demintro02.ipynb | snowdj/CompEcon-python |
Generate fixed-point mapping | aeq = a
a = np.linspace(0, 2, 100)
g = np.array([A(k, ptarg) for k in a]) | _____no_output_____ | MIT | notebooks/old notebooks/demintro02.ipynb | snowdj/CompEcon-python |
Graph rational expectations equilibrium | fig1 = plt.figure(figsize=[6, 6])
ax = fig1.add_subplot(111, title='Rational expectations equilibrium', aspect=1,
xlabel='Acreage Planted', xticks=[0, aeq, 2], xticklabels=['0', '$a^{*}$', '2'],
ylabel='Rational Acreage Planted', yticks=[0, aeq, 2],yticklabels=['0', '$a^{*}... | _____no_output_____ | MIT | notebooks/old notebooks/demintro02.ipynb | snowdj/CompEcon-python |
Compute rational expectations equilibrium as a function of the target price | nplot = 50
ptarg = np.linspace(0, 2, nplot)
a = 1
Ep, Ef, Er, Eg, Sp, Sf, Sr, Sg = (np.empty(nplot) for k in range(8))
for ip in range(nplot):
for it in range(50):
aold = a
a = A(a, ptarg[ip])
if np.linalg.norm((a - aold) < 1.e-10):
break
q = a * y # q... | _____no_output_____ | MIT | notebooks/old notebooks/demintro02.ipynb | snowdj/CompEcon-python |
Graph expected prices vs target price | fig2 = plt.figure(figsize=[8, 6])
ax1 = fig2.add_subplot(121, title='Expected price',
xlabel='Target price', xticks=[0, 1, 2],
ylabel='Expectation', yticks=[0.5, 1, 1.5, 2], ylim=[0.5, 2.0])
zeroline(Ep)
ax1.plot(ptarg, Ep, linewidth=4, label='Market Price')
ax1.plot(ptarg, Ef, linewid... | _____no_output_____ | MIT | notebooks/old notebooks/demintro02.ipynb | snowdj/CompEcon-python |
Graph expected prices vs target price | ax2 = fig2.add_subplot(122, title='Price variabilities',
xlabel='Target price', xticks=[0, 1, 2],
ylabel='Standard deviation', yticks=[0, 0.1, 0.2]) #plt.ylim(0.5, 2.0)
zeroline(Sf)
ax2.plot(ptarg, Sp, linewidth=4, label='Market Price')
ax2.plot(ptarg, Sf, linewidth=4, labe... | _____no_output_____ | MIT | notebooks/old notebooks/demintro02.ipynb | snowdj/CompEcon-python |
Graph expected farm revenue vs target price | fig3 = plt.figure(figsize=[12, 6])
ax1 = fig3.add_subplot(131, title='Expected revenue',
xlabel='Target price', xticks=[0, 1, 2],
ylabel='Expectation', yticks=[1, 2, 3], ylim=[0.8, 3.0])
zeroline(Er)
ax1.plot(ptarg, Er, linewidth=4) | _____no_output_____ | MIT | notebooks/old notebooks/demintro02.ipynb | snowdj/CompEcon-python |
Graph standard deviation of farm revenue vs target price | ax2 = fig3.add_subplot(132, title='Farm Revenue Variability',
xlabel='Target price', xticks=[0, 1, 2],
ylabel='Standard deviation', yticks=[0, 0.2, 0.4])
zeroline(Sr)
ax2.plot(ptarg, Sr, linewidth=4) | _____no_output_____ | MIT | notebooks/old notebooks/demintro02.ipynb | snowdj/CompEcon-python |
Graph expected government expenditures vs target price | ax3 = fig3.add_subplot(133, title='Expected Government Expenditures',
xlabel='Target price', xticks=[0, 1, 2],
ylabel='Expectation', yticks=[0, 1, 2], ylim=[-0.05, 2.0])
zeroline(Eg)
ax3.plot(ptarg, Eg, linewidth=4)
plt.show() | _____no_output_____ | MIT | notebooks/old notebooks/demintro02.ipynb | snowdj/CompEcon-python |
'IBM' Stock analysis for monthly , weekly as well as daily stock prices. | df['IBM_week'] = df.IBM.rolling(7).mean().shift()
df['IBM_month'] = df.IBM.rolling(30).mean()
plt.figure(figsize=(15,10))
plt.grid(True)
plt.plot(df['IBM_week'],label='Weekly')
plt.plot(df['IBM_month'], label='Monthly')
plt.plot(df['IBM'],label='IBM')
plt.legend(loc=2) | _____no_output_____ | Apache-2.0 | task5/Stock_LSTM[final].ipynb | raviyadav44/Brillect-PML-Internship |
APPL stocks | df['AAPL_week'] = df.IBM.rolling(7).mean()
df['AAPL_month'] = df.IBM.rolling(30).mean()
plt.figure(figsize=(15,10))
plt.grid(True)
plt.plot(df['AAPL_week'],label='Weekly')
plt.plot(df['AAPL_month'], label='Monthly')
plt.plot(df['AAPL'],label='AAPL')
plt.legend(loc=2)
from statsmodels.tsa.stattools import adfuller
def ... | [[0.7772312]]
| Apache-2.0 | task5/Stock_LSTM[final].ipynb | raviyadav44/Brillect-PML-Internship |
Stacked LSTM | df1=df.reset_index()['AAPL']
import matplotlib.pyplot as plt
plt.plot(df1)
from sklearn.preprocessing import MinMaxScaler
scaler=MinMaxScaler(feature_range=(0,1))
df1=scaler.fit_transform(np.array(df1).reshape(-1,1))
print(df1)
##splitting dataset into train and test split
training_size=int(len(df1)*0.65)
test_size=len... | _____no_output_____ | Apache-2.0 | task5/Stock_LSTM[final].ipynb | raviyadav44/Brillect-PML-Internship |
Baseline model classification The purpose of this notebook is to make predictions for all six categories on the given dataset using some set of rules.Let's assume that human labellers have labelled these comments based on the certain kind of words present in the comments. So it is worth exploring the comments to check... | import os
dir_path = os.path.dirname(os.getcwd())
import numpy as np
import pandas as pd
import nltk
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
import re
import string
import operator
import pickle
import sys
sys.path.append(os.path.join(dir_path, "src"))
from clean_comments import clea... | _____no_output_____ | MIT | notebooks/baseline_model.ipynb | Navjotbians/Toxic-comment-classifier |
2. Datasets for each category Dataset with toxic comments | #extract dataset with toxic label
df_toxic = df[df['toxic'] == 1]
#Reseting the index
df_toxic.set_index(['id'], inplace = True)
df_toxic.reset_index(level =['id'], inplace = True) | _____no_output_____ | MIT | notebooks/baseline_model.ipynb | Navjotbians/Toxic-comment-classifier |
Dataset of severe toxic comments | #extract dataset with Severe toxic label
df_severe_toxic = df[df['severe_toxic'] == 1]
#Reseting the index
df_severe_toxic.set_index(['id'], inplace = True)
df_severe_toxic.reset_index(level =['id'], inplace = True) | _____no_output_____ | MIT | notebooks/baseline_model.ipynb | Navjotbians/Toxic-comment-classifier |
Dataset with obscene comment | #extract dataset with obscens label
df_obscene = df[df['obscene'] == 1]
#Reseting the index
df_obscene.set_index(['id'], inplace = True)
df_obscene.reset_index(level =['id'], inplace = True)
#df_obscene =df_obscene.drop('comment_text', axis=1) | _____no_output_____ | MIT | notebooks/baseline_model.ipynb | Navjotbians/Toxic-comment-classifier |
Dataset with comments labeled as "identity_hate" | df_identity_hate = df[df['identity_hate'] == 1]
#Reseting the index
df_identity_hate.set_index(['id'], inplace = True)
df_identity_hate.reset_index(level =['id'], inplace = True) | _____no_output_____ | MIT | notebooks/baseline_model.ipynb | Navjotbians/Toxic-comment-classifier |
Dataset with all the threat comments | df_threat = df[df['threat'] == 1]
#Reseting the index
df_threat.set_index(['id'], inplace = True)
df_threat.reset_index(level =['id'], inplace = True) | _____no_output_____ | MIT | notebooks/baseline_model.ipynb | Navjotbians/Toxic-comment-classifier |
Dataset of comments with "Insult" label | df_insult = df[df['insult'] == 1]
#Reseting the index
df_insult.set_index(['id'], inplace = True)
df_insult.reset_index(level =['id'], inplace = True) | _____no_output_____ | MIT | notebooks/baseline_model.ipynb | Navjotbians/Toxic-comment-classifier |
Dataset with comments which have all six labels | df_6 = df[(df['toxic']==1) & (df['severe_toxic']==1) &
(df['obscene']==1) & (df['threat']==1)&
(df['insult']==1)& (df['identity_hate']==1)]
df_6.set_index(['id'], inplace = True)
df_6.reset_index(level =['id'], inplace = True)
# df6 = df_6.drop('comment_text', axis=1) | _____no_output_____ | MIT | notebooks/baseline_model.ipynb | Navjotbians/Toxic-comment-classifier |
3. Preperation of vocab | ### frequent_words function take dataset as an input and returns two arguments -
### all_words and counts.
### all_words gives all the words occuring in the provided dataset
### counts gives dictionary with keys as a words those exists in the entire dataset and values
### as a count of existance of these words in the ... | _____no_output_____ | MIT | notebooks/baseline_model.ipynb | Navjotbians/Toxic-comment-classifier |
Getting the vocab used in each category in descending order its count For **`toxic`** category | descend_order_toxic_dict = descend_order_dict(df_toxic) | _____no_output_____ | MIT | notebooks/baseline_model.ipynb | Navjotbians/Toxic-comment-classifier |
These are the words most frequently used in toxic comments For **`severe_toxic`** category | descend_order_severe_toxic_dict =descend_order_dict(df_severe_toxic) | _____no_output_____ | MIT | notebooks/baseline_model.ipynb | Navjotbians/Toxic-comment-classifier |
These are the words most frequently used in severe toxic comments For **`obscene`** category | descend_order_obscene_dict = descend_order_dict(df_obscene) | _____no_output_____ | MIT | notebooks/baseline_model.ipynb | Navjotbians/Toxic-comment-classifier |
These are the words most frequently used in obscene comments For **`threat`** category | descend_order_threat_dict = descend_order_dict(df_threat) | _____no_output_____ | MIT | notebooks/baseline_model.ipynb | Navjotbians/Toxic-comment-classifier |
These are the words most frequently used in severe threat comments For **`insult`** category | descend_order_insult_dict = descend_order_dict(df_insult) | _____no_output_____ | MIT | notebooks/baseline_model.ipynb | Navjotbians/Toxic-comment-classifier |
These are the words most frequently used in comments labeled as an insult For **`identity_hate`** category | descend_order_id_hate_dict = descend_order_dict(df_identity_hate) | _____no_output_____ | MIT | notebooks/baseline_model.ipynb | Navjotbians/Toxic-comment-classifier |
These are the most frequently used words in the comments labeled as identity_hate For comments when all categories are 1 | descend_order_all_label_dict = descend_order_dict(df_6) | _____no_output_____ | MIT | notebooks/baseline_model.ipynb | Navjotbians/Toxic-comment-classifier |
These are the most frequently used words in the comments labeled as identity_hate Picking up the top n words from the descend vocab dictionary In this code, top 3 words are considered to make the prediction. | # list(descend_order_all_label_dict.keys())[3]
## combining descend vocab dictionaries of all the categories in one dictionary
## with categories as their keys
all_label_descend_vocab = {'toxic':descend_order_toxic_dict,
'severe_toxic':descend_order_severe_toxic_dict,
'ob... | _____no_output_____ | MIT | notebooks/baseline_model.ipynb | Navjotbians/Toxic-comment-classifier |
4. Performance check of baseline Model | ## Check if the any word from the top 3 words from the six categories exist in the comments
def word_intersection(input_str, n, all_words =all_label_descend_vocab):
toxic_pred = []
severe_toxic_pred = []
obscene_pred = []
threat_pred = []
insult_pred = []
id_hate_pred = []
rule_based_pred =... | _____no_output_____ | MIT | notebooks/baseline_model.ipynb | Navjotbians/Toxic-comment-classifier |
Uncomment the below cell to get the prediction on the dataset but it is already saved in `rule_base_pred.pkl` in list form to save time | ## store the values of predictions by running the word_intersection function on
## all the comments
# rule_base_pred = df['comment_text'].apply(lambda x: word_intersection(x,3)) | _____no_output_____ | MIT | notebooks/baseline_model.ipynb | Navjotbians/Toxic-comment-classifier |
After running above cell, we get the predictions on the entire dataset for each category in `rule_base_pred`, the orginal type of `rule_base_pred` is pandas.core.series.Series. This pandas series is converted into list and saved for future use. This `.pkl` fine can be loaded by running below cell. | ### save rule_base_pred
# file_name = "rule_base_pred.pkl"
# open_file = open(file_name, "wb")
# pickle.dump(rule_base_pred, open_file)
# # open_file.close()
# open_file = open("rule_base_pred.pkl", "rb")
# pred_rule = pickle.load(open_file)
# open_file.close()
### Open the saved rule_base_pred.pkl
pkl_file = os.path.... | _____no_output_____ | MIT | notebooks/baseline_model.ipynb | Navjotbians/Toxic-comment-classifier |
Uncomment pred_rule line in below cell to convert the type of predictions from panda series to list,if not using saved `rule_base_pred.pkl` | ### Change the type to list
pred_true = y_true.values.tolist()
# pred_rule = rule_base_pred.values.tolist() | _____no_output_____ | MIT | notebooks/baseline_model.ipynb | Navjotbians/Toxic-comment-classifier |
Compute accuracy of Baseline Model | ## Accuracy check for decent and not-decent comments classification
count = 0
for i in range(0, len(df)):
if pred_true[i] == pred_rule[i]:
count = count+1
print("Overall accuracy of rule based classifier : {}".format((count/len(df))*100)) | Overall accuracy of rule based classifier : 76.5615306039318
| MIT | notebooks/baseline_model.ipynb | Navjotbians/Toxic-comment-classifier |
Based on the rule implimented here, baseline classifier is classifying decent and not-decent comments with the **accuracy of 76.6%**.Now we have to see if AI based models giver better performance than this. | ## Category wise accuracy check
mean = []
for j in range(0, len(pred_true[0])):
count = 0
for i in range(0, len(df)):
if pred_true[i][j] == pred_rule[i][j]:
count = count+1
mean.append(count/len(df)*100)
print("Accuracy of rule based classifier in predicting {} comments : {}".format(... | Accuracy of rule based classifier in predicting toxic comments : 89.4554774990443
Accuracy of rule based classifier in predicting severe_toxic comments : 88.22906417832814
Accuracy of rule based classifier in predicting obscene comments : 96.3282802012897
Accuracy of rule based classifier in predicting threat comments ... | MIT | notebooks/baseline_model.ipynb | Navjotbians/Toxic-comment-classifier |
Mean accuracy of our *rule-based-model* is 92.7%Minimum accuracy for predicting `toxic `, `severe_toxic `, `obscene `, `threat `, `insult `, or `identity_hate ` class of the Baseline model is more that 88%.Accuracies for:`toxic `: 89.4%`severe_toxic `: 88.2%`obscene `: 96.3%`threat `: 87.8%`insult `: 95.8%`identity_ha... | yp=np.array([np.array(xi) for xi in pred_rule])
type(yp)
# type(y[0])
yp.shape
yt=np.array([np.array(xi) for xi in pred_true])
type(yt)
yt.shape
from sklearn.metrics import jaccard_score
print("Jaccard score is : {}".format(jaccard_score(yt,yp, average= 'weighted'))) | Jaccard score is : 0.25033619059083945
| MIT | notebooks/baseline_model.ipynb | Navjotbians/Toxic-comment-classifier |
Manual Labeling Data PreparationGenerate the pixels that will be used for train, test, and validation. This keeps pixels a certain distance and ensures they're spatially comprehensive. | import rasterio
import random
import matplotlib.pyplot as plt
import os
import sys
import datetime
from sklearn.utils import class_weight
module_path = os.path.abspath(os.path.join('..'))
if module_path not in sys.path:
sys.path.append(module_path)
module_path = os.path.abspath(os.path.join('rcnn'))
if module_... | _____no_output_____ | MIT | labeling_data_prep.ipynb | patrickcgray/florence_mapping |
Load in the training data | lc_labels = rasterio.open('/deep_data/recurrent_data/NLCD_DATA/landcover/NLCD_2011_Land_Cover_L48_20190424.img')
canopy_labels = rasterio.open('/deep_data/recurrent_data/NLCD_DATA/canopy/CONUSCartographic_2_8_16/Cartographic/nlcd2011_usfs_conus_canopy_cartographic.img') | _____no_output_____ | MIT | labeling_data_prep.ipynb | patrickcgray/florence_mapping |
Ingest the landsat imagery stacked into yearly seasonal tilesWe don't really need to do this here but the code is just copied from the rcnn code | tiles = {}
landsat_datasets = {}
tiles['028012'] = ['20110103', '20110308', '20110730', '20110831', '20111103']
tiles['029011'] = ['20110103', '20110308', '20110730', '20110831', '20111018']
tiles['028011'] = ['20110103', '20110308', '20110831', '20111018', '20111103']
for tile_number, dates in tiles.items():
tile... | _____no_output_____ | MIT | labeling_data_prep.ipynb | patrickcgray/florence_mapping |
Testing for Runtime and Memory Usage | %load_ext line_profiler
%lprun -f rnn_pixels.tvt_pix_locations rnn_pixels.tvt_pix_locations(landsat_datasets, lc_labels, canopy_labels, tile_size, tile_list, clean_pixels, 10, 10, 10, class_dict)
w_tile_gen = rnn_tiles.rnn_tile_gen(landsat_datasets, lc_labels, canopy_labels, tile_size, class_count)
w_generator = w_tile... | 6.15 ms ± 111 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
| MIT | labeling_data_prep.ipynb | patrickcgray/florence_mapping |
Generate Data for TVT | px = rnn_pixels.make_pixels(1, tile_list)
len(px)
px
2500000 / 2500 * 45 / 60 / 60
print(datetime.datetime.now())
px_to_use = px
clean_pixels = rnn_pixels.delete_bad_tiles(landsat_datasets,lc_labels, canopy_labels, px_to_use, tile_size, buffer_pix=1)
print(datetime.datetime.now())
print(len(clean_pixels))
print(datetim... | 2020-02-08 19:57:27.832484
Beginning TVT pixel creation.
Iterating through data and clipping for balance.
Processing Complete.
2020-02-09 05:26:35.530992
test: 900 val: 900 train: 9000
| MIT | labeling_data_prep.ipynb | patrickcgray/florence_mapping |
See if Data is Actually Balanced | class_count = 6
pixels = tvt_pixels[2]
# gets balanced pixels locations
w_tile_gen = rnn_tiles.rnn_tile_gen(landsat_datasets, lc_labels, canopy_labels, tile_size, class_count)
w_generator = w_tile_gen.tile_generator(pixels, batch_size=1, flatten=True, canopy=True)
total_labels = list()
count = 0
#buckets = {0:[], 1:... | _____no_output_____ | MIT | labeling_data_prep.ipynb | patrickcgray/florence_mapping |
run through the pixels, buffer each pixel and add it to a geopandas dataset, convert that CRS to 4326 then save that geopandas dataset as a shapefile | #count_per_class = 3000
count_per_class = 1500 # 1667 * 6 ~= 10,000
pixel_coords = []
for lc_class in buckets.keys():
for i, pixel in enumerate(buckets[lc_class]):
landsat_ds = landsat_datasets[pixel["tile_name"]][0] # get the stack of ls datasets from that location and take the first
x, y = landsa... | _____no_output_____ | MIT | labeling_data_prep.ipynb | patrickcgray/florence_mapping |
import numpy as np
import os
import sys
from tensorflow.keras.layers import Input, Dropout, Concatenate
from tensorflow.keras.layers import Conv2DTranspose, Conv2D
from tensorflow.keras.models import Sequential, Model
from tensorflow.keras.layers import LeakyReLU, Activation
from tensorflow.keras.layers import BatchNor... | _____no_output_____ | MIT | UNET/UNET_Build.ipynb | hansong0219/Advanced-Deep-learning-Notebooks | |
Kobe Bryant Tribute Word Cloud @Author: Deep Contractor | import pandas as pd
import numpy as np
from os import path, getcwd
import matplotlib.pyplot as plt
from wordcloud import WordCloud, ImageColorGenerator, STOPWORDS
from PIL import Image
from twitterscraper import query_tweets
import datetime as dt
begin_date = dt.date(2020,1,26)
end_date = dt.date(2020,1,27)
lang = '... | _____no_output_____ | Apache-2.0 | Kobe Bryant Tribute.ipynb | chesterking123/Kobe-Bryant-Tribute-Word-Cloud |
Natural Language Processing RNN y LSTM. | from tensorflow.keras import *
from tensorflow.keras.layers import *
from tensorflow.keras.preprocessing.text import *
from tensorflow.keras.utils import *
import tensorflow as tf
import numpy as np
data = ["""Con diez cañones por banda,
viento en popa a toda vela,
no corta el mar, sino vuela
un velero bergantín;
... | ['diez cañones por su viento y la a un vela no corta el mar sino vuela un velero bergantín bajel pirata que ni por su bravura el mar en la mar sino del uno al otro confín la lona en la mar sino en la lona gime el mar y allá en la movimiento olas de plata y allá y allá el mar pirata que alegre en la lona a a un velero a... | MIT | NaturalLanguajeProcessing.ipynb | qwerteleven/ToolsDeepLearning |
Work looking at https://www.bexar.org/2988/Online-District-Clerk-Criminal-Records | import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import datetime
%matplotlib inline
Bexar_Criminal_AB_df = pd.read_csv(r'http://edocs.bexar.org/cc/DC_cjjorad_a_b.csv',header=0)
Bexar_Criminal_C_df = pd.read_csv('http://edocs.bexar.org/cc/DC_cjjorad_c.csv',header=0)
Bexar_Criminal_DF_df = pd.read_c... | _____no_output_____ | MIT | Bexar_Records_First_Work.ipynb | ldhagen/Bexar_Records |
https://search.bexar.org/Case/CaseDetail?r=5ae98979-5190-4b60-b939-cb5ddef960cd&cs=2007CR11191W&ct=&&p=1_2007CR11191W+++D1871272998100000 | combined_df.loc[:, 'OFFENSE-DATE_dt'] = pd.to_datetime(combined_df['OFFENSE-DATE'], errors='coerce') | _____no_output_____ | MIT | Bexar_Records_First_Work.ipynb | ldhagen/Bexar_Records |
https://www.krem.com/article/news/crime/police-say-guns-drugs-pipe-bombs-found-in-north-san-antonio-home-2-arrested/273-073a5835-3afc-4a01-9742-234a84bfed85 | combined_df[combined_df['FULL-NAME'].str.contains('HOTTLE')]
combined_df[(combined_df['OFFENSE-DATE_dt'] =='2019-07-17')]
combined_df[combined_df['FULL-NAME'].str.contains('FERRILL')]
combined_df[(combined_df['BIRTHDATE_dt'] == '1997-09-29')]
combined_df[combined_df['FULL-NAME'].str.contains('LEDBETTER')]
combined_df[(... | _____no_output_____ | MIT | Bexar_Records_First_Work.ipynb | ldhagen/Bexar_Records |
https://search.bexar.org/Case/CaseDetail?r=103d31d3-30d0-4a6d-bb7e-3a67205e3f52&cs=2009CR2391A&ct=&=&full=y&p=1_2009CR2391A%20%20%20%20D4371336448100000events | x = combined_df[(combined_df['BIRTHDATE_dt'] == '1985-10-25') & (combined_df['FULL-NAME'].str.contains('ROBLES'))]
x.sort_values(by=['OFFENSE-DATE_dt'])
combined_df['OFFENSE-DATE_dt'].max()
len(combined_df)
combined_df[combined_df['OFFENSE-DATE_dt'] > '2021-8-1']
combined_df[combined_df['FULL-NAME'].str.contains('NICEF... | _____no_output_____ | MIT | Bexar_Records_First_Work.ipynb | ldhagen/Bexar_Records |
Introduction to Databases and SQL- **Authors**: Ian Dennis Miller- **Research field**: Social Psychology - Social Complexity- **Lesson topic**: Databases and SQL- **Lesson content URL**: Plan- get a data set from R: mtcars- select from it using SQL (via sqldf)- export it as CSV file- in sqlite, create database and i... | nrow(mtcars)
ncol(mtcars)
head(mtcars)
summary(mtcars) | _____no_output_____ | Apache-2.0 | lessons/misc/sql-intro/r-sql.ipynb | UAAppComp/studyGroup |
use SQL to select cars with 6-cylinder engines | library(sqldf)
# help(sqldf)
sqldf('select * from mtcars where cyl=6') | _____no_output_____ | Apache-2.0 | lessons/misc/sql-intro/r-sql.ipynb | UAAppComp/studyGroup |
There are 7 cars matching the query. | nrow(sqldf('select * from mtcars where cyl=6')) | _____no_output_____ | Apache-2.0 | lessons/misc/sql-intro/r-sql.ipynb | UAAppComp/studyGroup |
We can obtain the same result directly with SQL... but let's not get ahead of ourselves. | sqldf('select count(*) from mtcars where cyl=6') | _____no_output_____ | Apache-2.0 | lessons/misc/sql-intro/r-sql.ipynb | UAAppComp/studyGroup |
write mtcars dataset to the file system | df = mtcars
df$name = rownames(df) # move R's rownames into their own column
write.table(df, "mtcars.csv", quote=TRUE, row.names=FALSE, col.names=FALSE, sep=",") | _____no_output_____ | Apache-2.0 | lessons/misc/sql-intro/r-sql.ipynb | UAAppComp/studyGroup |
create sqlite database in terminal make mtcars-initThat will run the following: sqlite3 mtcars.sqlite < mtcars-init.sqlThat SQL file does the following:- drop a table called results- create a table called results with columns for the mtcars data- tell sqlite to load a CSV file- load the CSV file into the results... | library(RSQLite)
# connect to the database
db = dbConnect(SQLite(), dbname="mtcars.sqlite") | _____no_output_____ | Apache-2.0 | lessons/misc/sql-intro/r-sql.ipynb | UAAppComp/studyGroup |
list the tables that are available | dbListTables(db) | _____no_output_____ | Apache-2.0 | lessons/misc/sql-intro/r-sql.ipynb | UAAppComp/studyGroup |
Inspect columns in the results table | dbListFields(db, "results") | _____no_output_____ | Apache-2.0 | lessons/misc/sql-intro/r-sql.ipynb | UAAppComp/studyGroup |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.