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
Connect to trinoThe following cell creates a trino api connection.It assumes that your `credentials.env` file has been edited so that`TRINO_PASSWD` has a JWT token obtained from:https://das-odh-trino.apps.odh-cl1.apps.os-climate.org/Your `TRINO_USER` value should be your github username.
import trino conn = trino.dbapi.connect( host=os.environ['TRINO_HOST'], port=int(os.environ['TRINO_PORT']), user=os.environ['TRINO_USER'], http_scheme='https', auth=trino.auth.JWTAuthentication(os.environ['TRINO_PASSWD']), verify=True, ) cur = conn.cursor()
_____no_output_____
FTL
notebooks/test-trino-access.ipynb
os-climate/data-platform-demo
Test your trino connectionThis cell shows all the catalogs visible to you.If your trino api connection initialized correctly above,this `show catalogs` command should always succeed.
cur.execute('show catalogs') cur.fetchall()
_____no_output_____
FTL
notebooks/test-trino-access.ipynb
os-climate/data-platform-demo
Gaussian discriminant analysis con stessa matrice di covarianza per le distribuzioni delle due classi e conseguente separatore lineare. Implementata in scikit-learn. Valutazione con cross validation.
import warnings warnings.filterwarnings('ignore') %matplotlib inline import pandas as pd import numpy as np import scipy.stats as st from sklearn.discriminant_analysis import LinearDiscriminantAnalysis from sklearn.model_selection import cross_val_score import sklearn.metrics as mt import matplotlib.pyplot as plt impo...
_____no_output_____
MIT
codici/.ipynb_checkpoints/gda-lin-sk-cv-checkpoint.ipynb
tvml/fo2021
Leggiamo i dati da un file csv in un dataframe pandas. I dati hanno 3 valori: i primi due corrispondono alle features e sono assegnati alle colonne x1 e x2 del dataframe; il terzo è il valore target, assegnato alla colonna t. Vengono poi creati una matrice X delle features e un vettore target t
# legge i dati in dataframe pandas data = pd.read_csv("../../data/ex2data1.txt", header= None,delimiter=',', names=['x1','x2','t']) # calcola dimensione dei dati n = len(data) n0 = len(data[data.t==0]) # calcola dimensionalità delle features features = data.columns nfeatures = len(features)-1 X = np.array(data[featu...
_____no_output_____
MIT
codici/.ipynb_checkpoints/gda-lin-sk-cv-checkpoint.ipynb
tvml/fo2021
Visualizza il dataset.
fig = plt.figure(figsize=(16,8)) ax = fig.gca() ax.scatter(data[data.t==0].x1, data[data.t==0].x2, s=40, color=colors[0], alpha=.7) ax.scatter(data[data.t==1].x1, data[data.t==1].x2, s=40,c=colors[1], alpha=.7) plt.xlabel('$x_1$', fontsize=12) plt.ylabel('$x_2$', fontsize=12) plt.xticks(fontsize=10) plt.yticks(fontsize...
_____no_output_____
MIT
codici/.ipynb_checkpoints/gda-lin-sk-cv-checkpoint.ipynb
tvml/fo2021
Definisce un classificatore basato su GDA quadratica ed effettua il training sul dataset.
clf = LinearDiscriminantAnalysis(store_covariance=True) clf.fit(X, t)
_____no_output_____
MIT
codici/.ipynb_checkpoints/gda-lin-sk-cv-checkpoint.ipynb
tvml/fo2021
Definiamo la griglia 100x100 da utilizzare per la visualizzazione delle varie distribuzioni.
# insieme delle ascisse dei punti u = np.linspace(min(X[:,0]), max(X[:,0]), 100) # insieme delle ordinate dei punti v = np.linspace(min(X[:,1]), max(X[:,1]), 100) # deriva i punti della griglia: il punto in posizione i,j nella griglia ha ascissa U(i,j) e ordinata V(i,j) U, V = np.meshgrid(u, v)
_____no_output_____
MIT
codici/.ipynb_checkpoints/gda-lin-sk-cv-checkpoint.ipynb
tvml/fo2021
Calcola sui punti della griglia le probabilità delle classi $p(x|C_0), p(x|C_1)$ e le probabilità a posteriori delle classi $p(C_0|x), p(C_1|x)$
# probabilità a posteriori delle due distribuzioni sulla griglia Z = clf.predict_proba(np.c_[U.ravel(), V.ravel()]) pp0 = Z[:, 0].reshape(U.shape) pp1 = Z[:, 1].reshape(V.shape) # rapporto tra le probabilità a posteriori delle classi per tutti i punti della griglia z=pp0/pp1 # probabilità per le due classi sulla gr...
_____no_output_____
MIT
codici/.ipynb_checkpoints/gda-lin-sk-cv-checkpoint.ipynb
tvml/fo2021
Visualizzazione della distribuzione di $p(x|C_0)$
fig = plt.figure(figsize=(16,8)) ax = fig.gca() # inserisce una rappresentazione della probabilità della classe C0 sotto forma di heatmap imshow_handle = plt.imshow(p0, origin='lower', extent=(min(X[:,0]), max(X[:,0]), min(X[:,1]), max(X[:,1])), alpha=.7) plt.contour(U, V, p0, linewidths=[.7], colors=[colors[6]]) # rap...
_____no_output_____
MIT
codici/.ipynb_checkpoints/gda-lin-sk-cv-checkpoint.ipynb
tvml/fo2021
Visualizzazione della distribuzione di $p(x|C1)$
fig = plt.figure(figsize=(16,8)) ax = fig.gca() # inserisce una rappresentazione della probabilità della classe C0 sotto forma di heatmap imshow_handle = plt.imshow(p1, origin='lower', extent=(min(X[:,0]), max(X[:,0]), min(X[:,1]), max(X[:,1])), alpha=.7) plt.contour(U, V, p1, linewidths=[.7], colors=[colors[6]]) # rap...
_____no_output_____
MIT
codici/.ipynb_checkpoints/gda-lin-sk-cv-checkpoint.ipynb
tvml/fo2021
Visualizzazione di $p(C_0|x)$
fig = plt.figure(figsize=(8,8)) ax = fig.gca() imshow_handle = plt.imshow(pp0, origin='lower', extent=(min(X[:,0]), max(X[:,0]), min(X[:,1]), max(X[:,1])), alpha=.7) ax.scatter(data[data.t==0].x1, data[data.t==0].x2, s=40, c=colors[0], alpha=.7) ax.scatter(data[data.t==1].x1, data[data.t==1].x2, s=40,c=colors[1], alpha...
_____no_output_____
MIT
codici/.ipynb_checkpoints/gda-lin-sk-cv-checkpoint.ipynb
tvml/fo2021
Visualizzazione di $p(C_1|x)$
fig = plt.figure(figsize=(8,8)) ax = fig.gca() imshow_handle = plt.imshow(pp1, origin='lower', extent=(min(X[:,0]), max(X[:,0]), min(X[:,1]), max(X[:,1])), alpha=.7) ax.scatter(data[data.t==0].x1, data[data.t==0].x2, s=40, c=colors[0], alpha=.7) ax.scatter(data[data.t==1].x1, data[data.t==1].x2, s=40,c=colors[1], alpha...
_____no_output_____
MIT
codici/.ipynb_checkpoints/gda-lin-sk-cv-checkpoint.ipynb
tvml/fo2021
Applica la cross validation (5-fold) per calcolare l'accuracy effettuando la media sui 5 valori restituiti.
print("Accuracy: {0:5.3f}".format(cross_val_score(clf, X, t, cv=5, scoring='accuracy').mean()))
Accuracy: 0.870
MIT
codici/.ipynb_checkpoints/gda-lin-sk-cv-checkpoint.ipynb
tvml/fo2021
Parte 04Nessa parte os modelos criados anteriormente serão utilizados para realizar predições. Para isso, eles devem serregistrados no TFX. Para efetuar as predições, os dados utilizados no treinamento desses modelos serão inseridosno SAVIME, o qual ficará encarregado de enviar e receber os dados para/de TFX.
import os import sys # Necessário mudar o diretório de trabalho para o nível mais acima if not 'notebooks' in os.listdir('.'): current_dir = os.path.abspath(os.getcwd()) parent_dir = os.path.dirname(current_dir) os.chdir(parent_dir) # Inserir aqui o caminho do arquivo de dados: um json contendo informaçõe...
_____no_output_____
MIT
notebooks-pt/Tutorial - Parte 04.ipynb
dnasc/savime-notebooks
A primeira etapa a ser realizada é converter os dados para um formato processável para o SAVIME.
with h5py.File(dataset_path, 'r') as in_: array = in_['real'][...] # Especificar dimensões time_series = ('time_series', range(array.shape[0])) time_step = ('time_step', range(array.shape[1])) pos_x = ('pos_x', range(array.shape[2])) pos_y = ('pos_y', range(array.shape[3])) # Remover última dimensão espúria s...
_____no_output_____
MIT
notebooks-pt/Tutorial - Parte 04.ipynb
dnasc/savime-notebooks
Também é nessário fazer a divisão do conjunto de dados de entrada em x e y. Como dito na parte anterior, cada série temporal possuí 10 instantes de tempo. Além disso, os modelos foram treinados a prever o décimo instante de tempo a partir dos nove anteriores. A critério de exemplo, selecionamos abaixo um grupo de série...
# Seleciona-se apenas um grupo para predição. chosen_model_name = data['model'] chosen_group_ix = 0 x = squeezed_array[[chosen_group_ix], :-1] y = squeezed_array[[chosen_group_ix], 1:] pc = PredictionConsumer(host=tfx_host, port=tfx_port, model_name=chosen_model_name) y_hat = pc.predict(x) anim_y = animate_heat_map(n...
_____no_output_____
MIT
notebooks-pt/Tutorial - Parte 04.ipynb
dnasc/savime-notebooks
Abaixo verificamos se os dados foram corretamente registrados no SAVIME.
with pysavime.Client(host=savime_host, port=savime_port, raise_silent_error=True) as client: response = client.execute(pysavime.operator.select(tar))[0] is_the_same = np.isclose(response.attrs['temperature'].reshape(squeezed_array.shape),squeezed_array).all() print('Checagem:', is_the_same)
Checagem: True
MIT
notebooks-pt/Tutorial - Parte 04.ipynb
dnasc/savime-notebooks
O próximo passo é executar o comando PREDICT.
# Vamos selecionar apenas os 9 primeiros instantes de tempo cmd = pysavime.operator.subset(tar, time_step_dim.name, 0, 8) # Definir as dimensões de entrada e saída do nosso modelo input_dims_spec = [(group_dim.name, num_groups), (time_step_dim.name, num_time_steps - 1), (pos_x_...
_____no_output_____
MIT
notebooks-pt/Tutorial - Parte 04.ipynb
dnasc/savime-notebooks
Convolutional Neural Networks: ApplicationWelcome to Course 4's second assignment! In this notebook, you will:- Implement helper functions that you will use when implementing a TensorFlow model- Implement a fully functioning ConvNet using TensorFlow **After this assignment you will be able to:**- Build and train a Con...
import math import numpy as np import h5py import matplotlib.pyplot as plt import scipy from PIL import Image from scipy import ndimage import tensorflow as tf from tensorflow.python.framework import ops from cnn_utils import * %matplotlib inline np.random.seed(1)
_____no_output_____
MIT
Convolution_model_Application_v1a.ipynb
Yfyangd/Deep_Learning
Run the next cell to load the "SIGNS" dataset you are going to use.
# Loading the data (signs) X_train_orig, Y_train_orig, X_test_orig, Y_test_orig, classes = load_dataset()
_____no_output_____
MIT
Convolution_model_Application_v1a.ipynb
Yfyangd/Deep_Learning
As a reminder, the SIGNS dataset is a collection of 6 signs representing numbers from 0 to 5.The next cell will show you an example of a labelled image in the dataset. Feel free to change the value of `index` below and re-run to see different examples.
# Example of a picture index = 6 plt.imshow(X_train_orig[index]) print ("y = " + str(np.squeeze(Y_train_orig[:, index])))
y = 2
MIT
Convolution_model_Application_v1a.ipynb
Yfyangd/Deep_Learning
In Course 2, you had built a fully-connected network for this dataset. But since this is an image dataset, it is more natural to apply a ConvNet to it.To get started, let's examine the shapes of your data.
X_train = X_train_orig/255. X_test = X_test_orig/255. Y_train = convert_to_one_hot(Y_train_orig, 6).T Y_test = convert_to_one_hot(Y_test_orig, 6).T print ("number of training examples = " + str(X_train.shape[0])) print ("number of test examples = " + str(X_test.shape[0])) print ("X_train shape: " + str(X_train.shape)) ...
number of training examples = 1080 number of test examples = 120 X_train shape: (1080, 64, 64, 3) Y_train shape: (1080, 6) X_test shape: (120, 64, 64, 3) Y_test shape: (120, 6)
MIT
Convolution_model_Application_v1a.ipynb
Yfyangd/Deep_Learning
1.1 - Create placeholdersTensorFlow requires that you create placeholders for the input data that will be fed into the model when running the session.**Exercise**: Implement the function below to create placeholders for the input image X and the output Y. You should not define the number of training examples for the m...
# GRADED FUNCTION: create_placeholders def create_placeholders(n_H0, n_W0, n_C0, n_y): """ Creates the placeholders for the tensorflow session. Arguments: n_H0 -- scalar, height of an input image n_W0 -- scalar, width of an input image n_C0 -- scalar, number of channels of the input n_...
X = Tensor("Placeholder:0", shape=(?, 64, 64, 3), dtype=float32) Y = Tensor("Placeholder_1:0", shape=(?, 6), dtype=float32)
MIT
Convolution_model_Application_v1a.ipynb
Yfyangd/Deep_Learning
**Expected Output** X = Tensor("Placeholder:0", shape=(?, 64, 64, 3), dtype=float32) Y = Tensor("Placeholder_1:0", shape=(?, 6), dtype=float32) 1.2 - Initialize parametersYou will initialize weights/filters $W1$ and $W2$ using `tf.contrib.layers.xavier_initializer(seed = 0)`. You don't need to worry about bias ...
# GRADED FUNCTION: initialize_parameters def initialize_parameters(): """ Initializes weight parameters to build a neural network with tensorflow. The shapes are: W1 : [4, 4, 3, 8] W2 : [2, 2, 8, 16] Note that we will hard code the shape values in the functio...
W1[1,1,1] = [ 0.00131723 0.14176141 -0.04434952 0.09197326 0.14984085 -0.03514394 -0.06847463 0.05245192] W1.shape: (4, 4, 3, 8) W2[1,1,1] = [-0.08566415 0.17750949 0.11974221 0.16773748 -0.0830943 -0.08058 -0.00577033 -0.14643836 0.24162132 -0.05857408 -0.19055021 0.1345228 -0.22779644 -0.1601823 -0....
MIT
Convolution_model_Application_v1a.ipynb
Yfyangd/Deep_Learning
** Expected Output:**```W1[1,1,1] = [ 0.00131723 0.14176141 -0.04434952 0.09197326 0.14984085 -0.03514394 -0.06847463 0.05245192]W1.shape: (4, 4, 3, 8)W2[1,1,1] = [-0.08566415 0.17750949 0.11974221 0.16773748 -0.0830943 -0.08058 -0.00577033 -0.14643836 0.24162132 -0.05857408 -0.19055021 0.1345228 -0.22779644 ...
# GRADED FUNCTION: forward_propagation def forward_propagation(X, parameters): """ Implements the forward propagation for the model: CONV2D -> RELU -> MAXPOOL -> CONV2D -> RELU -> MAXPOOL -> FLATTEN -> FULLYCONNECTED Note that for simplicity and grading purposes, we'll hard-code some values su...
Z3 = [[-0.44670227 -1.57208765 -1.53049231 -2.31013036 -1.29104376 0.46852064] [-0.17601591 -1.57972014 -1.4737016 -2.61672091 -1.00810647 0.5747785 ]]
MIT
Convolution_model_Application_v1a.ipynb
Yfyangd/Deep_Learning
**Expected Output**:```Z3 = [[-0.44670227 -1.57208765 -1.53049231 -2.31013036 -1.29104376 0.46852064] [-0.17601591 -1.57972014 -1.4737016 -2.61672091 -1.00810647 0.5747785 ]]``` 1.4 - Compute costImplement the compute cost function below. Remember that the cost function helps the neural network see how much the mod...
# GRADED FUNCTION: compute_cost def compute_cost(Z3, Y): """ Computes the cost Arguments: Z3 -- output of forward propagation (output of the last LINEAR unit), of shape (number of examples, 6) Y -- "true" labels vector placeholder, same shape as Z3 Returns: cost - Tensor of the c...
cost = 2.91034
MIT
Convolution_model_Application_v1a.ipynb
Yfyangd/Deep_Learning
**Expected Output**: ```cost = 2.91034``` 1.5 Model Finally you will merge the helper functions you implemented above to build a model. You will train it on the SIGNS dataset. **Exercise**: Complete the function below. The model below should:- create placeholders- initialize parameters- forward propagate- compute the ...
# GRADED FUNCTION: model def model(X_train, Y_train, X_test, Y_test, learning_rate = 0.009, num_epochs = 100, minibatch_size = 64, print_cost = True): """ Implements a three-layer ConvNet in Tensorflow: CONV2D -> RELU -> MAXPOOL -> CONV2D -> RELU -> MAXPOOL -> FLATTEN -> FULLYCONNECTED A...
_____no_output_____
MIT
Convolution_model_Application_v1a.ipynb
Yfyangd/Deep_Learning
Run the following cell to train your model for 100 epochs. Check if your cost after epoch 0 and 5 matches our output. If not, stop the cell and go back to your code!
_, _, parameters = model(X_train, Y_train, X_test, Y_test)
Cost after epoch 0: 1.917929 Cost after epoch 5: 1.506757 Cost after epoch 10: 0.955359 Cost after epoch 15: 0.845802 Cost after epoch 20: 0.701174 Cost after epoch 25: 0.571977 Cost after epoch 30: 0.518435 Cost after epoch 35: 0.495806 Cost after epoch 40: 0.429827 Cost after epoch 45: 0.407291 Cost after epoch 50: 0...
MIT
Convolution_model_Application_v1a.ipynb
Yfyangd/Deep_Learning
**Expected output**: although it may not match perfectly, your expected output should be close to ours and your cost value should decrease. **Cost after epoch 0 =** 1.917929 **Cost after epoch 5 =** 1.506757 **Train Accuracy =** 0.940741 ...
fname = "images/thumbs_up.jpg" image = np.array(ndimage.imread(fname, flatten=False)) my_image = scipy.misc.imresize(image, size=(64,64)) plt.imshow(my_image)
_____no_output_____
MIT
Convolution_model_Application_v1a.ipynb
Yfyangd/Deep_Learning
Imports
import requests import getpass import pickle import io import time import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import numpy as np import itertools
_____no_output_____
MIT
data/GenesisGrabber.ipynb
yoki31/visualize
Loginhttps://www.statistikdaten.bayern.de/genesis/online?Menu=Anmeldungabreadcrumb
username = input() password = getpass.getpass()
_____no_output_____
MIT
data/GenesisGrabber.ipynb
yoki31/visualize
Test login
class GenesisApi: def __init__(self, username, password, polling_rate=5): self.username = username self.password = password self.polling_rate = polling_rate self.__base_url = 'https://www.statistikdaten.bayern.de/genesisWS/rest/2020/' self.__base_params...
_____no_output_____
MIT
data/GenesisGrabber.ipynb
yoki31/visualize
Download dataNote: This takes a long time
responses_demographic = {} for year in range(1980, 2020 + 1): print('Requesting table for the year ' + str(year)) response = genesis.get_table('12411-003r', year) print('Got data') responses_demographic[str(year)] = response responses_area = {} # 33111-201r 1980, 1984, 1988, 1992, 1996, 2000, 2004, 20...
_____no_output_____
MIT
data/GenesisGrabber.ipynb
yoki31/visualize
Convert to DataFrame
def convert_to_dataframe(response, start_at_line, date_line, header_line): raw_content = response['Object']['Content'] content = raw_content.split('\n', start_at_line) date = content[date_line].split(';',1)[0] csv = io.StringIO(content[header_line] + '\n' + content[start_at_line].split('\n__________', 1...
_____no_output_____
MIT
data/GenesisGrabber.ipynb
yoki31/visualize
Demographic
dfs = list() for year, response in responses_demographic.items(): df = convert_to_dataframe(response, start_at_line=6, date_line=4, header_line=5) dfs.append(df) df_demographic = pd.concat(dfs, axis=0, ignore_index=True) column_names = df_demographic.columns.values column_names[0] = 'AGS' column_names[1] = 'G...
_____no_output_____
MIT
data/GenesisGrabber.ipynb
yoki31/visualize
Area
dfs = list() for year, response in responses_area.items(): df = convert_to_dataframe(response, start_at_line=10, date_line=5, header_line=8) column_names = df.columns.values column_names[0] = 'AGS' column_names[1] = 'Gemeinde' df.columns = column_names for column_name in column_names[2: len(co...
_____no_output_____
MIT
data/GenesisGrabber.ipynb
yoki31/visualize
Combined
df_all = pd.merge(df_area, df_demographic, how='left', on=['AGS', 'Gemeinde', 'date']) df_all.rename(columns={'Insgesamt_x':'Insgesamt Fläche', 'Insgesamt_y':'Insgesamt Bewohner'}, inplace=True) df_all
_____no_output_____
MIT
data/GenesisGrabber.ipynb
yoki31/visualize
Save and load data
df_demographic.to_pickle('df_demographic.pickle') df_area.to_pickle('df_area.pickle') with open('responses_demographic.pickle', 'wb') as f: pickle.dump(responses_demographic, f, pickle.HIGHEST_PROTOCOL) with open('responses_area.pickle', 'wb') as f: pickle.dump(responses_area, f, pickle.HIGHEST_PROTOCOL) df_d...
_____no_output_____
MIT
data/GenesisGrabber.ipynb
yoki31/visualize
Categorize
categories = { "living": [ "Wohnen", "11000 Wohnbaufläche", ], "industry": [ "Gewerbe, Industrie", "Betriebsfläche (ohne Abbauland)", "Abbauland", "12100 Industrie und Gewerbe", "12200 Handel und Dienstleistung", "12300 Versorgungsanlage", ...
_____no_output_____
MIT
data/GenesisGrabber.ipynb
yoki31/visualize
Rename columns
df_area.rename(columns={"Insgesamt": "total", "Gemeinde": "municipality"}, inplace=True)
_____no_output_____
MIT
data/GenesisGrabber.ipynb
yoki31/visualize
Filter unused municipalities
df_area = df_area[df_area["AGS"] <= 9999]
_____no_output_____
MIT
data/GenesisGrabber.ipynb
yoki31/visualize
Merge demographic data
df_area df_demographic.drop(["männlich", "weiblich"], axis=1, inplace=True) df_demographic.rename(columns={"Gemeinde": "municipality", "Insgesamt": "demographic"}, inplace=True) df_area = pd.merge(df_area, df_demographic, how='left', on=['AGS', 'municipality', 'date'])
_____no_output_____
MIT
data/GenesisGrabber.ipynb
yoki31/visualize
Export to JSON
df_area df_export = df_area.copy() df_export['date'] = df_export['date'].dt.strftime('%d.%m.%Y') with open("data.json", "w", encoding="utf-8") as f: df_export.to_json(f, orient="records", force_ascii=False)
_____no_output_____
MIT
data/GenesisGrabber.ipynb
yoki31/visualize
Basic graphs
f, ax = plt.subplots(figsize=(7, 7)) ax.set(yscale="log") g = sns.lineplot(data=df_demographic[(df_demographic['Gemeinde']=='Friedberg, St') | (df_demographic['Gemeinde']=='Augsburg (Krfr.St)') | (df_demographic['Gemeinde']=='Garmisch-Partenkirchen, M')], style='Gemeinde', x='date', y='Insgesamt', ax=ax) g.set_title('E...
_____no_output_____
MIT
data/GenesisGrabber.ipynb
yoki31/visualize
Import data
pd.set_option('display.max_rows', 500) pd.set_option('display.max_columns', 38) df = pd.read_csv('zar_dataset.csv') df.info() df.head() df.describe()
_____no_output_____
MIT
BNN Model.ipynb
mdtycho/Zar-Currency-Prediction-Model
Create Labels For Data, Classification and Regression Labels
from sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split scaler = StandardScaler() df['target_clf'] = df['target_return'].apply(lambda x: float(x/abs(x)) if x!=0 else -1) df['target_clf'] = df['target_clf'].apply(lambda x: x if x==1 else 0) df.rename(columns = {'target_retu...
_____no_output_____
MIT
BNN Model.ipynb
mdtycho/Zar-Currency-Prediction-Model
Function for Feeding Data In Batches
def next_batch(num, data, labels): ''' Return a total of `num` random samples and labels. ''' idx = np.arange(0 , len(data)) np.random.shuffle(idx) idx = idx[:num] data_shuffle = [data[ i] for i in idx] labels_shuffle = [labels[ i] for i in idx] return np.asarray(data_shuffle), np....
_____no_output_____
MIT
BNN Model.ipynb
mdtycho/Zar-Currency-Prediction-Model
Build Bayesian Model
N = 100 # number of rows in a minibatch. D = 36 # number of features. K = 2 # number of classes. # Create a placeholder to hold the data (in minibatches) in a TensorFlow graph. x = tf.placeholder(tf.float32, [None, D]) # Normal(0,1) priors for the variables. Note that the syntax assumes TensorFlow 1.1. w = Norma...
_____no_output_____
MIT
BNN Model.ipynb
mdtycho/Zar-Currency-Prediction-Model
Compute The Accuracy Distribution For The Bayesian Neural Net
# Compute the accuracy of the model. # For each sample we compute the predicted class and compare with the test labels. # Predicted class is defined as the one which as maximum proability. # We perform this test for each (w,b) in the posterior giving us a set of accuracies # Finally we make a histogram of accuracies f...
_____no_output_____
MIT
BNN Model.ipynb
mdtycho/Zar-Currency-Prediction-Model
Test The Model On Brazil Data, We Should Get A wider Distribution Of Accuracies Brazil
brazil = pd.read_csv('brazil_clean.csv') brazil.head() brazil.info() brazil['Date'] = pd.to_datetime(brazil['Date']) brazil.head() brazil.info() brazil['target_cl'] = brazil['target_cl'].apply(lambda x: x if x==1 else 0) brazil.rename(columns = {'target_return':'target_reg'}, inplace = True) brazil.head() brazil.descri...
_____no_output_____
MIT
BNN Model.ipynb
mdtycho/Zar-Currency-Prediction-Model
Train your first modelThis is the second of our [beginner tutorial series](https://github.com/deepjavalibrary/djl/tree/master/jupyter/tutorial) that will take you through creating, training, and running inference on a neural network. In this tutorial, you will learn how to train an image classification model that can ...
// Add the snapshot repository to get the DJL snapshot artifacts // %mavenRepo snapshots https://oss.sonatype.org/content/repositories/snapshots/ // Add the maven dependencies %maven ai.djl:api:0.17.0 %maven ai.djl:basicdataset:0.17.0 %maven ai.djl:model-zoo:0.17.0 %maven ai.djl.mxnet:mxnet-engine:0.17.0 %maven org.sl...
_____no_output_____
Apache-2.0
jupyter/tutorial/02_train_your_first_model.ipynb
dandansamax/djl
Step 1: Prepare MNIST dataset for trainingIn order to train, you must create a [Dataset class](https://javadoc.io/static/ai.djl/api/0.17.0/index.html?ai/djl/training/dataset/Dataset.html) to contain your training data. A dataset is a collection of sample input/output pairs for the function represented by your neural n...
int batchSize = 32; Mnist mnist = Mnist.builder().setSampling(batchSize, true).build(); mnist.prepare(new ProgressBar());
_____no_output_____
Apache-2.0
jupyter/tutorial/02_train_your_first_model.ipynb
dandansamax/djl
Step 2: Create your ModelNext we will build a model. A [Model](https://javadoc.io/static/ai.djl/api/0.17.0/index.html?ai/djl/Model.html) contains a neural network [Block](https://javadoc.io/static/ai.djl/api/0.17.0/index.html?ai/djl/nn/Block.html) along with additional artifacts used for the training process. It posse...
Model model = Model.newInstance("mlp"); model.setBlock(new Mlp(28 * 28, 10, new int[] {128, 64}));
_____no_output_____
Apache-2.0
jupyter/tutorial/02_train_your_first_model.ipynb
dandansamax/djl
Step 3: Create a TrainerNow, you can create a [`Trainer`](https://javadoc.io/static/ai.djl/api/0.17.0/index.html?ai/djl/training/Trainer.html) to train your model. The trainer is the main class to orchestrate the training process. Usually, they will be opened using a try-with-resources and closed after training is ove...
DefaultTrainingConfig config = new DefaultTrainingConfig(Loss.softmaxCrossEntropyLoss()) //softmaxCrossEntropyLoss is a standard loss for classification problems .addEvaluator(new Accuracy()) // Use accuracy so we humans can understand how accurate the model is .addTrainingListeners(TrainingListener.Default...
_____no_output_____
Apache-2.0
jupyter/tutorial/02_train_your_first_model.ipynb
dandansamax/djl
Step 5: Initialize TrainingBefore training your model, you have to initialize all of the parameters with starting values. You can use the trainer for this initialization by passing in the input shape.* The first axis of the input shape is the batch size. This won't impact the parameter initialization, so you can use 1...
trainer.initialize(new Shape(1, 28 * 28));
_____no_output_____
Apache-2.0
jupyter/tutorial/02_train_your_first_model.ipynb
dandansamax/djl
Step 6: Train your modelNow, we can train the model.When training, it is usually organized into epochs where each epoch trains the model on each item in the dataset once. It is slightly faster than training randomly.Then, we will use the EasyTrain to, as the name promises, make the training easy. If you want to see mo...
// Deep learning is typically trained in epochs where each epoch trains the model on each item in the dataset once. int epoch = 2; EasyTrain.fit(trainer, epoch, mnist, null);
_____no_output_____
Apache-2.0
jupyter/tutorial/02_train_your_first_model.ipynb
dandansamax/djl
Step 7: Save your modelOnce your model is trained, you should save it so that it can be reloaded later. You can also add metadata to it such as training accuracy, number of epochs trained, etc that can be used when loading the model or when examining it.
Path modelDir = Paths.get("build/mlp"); Files.createDirectories(modelDir); model.setProperty("Epoch", String.valueOf(epoch)); model.save(modelDir, "mlp"); model
_____no_output_____
Apache-2.0
jupyter/tutorial/02_train_your_first_model.ipynb
dandansamax/djl
HSV feature
train_x = [] train_y = [] train_dir = os.path.join(dest, "random_forest_train") for img in os.listdir(train_dir): img_id = int(img.split(".")[0]) train_y.append(int(img_id2class[img_id])) train_x.append(extract_hist_feature(cv2.imread(os.path.join(train_dir, img)), rgb=False)) classifier = RandomForestClass...
_____no_output_____
MIT
random_forest/color.ipynb
den8972/228
RGB feature
train_x = [] train_y = [] train_dir = os.path.join(dest, "random_forest_train") for img in os.listdir(train_dir): img_id = int(img.split(".")[0]) train_y.append(int(img_id2class[img_id])) train_x.append(extract_hist_feature(cv2.imread(os.path.join(train_dir, img)), rgb=True)) classifier = RandomForestClassi...
_____no_output_____
MIT
random_forest/color.ipynb
den8972/228
Transfer LearningMost of the time you won't want to train a whole convolutional network yourself. Modern ConvNets training on huge datasets like ImageNet take weeks on multiple GPUs. Instead, most people use a pretrained network either as a fixed feature extractor, or as an initial network to fine tune. In this notebo...
from tensorflow.python.client import device_lib print(device_lib.list_local_devices()) print(device_lib) from urllib.request import urlretrieve from os.path import isfile, isdir from tqdm import tqdm vgg_dir = 'tensorflow_vgg/' # Make sure vgg exists if not isdir(vgg_dir): raise Exception("VGG directory doesn't e...
Parameter file already exists!
MIT
transfer-learning/Transfer_Learning_Solution.ipynb
freedomkwok/deep-learning
Flower powerHere we'll be using VGGNet to classify images of flowers. To get the flower dataset, run the cell below. This dataset comes from the [TensorFlow inception tutorial](https://www.tensorflow.org/tutorials/image_retraining).
import tarfile dataset_folder_path = 'flower_photos' class DLProgress(tqdm): last_block = 0 def hook(self, block_num=1, block_size=1, total_size=None): self.total = total_size self.update((block_num - self.last_block) * block_size) self.last_block = block_num if not isfile('flower_ph...
_____no_output_____
MIT
transfer-learning/Transfer_Learning_Solution.ipynb
freedomkwok/deep-learning
ConvNet CodesBelow, we'll run through all the images in our dataset and get codes for each of them. That is, we'll run the images through the VGGNet convolutional layers and record the values of the first fully connected layer. We can then write these to a file for later when we build our own classifier.Here we're usi...
import os import numpy as np import tensorflow as tf from tensorflow_vgg import vgg16 from tensorflow_vgg import utils data_dir = 'flower_photos/' contents = os.listdir(data_dir) classes = [each for each in contents if os.path.isdir(data_dir + each)]
_____no_output_____
MIT
transfer-learning/Transfer_Learning_Solution.ipynb
freedomkwok/deep-learning
Below I'm running images through the VGG network in batches.
# Set the batch size higher if you can fit in in your GPU memory batch_size = 10 codes_list = [] labels = [] batch = [] codes = None with tf.Session() as sess: vgg = vgg16.Vgg16() input_ = tf.placeholder(tf.float32, [None, 224, 224, 3]) with tf.name_scope("content_vgg"): vgg.build(input_) for...
_____no_output_____
MIT
transfer-learning/Transfer_Learning_Solution.ipynb
freedomkwok/deep-learning
Building the ClassifierNow that we have codes for all the images, we can build a simple classifier on top of them. The codes behave just like normal input into a simple neural network. Below I'm going to have you do most of the work.
# read codes and labels from file import csv with open('labels') as f: reader = csv.reader(f, delimiter='\n') labels = np.array([each for each in reader if len(each) > 0]).squeeze() with open('codes') as f: codes = np.fromfile(f, dtype=np.float32) codes = codes.reshape((len(labels), -1))
_____no_output_____
MIT
transfer-learning/Transfer_Learning_Solution.ipynb
freedomkwok/deep-learning
Data prepAs usual, now we need to one-hot encode our labels and create validation/test sets. First up, creating our labels!> **Exercise:** From scikit-learn, use [LabelBinarizer](http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.LabelBinarizer.html) to create one-hot encoded vectors from the label...
codes from sklearn.preprocessing import LabelBinarizer lb = LabelBinarizer() lb.fit(labels) labels_vecs = lb.transform(labels) labels_vecs
_____no_output_____
MIT
transfer-learning/Transfer_Learning_Solution.ipynb
freedomkwok/deep-learning
Now you'll want to create your training, validation, and test sets. An important thing to note here is that our labels and data aren't randomized yet. We'll want to shuffle our data so the validation and test sets contain data from all classes. Otherwise, you could end up with testing sets that are all one class. Typic...
from sklearn.model_selection import StratifiedShuffleSplit ss = StratifiedShuffleSplit(n_splits=1, test_size=0.2) train_idx, val_idx = next(ss.split(codes, labels_vecs)) half_val_len = int(len(val_idx)/2) val_idx, test_idx = val_idx[:half_val_len], val_idx[half_val_len:] train_x, train_y = codes[train_idx], labels_...
Train shapes (x, y): (2936, 4096) (2936, 5) Validation shapes (x, y): (367, 4096) (367, 5) Test shapes (x, y): (367, 4096) (367, 5)
MIT
transfer-learning/Transfer_Learning_Solution.ipynb
freedomkwok/deep-learning
If you did it right, you should see these sizes for the training sets:```Train shapes (x, y): (2936, 4096) (2936, 5)Validation shapes (x, y): (367, 4096) (367, 5)Test shapes (x, y): (367, 4096) (367, 5)``` Classifier layersOnce you have the convolutional codes, you just need to build a classfier from some fully connec...
inputs_ = tf.placeholder(tf.float32, shape=[None, codes.shape[1]]) labels_ = tf.placeholder(tf.int64, shape=[None, labels_vecs.shape[1]]) fc = tf.contrib.layers.fully_connected(inputs_, 256) logits = tf.contrib.layers.fully_connected(fc, labels_vecs.shape[1], activation_fn=None) cross_entropy = tf.nn.softmax_cros...
_____no_output_____
MIT
transfer-learning/Transfer_Learning_Solution.ipynb
freedomkwok/deep-learning
Batches!Here is just a simple way to do batches. I've written it so that it includes all the data. Sometimes you'll throw out some data at the end to make sure you have full batches. Here I just extend the last batch to include the remaining data.
def get_batches(x, y, n_batches=10): """ Return a generator that yields batches from arrays x and y. """ batch_size = len(x)//n_batches for ii in range(0, n_batches*batch_size, batch_size): # If we're not on the last batch, grab data with size batch_size if ii != (n_batches-1)*batch_siz...
_____no_output_____
MIT
transfer-learning/Transfer_Learning_Solution.ipynb
freedomkwok/deep-learning
TrainingHere, we'll train the network.> **Exercise:** So far we've been providing the training code for you. Here, I'm going to give you a bit more of a challenge and have you write the code to train the network. Of course, you'll be able to see my solution if you need help.
epochs = 10 iteration = 0 saver = tf.train.Saver() with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for e in range(epochs): for x, y in get_batches(train_x, train_y): feed = {inputs_: x, labels_: y} loss, _ = sess.run([cost, optimize...
_____no_output_____
MIT
transfer-learning/Transfer_Learning_Solution.ipynb
freedomkwok/deep-learning
TestingBelow you see the test accuracy. You can also see the predictions returned for images.
with tf.Session() as sess: saver.restore(sess, tf.train.latest_checkpoint('checkpoints')) feed = {inputs_: test_x, labels_: test_y} test_acc = sess.run(accuracy, feed_dict=feed) print("Test accuracy: {:.4f}".format(test_acc)) %matplotlib inline import matplotlib.pyplot as plt from scip...
_____no_output_____
MIT
transfer-learning/Transfer_Learning_Solution.ipynb
freedomkwok/deep-learning
Below, feel free to choose images and see how the trained classifier predicts the flowers in them.
test_img_path = 'flower_photos/roses/10894627425_ec76bbc757_n.jpg' test_img = imread(test_img_path) plt.imshow(test_img) # Run this cell if you don't have a vgg graph built with tf.Session() as sess: input_ = tf.placeholder(tf.float32, [None, 224, 224, 3]) vgg = vgg16.Vgg16() vgg.build(input_) with tf.Sessi...
_____no_output_____
MIT
transfer-learning/Transfer_Learning_Solution.ipynb
freedomkwok/deep-learning
Set up AWS Panorama development environment on SageMaker NotebookThis notebook installs dependencies required for AWS Panorama application development. Run following cells just once, before starting labs.
%pip install panoramacli %pip install mxnet %pip install gluoncv !./scripts/install-docker.sh # for CPU build !./scripts/install-dlr.sh # for p2/p3/g4 instance, we could use pre-built package to skip long building time #%pip install https://neo-ai-dlr-release.s3-us-west-2.amazonaws.com/v1.10.0/gpu/dlr-1.10.0-py3-none-...
_____no_output_____
MIT-0
setup-sm.ipynb
aws-samples/aws-panorama-immersion-day
Transfer learning with Tensorflow在这个Notebook当中,我们将介绍如何实用Tensorflow框架实现迁移学习。简单的来说,迁移学习就是利用已经训练好的模型中学习到的特征(Features),再根据用户需要添加额外的网络层,进行快速的针对新的特定的数据集的模型训练。由于这样生成的模型大部分的模型参数已经训练好并且已经学习到一定数量的hidden features,在提供新的数据集的时候再进行训练就能有效利用已学习到的知识来进行预测。本notebook所使用的预训练好的模型是MobileNet V2,其具体的原理就留给负责这部分的同学在后续具体介绍。我们当前只需要了解其大致的网络结构即可(结构如...
import matplotlib.pyplot as plt import numpy as np import os import tensorflow as tf from tensorflow.keras.preprocessing import image_dataset_from_directory
_____no_output_____
MIT
TF-transfer.ipynb
HAXRD/TF2vsPTH
1. 数据预处理 数据集分组在这里我们数据集已经按照路径分为Train集和Validation集。
PATH = os.path.join('./data', 'cats_and_dogs_filtered') train_dir = os.path.join(PATH, 'train') validation_dir = os.path.join(PATH, 'validation') BATCH_SIZE = 32 IMG_SIZE = (160, 160) train_dataset = image_dataset_from_directory(train_dir, shuffle=True, ...
Found 2000 files belonging to 2 classes. Found 1000 files belonging to 2 classes.
MIT
TF-transfer.ipynb
HAXRD/TF2vsPTH
查看数据集中的样本
class_names = train_dataset.class_names plt.figure(figsize=(10, 10)) for images, labels in train_dataset.take(1): for i in range(9): ax = plt.subplot(3, 3, i+1) plt.imshow(images[i].numpy().astype("uint8")) plt.title(class_names[labels[i]]) plt.axis("off")
_____no_output_____
MIT
TF-transfer.ipynb
HAXRD/TF2vsPTH
将图片像素值归一化
rescale_input = tf.keras.layers.experimental.preprocessing.Rescaling(1./255, offset=0)
_____no_output_____
MIT
TF-transfer.ipynb
HAXRD/TF2vsPTH
2.组合模型 载入预训练好的模型(MobileNet-v2)
IMG_SHAPE = IMG_SIZE + (3,) base_model = tf.keras.applications.MobileNetV2(input_shape=IMG_SHAPE, include_top=False, weights='imagenet') image_batch, label_batch = next(iter(train_dataset)) feature_batch = base_model(image_bat...
(32, 5, 5, 1280)
MIT
TF-transfer.ipynb
HAXRD/TF2vsPTH
特征提取(Feature Extraction)
# Freeze the MobileNet base_model.trainable = False base_model.summary() global_average_layer = tf.keras.layers.GlobalAveragePooling2D() feature_batch_average = global_average_layer(feature_batch) print(feature_batch_average.shape) prediction_layer = tf.keras.layers.Dense(1) prediction_batch = prediction_layer(feature_...
(32, 1)
MIT
TF-transfer.ipynb
HAXRD/TF2vsPTH
将上述的各个层集合成新的 Model
inputs = tf.keras.Input(shape=(160, 160, 3)) x = rescale_input(inputs) x = base_model(x, training=False) x = tf.keras.layers.Dropout(0.2)(x) outputs = prediction_layer(x) model = tf.keras.Model(inputs, outputs)
_____no_output_____
MIT
TF-transfer.ipynb
HAXRD/TF2vsPTH
编译模型
lr = 0.0001 model.compile(optimizer=tf.keras.optimizers.Adam(lr=lr), loss=tf.keras.losses.BinaryCrossentropy(from_logits=True), metrics='accuracy') model.summary()
Model: "model_1" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= input_3 (InputLayer) [(None, 160, 160, 3)] 0 _______________________________________...
MIT
TF-transfer.ipynb
HAXRD/TF2vsPTH
3.训练模型 迁移学习后的Validation准确率
epochs = 10 history = model.fit(train_dataset, epochs=initial_epochs, validation_data=validation_dataset)
Epoch 1/10 63/63 [==============================] - 33s 501ms/step - loss: 0.6727 - accuracy: 0.5925 - val_loss: 0.5018 - val_accuracy: 0.7060 Epoch 2/10 63/63 [==============================] - 23s 360ms/step - loss: 0.4419 - accuracy: 0.7635 - val_loss: 0.3507 - val_accuracy: 0.8390 Epoch 3/10 63/63 [================...
MIT
TF-transfer.ipynb
HAXRD/TF2vsPTH
学习曲线
acc = history.history['accuracy'] val_acc = history.history['val_accuracy'] loss = history.history['loss'] val_loss = history.history['val_loss'] plt.figure(figsize=(8, 8)) plt.subplot(2, 1, 1) plt.plot(acc, label='Training Accuracy') plt.plot(val_acc, label='Validation Accuracy') plt.legend(loc='lower right') plt.yl...
_____no_output_____
MIT
TF-transfer.ipynb
HAXRD/TF2vsPTH
基本程序设计- 一切代码输入,请使用英文输入法 编写一个简单的程序- 圆公式面积: area = radius \* radius \* 3.1415 在Python里面不需要定义数据的类型 控制台的读取与输入- input 输入进去的是字符串- eval - 在jupyter用shift + tab 键可以跳出解释文档 变量命名的规范- 由字母、数字、下划线构成- 不能以数字开头 \*- 标识符不能是关键词(实际上是可以强制改变的,但是对于代码规范而言是极其不适合)- 可以是任意长度- 驼峰式命名 变量、赋值语句和赋值表达式- 变量: 通俗理解为可以变化的量- x = 2 \* x + 1 在数学中是一个方程,而在语言...
C=input() F=float((9/5))*float(C)+32 print(F)
43 109.4
Apache-2.0
7.16.ipynb
liangfhaott3/python
- 2
r=input() h=input() S=float(r)**2*3.14 V=float(S)*float(h) print('底面积为:%.2f'%S) print('体积为:%.2f'%V)
5.5 12 底面积为:94.98 体积为:1139.82
Apache-2.0
7.16.ipynb
liangfhaott3/python
- 3
feet=input() meters=float(feet)*0.305 print(meters)
16.5 5.0325
Apache-2.0
7.16.ipynb
liangfhaott3/python
- 4
k=input() t1=input() t2=input() q=float(k)*(float(t2)-float(t1))*4184 print(q)
55.5 3.5 10.5 1625484.0
Apache-2.0
7.16.ipynb
liangfhaott3/python
- 5
ce=input() nll=input() lx=float(ce)*(float(nll)/1200) print('%.5f'%lx)
1000 3.5 2.91667
Apache-2.0
7.16.ipynb
liangfhaott3/python
- 6
v0=input() v1=input() t=input() pj=(float(v1)-float(v0))/float(t) print('%.4f'%pj)
5.5 50.9 4.5 10.0889
Apache-2.0
7.16.ipynb
liangfhaott3/python
- 7 进阶
amout=input() money=0 for i in range(6): money=(float(amout)+float(money))*(1+0.00417) print('%.2f'%money)
100 608.82
Apache-2.0
7.16.ipynb
liangfhaott3/python
- 8 进阶
number=int(input()) if (number>1000)or (number<=0): print('false') else: gewei=number%10 shiwei=(number//10)%10 baiwei=number//100 sum=gewei+shiwei+baiwei print(sum)
999 27
Apache-2.0
7.16.ipynb
liangfhaott3/python
PTN TemplateThis notebook serves as a template for single dataset PTN experiments It can be run on its own by setting STANDALONE to True (do a find for "STANDALONE" to see where) But it is intended to be executed as part of a *papermill.py script. See any of the experimentes with a papermill script to get started ...
%load_ext autoreload %autoreload 2 %matplotlib inline import os, json, sys, time, random import numpy as np import torch from torch.optim import Adam from easydict import EasyDict import matplotlib.pyplot as plt from steves_models.steves_ptn import Steves_Prototypical_Network from steves_utils.lazy_iterable_wr...
_____no_output_____
MIT
experiments/tuned_1v2/oracle.run1/trials/2/trial.ipynb
stevester94/csc500-notebooks
Required ParametersThese are allowed parameters, not defaultsEach of these values need to be present in the injected parameters (the notebook will raise an exception if they are not present)Papermill uses the cell tag "parameters" to inject the real parameters below this cell.Enable tags to see what I mean
required_parameters = { "experiment_name", "lr", "device", "seed", "dataset_seed", "labels_source", "labels_target", "domains_source", "domains_target", "num_examples_per_domain_per_label_source", "num_examples_per_domain_per_label_target", "n_shot", "n_way", "n_q...
_____no_output_____
MIT
experiments/tuned_1v2/oracle.run1/trials/2/trial.ipynb
stevester94/csc500-notebooks
mentions of facebook
# Search for all tweets # public_tweets = api.search(target_term, count=300, result_type="recent") # Twitter API Keys consumer_key = consumer_key consumer_secret = consumer_secret access_token = access_token access_token_secret = access_token_secret # Setup Tweepy API Authentication auth = tweepy.OAuthHandler(consumer...
Fri Jun 15 00:10:34 +0000 2018 Thu Jun 14 18:50:53 +0000 2018
MIT
Kara/.ipynb_checkpoints/grabbing_tweets_june_14-checkpoint.ipynb
rglukins/stock-tweet
1.Importing the Relevant Libraries
%matplotlib inline import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.linear_model import Ridge, Lasso, LinearRegression from sklearn.tree import DecisionTreeRegressor from sklearn.neighbors import KNeighborsRegressor from sklearn import metrics from sklearn.ensemble import RandomFor...
_____no_output_____
MIT
Wind_tunnel.ipynb
AcharyaRakesh/WindTunnel
2.Reading Data
df = pd.read_csv("WindTunnel.csv") df df = pd.read_csv("WindTunnel.csv") plt.xlabel('Freqency') plt.ylabel('Velocity') plt.plot(df.Freqency,df.Velocity) reg = linear_model.LinearRegression() reg.fit(df[["Freqency"]],df.Velocity) reg.predict([[65.0]]) L=0.2 r=0.1 v=3.45 A=0.0323 CL = (2*L)/(r*(v**2)*A) CL df = pd.re...
_____no_output_____
MIT
Wind_tunnel.ipynb
AcharyaRakesh/WindTunnel
Data Pre-process
X_train, X_valid, y_train, y_valid = train_test_split(X,y,test_size = 0.2,random_state = 10) sc = StandardScaler() X_train = sc.fit_transform(X_train) X_test = sc.transform(X_valid) algos = [LinearRegression(), Ridge(), Lasso(), KNeighborsRegressor(), DecisionTreeRegressor(),RandomForestRegressor()] nam...
_____no_output_____
MIT
Wind_tunnel.ipynb
AcharyaRakesh/WindTunnel
Building Model
clf = Ridge() clf.fit(X_train,y_train) clf.score(X_test,y_test) clf.predict([[6.8,0.74,0.0323,0.27]])
_____no_output_____
MIT
Wind_tunnel.ipynb
AcharyaRakesh/WindTunnel
Import packages
# import packages import requests from bs4 import BeautifulSoup url = "https://www.makaan.com/hyderabad-residential-property/rent-property-in-hyderabad-city" response = requests.get(url) soup = BeautifulSoup(response.text,"html.parser") s_tag = soup.find_all('span',attrs={'class' : 'seller-type'}) for each_owner in s...
_____no_output_____
Apache-2.0
makaan_webscraping.ipynb
akhila-sakinala/akhila-sakinala.github.io
Enter State Farm
from theano.sandbox import cuda cuda.use('gpu0') %matplotlib inline from __future__ import print_function, division path = "data/state/" #path = "data/state/sample/" import utils; reload(utils) from utils import * from IPython.display import FileLink batch_size=64
_____no_output_____
Apache-2.0
deeplearning1/nbs/statefarm.ipynb
Fandekasp/fastai_courses
Setup batches
batches = get_batches(path+'train', batch_size=batch_size) val_batches = get_batches(path+'valid', batch_size=batch_size*2, shuffle=False) (val_classes, trn_classes, val_labels, trn_labels, val_filenames, filenames, test_filenames) = get_classes(path)
Found 18946 images belonging to 10 classes. Found 3478 images belonging to 10 classes. Found 79726 images belonging to 1 classes.
Apache-2.0
deeplearning1/nbs/statefarm.ipynb
Fandekasp/fastai_courses