markdown
stringlengths
0
1.02M
code
stringlengths
0
832k
output
stringlengths
0
1.02M
license
stringlengths
3
36
path
stringlengths
6
265
repo_name
stringlengths
6
127
1. Introduction to Feature SelectionFeature selection is the process of selecting a subset of relevant features (variables, predictors) for use in model construction. It is used for three reasons:* simplification of models to make them easier to interpret by researchers/users,* shorter training times,* enhanced genera...
# set the random seed rng = np.random.RandomState(0)
_____no_output_____
MIT
2016/tutorial_final/75/Feature Selection Tutorial.ipynb
zeromtmu/practicaldatascience.github.io
**Exp. 1**
# Exp 1 n_samples = 10000 n_features = 3 noise_level = 0.2 X = rng.rand(n_samples, n_features) coef = np.zeros(n_features) coef[0] = 0.0 coef[1] = 1.0 coef[2] = 2.0 y = np.dot(X, coef) + noise_level * rng.normal(size=n_samples) lr = LinearRegression() lr.fit(X, y) print 'Exp. 1, coefficient of linear regression\n%s'...
Exp. 1, coefficient of linear regression [-0.01119616 0.99446444 1.99559463] Exp. 1, coefficient of lasso [-0. 0.98258754 1.98367942]
MIT
2016/tutorial_final/75/Feature Selection Tutorial.ipynb
zeromtmu/practicaldatascience.github.io
As we can see from **Exp. 1**, we can easily find the feature importances from the coefficient of the trained model.And an important characteristic of the L1 penalty is that it will leads to sparse models. Sparse models means the weight of unimportant/irrelevent features will shrink to 0. In **Exp. 1**, the first featu...
def plot_sel_path(X, y, coef, method='Lasso'): """Plot feature selection result """ if method == 'Lasso': # alpha_grid, _, scores_path = lars_path(X, y, method='lasso', eps=0.05) alpha_grid, scores_path, _ = lasso_path(X, y, eps=0.001) elif method == 'Stability': alpha_grid, scor...
Exp. 2, coefficients setting for the relevant features [ 0.5754498 0.93597176 0.66245048 0.32697755 0.4974818 ]
MIT
2016/tutorial_final/75/Feature Selection Tutorial.ipynb
zeromtmu/practicaldatascience.github.io
As we can see from the results, although lots of irrelevant features are given to the model. Lasso will shrink their coefficients to 0 very quickly. 2.4 Drawbacks of LassoThere are some well-known limitations of Lasso, including1. Lasso will tend to select an individual variable out of a group of highly correlated fea...
def gen_simulation_dataset(n_features=50, n_relevant_features=3, noise_level=0.2, coef_min=0.2, n_samples=10000, rng=np.random.RandomState(0), conditioning=1): block_size = n_relevant_features # The coefficients of our model coef = np.zeros(n_features)...
Exp. 3, coefficients of the relevant features [ 0.42871572 0.31671741 0.69989626]
MIT
2016/tutorial_final/75/Feature Selection Tutorial.ipynb
zeromtmu/practicaldatascience.github.io
As we can see from the results, Lasso will fail to select all the relevant features if there are some corelation between the features. However, Randomized Lasso or Stability Selection will overcome such drawback and select all relevant features. 4. Real DatasetIn this section, we will conduct some experiments to see h...
def read(idx): f_X = 'data/X'+str(idx)+'.txt' f_Y = 'data/Y'+str(idx)+'.txt' f = open(f_X, 'r') x = [] for l in f: x.append(l) f.close() f = open(f_Y, 'r') y = [] for l in f: y.append(int(l)) f.close() return x, y x_all = [] y_all = [] for i in range(1, 9): ...
80000 80000 36326 43674
MIT
2016/tutorial_final/75/Feature Selection Tutorial.ipynb
zeromtmu/practicaldatascience.github.io
After loading the whole dataset, we transfer it into tfidf matrix.
from natural_language_processing import tfidf tfidf_all, words_all = tfidf(x_all) print tfidf_all.shape
(80000, 1245607)
MIT
2016/tutorial_final/75/Feature Selection Tutorial.ipynb
zeromtmu/practicaldatascience.github.io
So there are about 1245607 features in total.
from sklearn.feature_selection import SelectFromModel from sklearn.svm import LinearSVC X = tfidf_all y = y_all lsvc = LinearSVC(C=0.02, penalty="l1", dual=False).fit(X, y) model = SelectFromModel(lsvc, prefit=True, threshold='mean') X_new = model.transform(X) print X_new.shape mask = model.get_support() print 'Numb...
(80000, 1307) Number of feature selected 1307 After feature selection 0.0002
MIT
2016/tutorial_final/75/Feature Selection Tutorial.ipynb
zeromtmu/practicaldatascience.github.io
Make a bar plot of the months in which movies with "Christmas" in their title tend to be released in the USA.
r = release_dates r = r[(r.title.str.contains("Christmas", re.IGNORECASE, regex=True)) & (r.country == "USA") ] r = r.groupby(r.date.dt.month).size() r.plot(kind='bar', xlabel="month")
_____no_output_____
MIT
Exercises-5.ipynb
zazke/pycon-pandas-tutorial
Make a bar plot of the months in which movies whose titles start with "The Hobbit" are released in the USA.
r = release_dates r = r[(r.title.str.contains("The Hobbit")) & (r.country == "USA") ] r = r.groupby(r.date.dt.month).size() r r.plot(kind='bar', xlabel="month")
_____no_output_____
MIT
Exercises-5.ipynb
zazke/pycon-pandas-tutorial
Make a bar plot of the day of the week on which movies with "Romance" in their title tend to be released in the USA.
r = release_dates r = r[(r.title.str.contains("Romance")) & (r.country == "USA") ] r = r.groupby(r.date.dt.dayofweek).size() r r.plot(kind='bar', xlabel="dayofweek (0=Monday)")
_____no_output_____
MIT
Exercises-5.ipynb
zazke/pycon-pandas-tutorial
Make a bar plot of the day of the week on which movies with "Action" in their title tend to be released in the USA.
r = release_dates r = r[(r.title.str.contains("Action")) & (r.country == "USA") ] r = r.groupby(r.date.dt.dayofweek).size() r r.plot(kind='bar', xlabel="dayofweek (0=Monday)")
_____no_output_____
MIT
Exercises-5.ipynb
zazke/pycon-pandas-tutorial
On which date was each Judi Dench movie from the 1990s released in the USA?
release_dates.columns c = cast c = c[(c.name == 'Judi Dench') & (c.year // 10 * 10 == 1990)] c = c.merge(release_dates, on=['title', 'year']) c = c[(c.country == 'USA')] c # data not available
_____no_output_____
MIT
Exercises-5.ipynb
zazke/pycon-pandas-tutorial
In which months do films with Judi Dench tend to be released in the USA?
c.groupby(c.date.dt.month).size()
_____no_output_____
MIT
Exercises-5.ipynb
zazke/pycon-pandas-tutorial
November (11月) and December (12月) In which months do films with Tom Cruise tend to be released in the USA?
c = cast c = c[(c.name == 'Tom Cruise')] c = c.merge(release_dates, on=['title', 'year']) c = c[(c.country == 'USA')] c.head() c.groupby(c.date.dt.month).size()
_____no_output_____
MIT
Exercises-5.ipynb
zazke/pycon-pandas-tutorial
TAXI!
mitexto = "el perro de san roque no tiene rabo" help(str) str.title(mitexto)
_____no_output_____
MIT
pythonUPVX32.ipynb
Coldang/pythonMoocCompanion
pero **mitexto** es de tipo str podriamos tal vez...
mitexto.title()
_____no_output_____
MIT
pythonUPVX32.ipynb
Coldang/pythonMoocCompanion
encadenando llamadas
mitexto.replace('san','mr').title()
_____no_output_____
MIT
pythonUPVX32.ipynb
Coldang/pythonMoocCompanion
Build Your First QA System[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/deepset-ai/haystack/blob/master/tutorials/Tutorial1_Basic_QA_Pipeline.ipynb)Question Answering can be used in a variety of use cases. A very common one: Using it to navigate...
# Make sure you have a GPU running !nvidia-smi # Install the latest release of Haystack in your own environment #! pip install farm-haystack # Install the latest master of Haystack !pip install grpcio-tools==1.34.1 !pip install git+https://github.com/deepset-ai/haystack.git # If you run this notebook on Google Colab...
_____no_output_____
Apache-2.0
tutorials/Tutorial1_Basic_QA_Pipeline.ipynb
tcapilla/haystack
Document StoreHaystack finds answers to queries within the documents stored in a `DocumentStore`. The current implementations of `DocumentStore` include `ElasticsearchDocumentStore`, `FAISSDocumentStore`, `SQLDocumentStore`, and `InMemoryDocumentStore`.**Here:** We recommended Elasticsearch as it comes preloaded with...
# Recommended: Start Elasticsearch using Docker via the Haystack utility function from haystack.utils import launch_es launch_es() # In Colab / No Docker environments: Start Elasticsearch from source ! wget https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-7.9.2-linux-x86_64.tar.gz -q ! tar -xzf elast...
_____no_output_____
Apache-2.0
tutorials/Tutorial1_Basic_QA_Pipeline.ipynb
tcapilla/haystack
Preprocessing of documentsHaystack provides a customizable pipeline for: - converting files into texts - cleaning texts - splitting texts - writing them to a Document StoreIn this tutorial, we download Wikipedia articles about Game of Thrones, apply a basic cleaning function, and index them in Elasticsearch.
# Let's first fetch some documents that we want to query # Here: 517 Wikipedia articles for Game of Thrones doc_dir = "data/article_txt_got" s3_url = "https://s3.eu-central-1.amazonaws.com/deepset.ai-farm-qa/datasets/documents/wiki_gameofthrones_txt.zip" fetch_archive_from_http(url=s3_url, output_dir=doc_dir) # Conver...
_____no_output_____
Apache-2.0
tutorials/Tutorial1_Basic_QA_Pipeline.ipynb
tcapilla/haystack
Initalize Retriever, Reader, & Pipeline RetrieverRetrievers help narrowing down the scope for the Reader to smaller units of text where a given question could be answered.They use some simple but fast algorithm.**Here:** We use Elasticsearch's default BM25 algorithm**Alternatives:**- Customize the `ElasticsearchRetri...
from haystack.retriever.sparse import ElasticsearchRetriever retriever = ElasticsearchRetriever(document_store=document_store) # Alternative: An in-memory TfidfRetriever based on Pandas dataframes for building quick-prototypes with SQLite document store. # from haystack.retriever.sparse import TfidfRetriever # retriev...
_____no_output_____
Apache-2.0
tutorials/Tutorial1_Basic_QA_Pipeline.ipynb
tcapilla/haystack
ReaderA Reader scans the texts returned by retrievers in detail and extracts the k best answers. They are basedon powerful, but slower deep learning models.Haystack currently supports Readers based on the frameworks FARM and Transformers.With both you can either load a local model or one from Hugging Face's model hub ...
# Load a local model or any of the QA models on # Hugging Face's model hub (https://huggingface.co/models) reader = FARMReader(model_name_or_path="deepset/roberta-base-squad2", use_gpu=True)
_____no_output_____
Apache-2.0
tutorials/Tutorial1_Basic_QA_Pipeline.ipynb
tcapilla/haystack
TransformersReader
# Alternative: # reader = TransformersReader(model_name_or_path="distilbert-base-uncased-distilled-squad", tokenizer="distilbert-base-uncased", use_gpu=-1)
_____no_output_____
Apache-2.0
tutorials/Tutorial1_Basic_QA_Pipeline.ipynb
tcapilla/haystack
PipelineWith a Haystack `Pipeline` you can stick together your building blocks to a search pipeline.Under the hood, `Pipelines` are Directed Acyclic Graphs (DAGs) that you can easily customize for your own use cases.To speed things up, Haystack also comes with a few predefined Pipelines. One of them is the `Extractive...
from haystack.pipeline import ExtractiveQAPipeline pipe = ExtractiveQAPipeline(reader, retriever)
_____no_output_____
Apache-2.0
tutorials/Tutorial1_Basic_QA_Pipeline.ipynb
tcapilla/haystack
Voilà! Ask a question!
# You can configure how many candidates the reader and retriever shall return # The higher top_k_retriever, the better (but also the slower) your answers. prediction = pipe.run( query="Who is the father of Arya Stark?", params={"Retriever": {"top_k": 10}, "Reader": {"top_k": 5}} ) # prediction = pipe.run(query="Wh...
_____no_output_____
Apache-2.0
tutorials/Tutorial1_Basic_QA_Pipeline.ipynb
tcapilla/haystack
![alt text](https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcTK4gQ9nhwHHaSXMHpeggWg7twwMCgb877smkRmtkmDeDoGF9Z6&usqp=CAU) Dicas e Truques de Ciência de Dados Baby Steps em Ciência de Dados **Python Crash Course** ![alt text](https://www.python.org/static/img/python-logo@2x.png) Strings
data = 'Cientista de Dados' print(data) print(len(data)) data[10:]
_____no_output_____
MIT
Crash_Course_Python_Parte_2.ipynb
Adrianacms/Hello-Word
Números
# Numbers value = 123 value type(value) print(value)
_____no_output_____
MIT
Crash_Course_Python_Parte_2.ipynb
Adrianacms/Hello-Word
Boleanos
# Boolean a = True b = False print(a,b) # Multiple Assignment a, b, c = 1, 2, 3 print(a, b,c) # No value a = None print(a)
None
MIT
Crash_Course_Python_Parte_2.ipynb
Adrianacms/Hello-Word
Flow Control If-Then-Else Condition Example
idade = 21 if idade >= 18: print('maior de idade') else: print('menor de idade') idade = 39 if idade < 12: print('crianca') elif idade < 18: print('adolescente') elif idade < 39: print('maduro') elif idade < 60: print('adulto') else: print('idoso')
adulto
MIT
Crash_Course_Python_Parte_2.ipynb
Adrianacms/Hello-Word
For-Loop Example
# For-Loop for i in range(10): print(i)
_____no_output_____
MIT
Crash_Course_Python_Parte_2.ipynb
Adrianacms/Hello-Word
While-Loop Example
# While-Loop e = 5 while e <= 100: print(e) e += 10
_____no_output_____
MIT
Crash_Course_Python_Parte_2.ipynb
Adrianacms/Hello-Word
Estrutura de Dados Tupla
tupla = (1, 2, 3) print(tupla) type(tupla)
_____no_output_____
MIT
Crash_Course_Python_Parte_2.ipynb
Adrianacms/Hello-Word
Lista
mylist = [1, 2, 3] print("O índice ZERO é o número: %d" % mylist[0]) type(mylist) mylist[0] mylist.append(4) print("List Length: %d" % len(mylist)) for value in mylist: print(value)
_____no_output_____
MIT
Crash_Course_Python_Parte_2.ipynb
Adrianacms/Hello-Word
Dicionário
mydict = {'a': 1, 'b': 2, 'c': 3} print("O valor da chave 'a' é igual: %d" % mydict['a']) mydict['a'] = 11 mydict['a'] = 11 print("A value: %d" % mydict['a']) print("Keys: %s" % mydict.keys()) print("Values: %s" % mydict.values()) for key in mydict.keys(): print(mydict[key])
11 2 3
MIT
Crash_Course_Python_Parte_2.ipynb
Adrianacms/Hello-Word
Functions
# Sum function def mysum(x, y): return x + y def myfun (x,y): return x+y print(myfun) # Test sum function myfun(1,3) # Sum function def myexp(x, y): return x**y myexp(3,3)
_____no_output_____
MIT
Crash_Course_Python_Parte_2.ipynb
Adrianacms/Hello-Word
**NumPy Crash Course** ![alt text](https://miro.medium.com/max/765/0*p0FtnloWd4ogMvTQ.png) Create Array (matriz) matrizes são tensores com 2 dimensões (**tensores de rank 2**).
# define an array import numpy mylist = [1, 2, 3] myarray = numpy.array(mylist) print(myarray) print(myarray.shape)
[1 2 3] (3,)
MIT
Crash_Course_Python_Parte_2.ipynb
Adrianacms/Hello-Word
Acessando os dados do Array (matriz)
# access values import numpy mylist = [[1, 2, 3], [3, 4, 5]] myarray = numpy.array(mylist) print(myarray) print(myarray.shape) print("Primeira linha: %s" % myarray[0]) print("última linha: %s" % myarray[-1]) print("Qual elemento está na Posição dessa consulta? A Resposta é %s" % myarray[0, 2]) print("Quais...
Quais elementos estão na coluna dessa consulta? A Resposta é [3 5]
MIT
Crash_Course_Python_Parte_2.ipynb
Adrianacms/Hello-Word
Arithmetic
# arithmetic import numpy myarray1 = numpy.array([2, 2, 2]) myarray2 = numpy.array([3, 3, 3]) print("Soma: %s" % (myarray1 + myarray2)) print("Multiplicação: %s" % (myarray1 * myarray2))
Soma: [5 5 5] Multiplicação: [6 6 6]
MIT
Crash_Course_Python_Parte_2.ipynb
Adrianacms/Hello-Word
O vetor n-dimensional (tensor) O NumPy é uma biblioteca para a linguagem Python com funções para se trabalhar com **computação numérica**. Seu **principal objeto é o vetor n-dimensional, ou ndarray**. Um vetor n-dimensional também é conhecido pelo nome **tensor**. A principal característica do ndarray é que ele dev...
#cria um vetor import numpy as np v = np.array([1,2,3,4]) print(v) print(v.dtype) v = np.array([1,2,3,4], dtype='float64') print(v.dtype)
float64
MIT
Crash_Course_Python_Parte_2.ipynb
Adrianacms/Hello-Word
Os tensores NumPy também possuem um atributo chamado shape. Esse atributo indica a forma do tensor, por exemplo:
print(v.shape)
(4,)
MIT
Crash_Course_Python_Parte_2.ipynb
Adrianacms/Hello-Word
Neste caso, o tensor v possui 1 dimensão (ou eixo) com 4 elementos. Um tensor unidimensional corresponde a um vetor. Podemos também criar um tensor bidimensional (uma matriz) usando o atributo shape:
# Alterando a dimensão do tensor v = np.array([1,2,3,4]) v.shape = (2,2) print(v)
[[1 2] [3 4]]
MIT
Crash_Course_Python_Parte_2.ipynb
Adrianacms/Hello-Word
Reshape Outra forma útil de mudar o shape de um tensor é simplesmente utilizando a função reshape:
v = np.array([1,2,3,4]).reshape(2,2) print(v)
[[1 2] [3 4]]
MIT
Crash_Course_Python_Parte_2.ipynb
Adrianacms/Hello-Word
**ndim** (eixos ou dimensões do tensor) e **size** (total de elementos/registros) O número de eixos (ou dimensões) de um tensor é dado pelo atributo ndim, enquanto o número total de elementos é dado por size:
v = np.array(range(9)).reshape(1,3,3) v print('Shape = ', v.shape) print('Número de dimensões = ', v.ndim) print('Número de elementos = ', v.size) print('\n\n Veja abaixo o Tensor v \n\n', v)
Shape = (1, 3, 3) Número de dimensões = 3 Número de elementos = 9 Veja abaixo o Tensor v [[[0 1 2] [3 4 5] [6 7 8]]]
MIT
Crash_Course_Python_Parte_2.ipynb
Adrianacms/Hello-Word
**Matplotlib Crash Course** ![alt text](https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRhMLqZjlbD_mb9HsaF8t1I2s9VI-8ZD60s1g&usqp=CAU) Line Plot
# basic line plot import matplotlib.pyplot as plt import numpy myarray = numpy.array([1, 2, 3]) plt.plot(myarray) plt.xlabel('Data') plt.ylabel('Faturamento') plt.show()
_____no_output_____
MIT
Crash_Course_Python_Parte_2.ipynb
Adrianacms/Hello-Word
Scatter Plot
# basic scatter plot import matplotlib.pyplot as plt import numpy vendas = numpy.array([1, 2, 3, 4, 8, 16 ]) faturamento = numpy.array([2, 4, 6, 8, 10, 12]) plt.scatter(vendas,faturamento) plt.xlabel('vendas') plt.ylabel('faturamento') plt.show() fig, ax = plt.subplots() size = 0.3 vals = np.array([[60., 32...
_____no_output_____
MIT
Crash_Course_Python_Parte_2.ipynb
Adrianacms/Hello-Word
**Eletroencefalograma** é um exame que avalia a atividade elétrica espontânea do cérebro. Para tanto, o teste, também conhecido pela abreviação EEG, amplifica os impulsos elétricos cerebrais e os registra, a fim de detectar anormalidades neurológicas.
import numpy as np import matplotlib.pyplot as plt import matplotlib.cbook as cbook import matplotlib.cm as cm from matplotlib.collections import LineCollection from matplotlib.ticker import MultipleLocator fig = plt.figure("MRI_with_EEG") # Load the MRI data (256x256 16 bit integers) with cbook.get_sampl...
_____no_output_____
MIT
Crash_Course_Python_Parte_2.ipynb
Adrianacms/Hello-Word
**Pandas Crash Course** ![alt text](https://s3.amazonaws.com/lintel-blogs-static-files/wp-content/uploads/2019/07/14165137/pandas.jpg) **Series**: Uma série é um array unidimensional onde as linhas e colunas podem ser rotuladas.
# series import numpy as np import pandas as pd myarray = np.array([1, 2, 3]) rownames = ['Kiwi', 'Marlos', 'Bruno'] myseries = pd.Series(myarray, index=rownames) print(myseries) print(myseries['Marlos'])
_____no_output_____
MIT
Crash_Course_Python_Parte_2.ipynb
Adrianacms/Hello-Word
**Dataframe**
# dataframe import numpy as np import pandas as pd myarray = np.array([[10, 9, 7], [5, 5, 8], [1,1,1]]) rownames = ['Marlos', 'Kiwi','Oliveira'] colnames = ['Geografia', 'Matemática', 'Biologia'] mydataframe = pd.DataFrame(myarray, index=rownames, columns=colnames) print(mydataframe) #Quantidade de linhas myd...
_____no_output_____
MIT
Crash_Course_Python_Parte_2.ipynb
Adrianacms/Hello-Word
**Resumão** ![alt text](https://static.imagensparawhats.com.br/content/assetz/uploads/2018/08/imagens-para-whats-praia-e-mar-gifs.gif) Você acaba de colocar o pé nesse MAR que é o **Python**. Você descobriu a sintaxe básica e o uso do Python e 3 bibliotecas Python principais usadas para inicira os trabalhos de aprend...
from IPython.core.display import HTML HTML('<iframe width="380" height="200" src="https://www.youtube.com/embed/W9iktBS67Iw" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>')
_____no_output_____
MIT
Crash_Course_Python_Parte_2.ipynb
Adrianacms/Hello-Word
Ensemble Learning Initial Imports
import warnings warnings.filterwarnings('ignore') import numpy as np import pandas as pd from pathlib import Path from collections import Counter from sklearn.metrics import balanced_accuracy_score from sklearn.metrics import confusion_matrix from imblearn.metrics import classification_report_imbalanced
_____no_output_____
ADSL
Starter_Code/credit_risk_ensemble.ipynb
willhua531/HW-Classification
Read the CSV and Perform Basic Data Cleaning
# Load the data file_path = Path('Resources/LoanStats_2019Q1.csv') df = pd.read_csv(file_path) # Preview the data df.head()
_____no_output_____
ADSL
Starter_Code/credit_risk_ensemble.ipynb
willhua531/HW-Classification
Split the Data into Training and Testing
# Create our features df_encoded = pd.get_dummies(df, columns = ['home_ownership', 'verification_status', 'issue_d', 'pymnt_plan', 'hardship_flag', 'debt_settlement_flag', 'initial_list_status', 'next_pymnt_d', 'application_type'])...
_____no_output_____
ADSL
Starter_Code/credit_risk_ensemble.ipynb
willhua531/HW-Classification
Data Pre-ProcessingScale the training and testing data using the `StandardScaler` from `sklearn`. Remember that when scaling the data, you only scale the features data (`X_train` and `X_testing`).
# Create the StandardScaler instance from sklearn.preprocessing import StandardScaler # YOUR CODE HERE scaler = StandardScaler() # Fit the Standard Scaler with the training data # When fitting scaling functions, only train on the training dataset # YOUR CODE HERE X_scaler = scaler.fit(X_train) # Scale the training and ...
_____no_output_____
ADSL
Starter_Code/credit_risk_ensemble.ipynb
willhua531/HW-Classification
Ensemble LearnersIn this section, you will compare two ensemble algorithms to determine which algorithm results in the best performance. You will train a Balanced Random Forest Classifier and an Easy Ensemble classifier . For each algorithm, be sure to complete the folliowing steps:1. Train the model using the trainin...
# Resample the training data with the BalancedRandomForestClassifier # YOUR CODE HERE from imblearn.ensemble import BalancedRandomForestClassifier brf = BalancedRandomForestClassifier(n_estimators=100, random_state=1) brf.fit(X_train, y_train) # Calculated the balanced accuracy score # YOUR CODE HERE y_pred = brf.predi...
_____no_output_____
ADSL
Starter_Code/credit_risk_ensemble.ipynb
willhua531/HW-Classification
Easy Ensemble Classifier
# Train the Classifier # YOUR CODE HERE from imblearn.ensemble import EasyEnsembleClassifier eec = EasyEnsembleClassifier(random_state = 0) eec.fit(X_train, y_train) # Calculated the balanced accuracy score # YOUR CODE HERE y_pred_eec = eec.predict(X_test) balanced_accuracy_score(y_test, y_pred_eec) # Display the conf...
pre rec spe f1 geo iba sup high_risk 0.06 0.91 0.93 0.12 0.92 0.84 87 low_risk 1.00 0.93 0.91 0.96 0.92 0.85 17118 avg / total 0.99 0.93 0.91 0.96 0.92 0...
ADSL
Starter_Code/credit_risk_ensemble.ipynb
willhua531/HW-Classification
In this post, I define a class to model the behavior of ahydrogen atom. In the process, I get to solve integrals like the following numerically to test my code:$$ \int_0^{\pi} \int_0^{2\pi} \lvert Y_{l, m_l} \rvert ^2 \sin \theta d \theta d \phi = 1 $$This post consists of a arge block of Python code up front, and then...
import numpy as np import matplotlib.pyplot as plt from matplotlib import cm from math import exp, sqrt, pi, cos, sin from scipy.integrate import dblquad, tplquad, quad import cmath class HydrogenicAtom: """ This class models the wavefunctions and energy levels of a hydrogenic atom. It assumes an infi...
_____no_output_____
BSD-2-Clause
notebooks/hydrogenic_atom.ipynb
akey7/basic-quantum-models
Check the spherical harmonicsMake sure all the spherical harmonics are normalized. That means each of the the spherical harmonic functions must stasify the following expression:$$ \int_0^{\pi} \int_0^{2\pi} \lvert Y_{l, m_l} \rvert ^2 \sin \theta d \theta d \phi = 1 $$The next block of code takes the spherical harmoni...
parameters = [ { 'n': 3, 'l': 0, 'ml': 0 }, { 'n': 3, 'l': 1, 'ml': 0 }, { 'n': 3, 'l': 1, 'ml': 1 }, { 'n': 3, 'l': 1, 'ml': -1 }, { 'n': 3, 'l': 2, 'ml': 0 }, { 'n': 3, 'l': 2, 'ml': 1 }, { 'n': 3, 'l': 2, 'ml': -1 }, { 'n': 3, 'l': 2, 'ml': 2 }, { 'n': 3, 'l': 2, 'ml': -2 }, {...
{'n': 3, 'l': 0, 'ml': 0, 'result': 0.9999999999999999} {'n': 3, 'l': 1, 'ml': 0, 'result': 1.0} {'n': 3, 'l': 1, 'ml': 1, 'result': 0.9999999999999999} {'n': 3, 'l': 1, 'ml': -1, 'result': 0.9999999999999999} {'n': 3, 'l': 2, 'ml': 0, 'result': 1.0000000000000002} {'n': 3, 'l': 2, 'ml': 1, 'result': 1.0} {'n': 3, 'l':...
BSD-2-Clause
notebooks/hydrogenic_atom.ipynb
akey7/basic-quantum-models
Plots of the radial functionsFigure 1 has plots of the radial functions for various combinations of n and l. Some of the subplots are blank because there is no corresponding radial function for their position on the chart.
fig, axs = plt.subplots(nrows=3, ncols=3, figsize=(12, 15)) # Just so I can access instance variables in an instance to make the dictionary. ha = HydrogenicAtom() yscaler = (ha.z / ha.a0)**(3/2) parameters = [ {'n': 1, 'l': 0, 'x_scaler': 5, 'yscaler': yscaler }, {'n': 2, 'l': 0, 'x_scaler': 15, 'yscaler': y...
_____no_output_____
BSD-2-Clause
notebooks/hydrogenic_atom.ipynb
akey7/basic-quantum-models
Hydrogen energy levelsNote how the levels pack closer together at higher energy levels. The lowest energy, -13.6 eV, is the ground state of the hydrogen atom. All the energies are negative, which means they refer to bound states where the nucleus holds the electron.
ys = [] for n in range(1, 10): ha = HydrogenicAtom(n=n) _, ev = ha.energy() ys.append((n, round(ev, 2))) fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(2, 10)) ax.set_ylim(-14.0, 0.0) ax.set_xticks([]) ax.set_ylabel('eV', size=20, color='b') ax.set_title('Hydrogen Energy Levels, n=1 to n=9', size=20, co...
_____no_output_____
BSD-2-Clause
notebooks/hydrogenic_atom.ipynb
akey7/basic-quantum-models
By numeric integration, what is the mean radius of 1s orbital?In this section, I follow the integral given in Example 10.2 that will find the mean radius of an orbital: $$ \langle r \rangle = \int_0^{\infty} r^3 R_{n,l}^2 dr $$I integrate it numerically with the `quad` function from `scipy.integrate`. The `points` arg...
ha = HydrogenicAtom(n=1, l=0, ml=0) def integrand(r): return r**3 * ha.radial(r)**2 quad(integrand, 0, 1, points=[0, 10 * ha.a0 * ha.n])
_____no_output_____
BSD-2-Clause
notebooks/hydrogenic_atom.ipynb
akey7/basic-quantum-models
The first element of the tuple above is the result of the integration, and the second element is the estimated error of the integration. Below is the solution to the analytical integration solution given by the book. It matches the numeric integration!
3 * ha.a0 / 2
_____no_output_____
BSD-2-Clause
notebooks/hydrogenic_atom.ipynb
akey7/basic-quantum-models
What about the 3s orbital? First numeric integration, then the numeric solution from the book.
ha = HydrogenicAtom(n=3, l=0, ml=0) def integrand(r): return r**3 * ha.radial(r)**2 quad(integrand, 0, 1, points=[0, 10 * ha.a0 * ha.n]) 27 * ha.a0 / 2
_____no_output_____
BSD-2-Clause
notebooks/hydrogenic_atom.ipynb
akey7/basic-quantum-models
What about the 3p orbital?
ha = HydrogenicAtom(n=3, l=1, ml=0) def integrand(r): return r**3 * ha.radial(r)**2 quad(integrand, 0, 1, points=[0, 10 * ha.a0 * ha.n]) 25 * ha.a0 / 2
_____no_output_____
BSD-2-Clause
notebooks/hydrogenic_atom.ipynb
akey7/basic-quantum-models
Overall, the numerical integration and the guess about where the interesting parts of the integration are worked out fairly well for these examples. What is the mean radius of each orbital?Make some plots of the mean radius of each orbital. Red circles are s orbitals, green squares are p orbitals, blue diamonds are d ...
parameters = [ {'n': 1, 'l': 0 }, {'n': 2, 'l': 0 }, {'n': 2, 'l': 1 }, {'n': 3, 'l': 0 }, {'n': 3, 'l': 1 }, {'n': 3, 'l': 2 } ] for p in parameters: ha = HydrogenicAtom(n=p['n'], l=p['l']) p['mean_radius_a0'] = ha.mean_orbital_radius() / ha.a0 fig, ax = plt.subplots(nrows=1, ncol...
_____no_output_____
BSD-2-Clause
notebooks/hydrogenic_atom.ipynb
akey7/basic-quantum-models
ReferenceThis example is taken from the book [DL with Python](https://www.manning.com/books/deep-learning-with-python) by F. Chollet. It explains how to retrain a pre-trained CNN classifierAll the notebooks from the book are available for free on [Github](https://github.com/fchollet/deep-learning-with-python-notebooks...
import keras keras.__version__
Using TensorFlow backend.
MIT
samples/notebooks/week04-03-using-a-pretrained-convnet.ipynb
gu-ma/ba_218_comppx_h1901
Using a pre-trained convnetThis notebook contains the code sample found in Chapter 5, Section 3 of [Deep Learning with Python](https://www.manning.com/books/deep-learning-with-python?a_aid=keras&a_bid=76564dff). Note that the original text features far more content, in particular further explanations and figures: in t...
from keras.applications import VGG16 conv_base = VGG16(weights='imagenet', include_top=False, input_shape=(150, 150, 3))
_____no_output_____
MIT
samples/notebooks/week04-03-using-a-pretrained-convnet.ipynb
gu-ma/ba_218_comppx_h1901
We passed three arguments to the constructor:* `weights`, to specify which weight checkpoint to initialize the model from* `include_top`, which refers to including or not the densely-connected classifier on top of the network. By default, this densely-connected classifier would correspond to the 1000 classes from Image...
conv_base.summary()
_________________________________________________________________ Layer (type) Output Shape Param # ================================================================= input_1 (InputLayer) (None, 150, 150, 3) 0 ________________________________________________________...
MIT
samples/notebooks/week04-03-using-a-pretrained-convnet.ipynb
gu-ma/ba_218_comppx_h1901
The final feature map has shape `(4, 4, 512)`. That's the feature on top of which we will stick a densely-connected classifier.At this point, there are two ways we could proceed: * Running the convolutional base over our dataset, recording its output to a Numpy array on disk, then using this data as input to a standalo...
import os import numpy as np from keras.preprocessing.image import ImageDataGenerator base_dir = '/Users/guillaume/Downloads/datasets/small/' train_dir = os.path.join(base_dir, 'train') validation_dir = os.path.join(base_dir, 'validation') test_dir = os.path.join(base_dir, 'test') datagen = ImageDataGenerator(rescal...
Found 2000 images belonging to 2 classes. Found 1000 images belonging to 2 classes. Found 1000 images belonging to 2 classes.
MIT
samples/notebooks/week04-03-using-a-pretrained-convnet.ipynb
gu-ma/ba_218_comppx_h1901
The extracted features are currently of shape `(samples, 4, 4, 512)`. We will feed them to a densely-connected classifier, so first we must flatten them to `(samples, 8192)`:
train_features = np.reshape(train_features, (2000, 4 * 4 * 512)) validation_features = np.reshape(validation_features, (1000, 4 * 4 * 512)) test_features = np.reshape(test_features, (1000, 4 * 4 * 512))
_____no_output_____
MIT
samples/notebooks/week04-03-using-a-pretrained-convnet.ipynb
gu-ma/ba_218_comppx_h1901
At this point, we can define our densely-connected classifier (note the use of dropout for regularization), and train it on the data and labels that we just recorded:
from keras import models from keras import layers from keras import optimizers model = models.Sequential() model.add(layers.Dense(256, activation='relu', input_dim=4 * 4 * 512)) model.add(layers.Dropout(0.5)) model.add(layers.Dense(1, activation='sigmoid')) model.compile(optimizer=optimizers.RMSprop(lr=2e-5), ...
_____no_output_____
MIT
samples/notebooks/week04-03-using-a-pretrained-convnet.ipynb
gu-ma/ba_218_comppx_h1901
Training is very fast, since we only have to deal with two `Dense` layers -- an epoch takes less than one second even on CPU.Let's take a look at the loss and accuracy curves during training:
import matplotlib.pyplot as plt acc = history.history['acc'] val_acc = history.history['val_acc'] loss = history.history['loss'] val_loss = history.history['val_loss'] epochs = range(len(acc)) plt.plot(epochs, acc, 'bo', label='Training acc') plt.plot(epochs, val_acc, 'b', label='Validation acc') plt.title('Training...
_____no_output_____
MIT
samples/notebooks/week04-03-using-a-pretrained-convnet.ipynb
gu-ma/ba_218_comppx_h1901
We reach a validation accuracy of about 90%, much better than what we could achieve in the previous section with our small model trained from scratch. However, our plots also indicate that we are overfitting almost from the start -- despite using dropout with a fairly large rate. This is because this technique does not...
from keras import models from keras import layers model = models.Sequential() model.add(conv_base) model.add(layers.Flatten()) model.add(layers.Dense(256, activation='relu')) model.add(layers.Dense(1, activation='sigmoid'))
_____no_output_____
MIT
samples/notebooks/week04-03-using-a-pretrained-convnet.ipynb
gu-ma/ba_218_comppx_h1901
This is what our model looks like now:
model.summary()
_________________________________________________________________ Layer (type) Output Shape Param # ================================================================= vgg16 (Model) (None, 4, 4, 512) 14714688 ________________________________________________________...
MIT
samples/notebooks/week04-03-using-a-pretrained-convnet.ipynb
gu-ma/ba_218_comppx_h1901
As you can see, the convolutional base of VGG16 has 14,714,688 parameters, which is very large. The classifier we are adding on top has 2 million parameters.Before we compile and train our model, a very important thing to do is to freeze the convolutional base. "Freezing" a layer or set of layers means preventing their...
print('This is the number of trainable weights ' 'before freezing the conv base:', len(model.trainable_weights)) conv_base.trainable = False print('This is the number of trainable weights ' 'after freezing the conv base:', len(model.trainable_weights))
This is the number of trainable weights after freezing the conv base: 4
MIT
samples/notebooks/week04-03-using-a-pretrained-convnet.ipynb
gu-ma/ba_218_comppx_h1901
With this setup, only the weights from the two `Dense` layers that we added will be trained. That's a total of four weight tensors: two per layer (the main weight matrix and the bias vector). Note that in order for these changes to take effect, we must first compile the model. If you ever modify weight trainability aft...
from keras.preprocessing.image import ImageDataGenerator train_datagen = ImageDataGenerator( rescale=1./255, rotation_range=40, width_shift_range=0.2, height_shift_range=0.2, shear_range=0.2, zoom_range=0.2, horizontal_flip=True, fill_mode='nearest') # Note that the val...
_____no_output_____
MIT
samples/notebooks/week04-03-using-a-pretrained-convnet.ipynb
gu-ma/ba_218_comppx_h1901
Let's plot our results again:
acc = history.history['acc'] val_acc = history.history['val_acc'] loss = history.history['loss'] val_loss = history.history['val_loss'] epochs = range(len(acc)) plt.plot(epochs, acc, 'bo', label='Training acc') plt.plot(epochs, val_acc, 'b', label='Validation acc') plt.title('Training and validation accuracy') plt.le...
_____no_output_____
MIT
samples/notebooks/week04-03-using-a-pretrained-convnet.ipynb
gu-ma/ba_218_comppx_h1901
As you can see, we reach a validation accuracy of about 96%. This is much better than our small convnet trained from scratch. Fine-tuningAnother widely used technique for model reuse, complementary to feature extraction, is _fine-tuning_. Fine-tuning consists in unfreezing a few of the top layers of a frozen model bas...
conv_base.summary()
_________________________________________________________________ Layer (type) Output Shape Param # ================================================================= input_1 (InputLayer) (None, 150, 150, 3) 0 ________________________________________________________...
MIT
samples/notebooks/week04-03-using-a-pretrained-convnet.ipynb
gu-ma/ba_218_comppx_h1901
We will fine-tune the last 3 convolutional layers, which means that all layers up until `block4_pool` should be frozen, and the layers `block5_conv1`, `block5_conv2` and `block5_conv3` should be trainable.Why not fine-tune more layers? Why not fine-tune the entire convolutional base? We could. However, we need to consi...
conv_base.trainable = True set_trainable = False for layer in conv_base.layers: if layer.name == 'block5_conv1': set_trainable = True if set_trainable: layer.trainable = True else: layer.trainable = False
_____no_output_____
MIT
samples/notebooks/week04-03-using-a-pretrained-convnet.ipynb
gu-ma/ba_218_comppx_h1901
Now we can start fine-tuning our network. We will do this with the RMSprop optimizer, using a very low learning rate. The reason for using a low learning rate is that we want to limit the magnitude of the modifications we make to the representations of the 3 layers that we are fine-tuning. Updates that are too large ma...
model.compile(loss='binary_crossentropy', optimizer=optimizers.RMSprop(lr=1e-5), metrics=['acc']) history = model.fit_generator( train_generator, steps_per_epoch=100, epochs=100, validation_data=validation_generator, validation_steps=50) model.save('cats_and_do...
_____no_output_____
MIT
samples/notebooks/week04-03-using-a-pretrained-convnet.ipynb
gu-ma/ba_218_comppx_h1901
Let's plot our results using the same plotting code as before:
acc = history.history['acc'] val_acc = history.history['val_acc'] loss = history.history['loss'] val_loss = history.history['val_loss'] epochs = range(len(acc)) plt.plot(epochs, acc, 'bo', label='Training acc') plt.plot(epochs, val_acc, 'b', label='Validation acc') plt.title('Training and validation accuracy') plt.le...
_____no_output_____
MIT
samples/notebooks/week04-03-using-a-pretrained-convnet.ipynb
gu-ma/ba_218_comppx_h1901
These curves look very noisy. To make them more readable, we can smooth them by replacing every loss and accuracy with exponential moving averages of these quantities. Here's a trivial utility function to do this:
def smooth_curve(points, factor=0.8): smoothed_points = [] for point in points: if smoothed_points: previous = smoothed_points[-1] smoothed_points.append(previous * factor + point * (1 - factor)) else: smoothed_points.append(point) return smoothed_points plt.plot(epochs, smooth...
_____no_output_____
MIT
samples/notebooks/week04-03-using-a-pretrained-convnet.ipynb
gu-ma/ba_218_comppx_h1901
These curves look much cleaner and more stable. We are seeing a nice 1% absolute improvement.Note that the loss curve does not show any real improvement (in fact, it is deteriorating). You may wonder, how could accuracy improve if the loss isn't decreasing? The answer is simple: what we display is an average of pointwi...
test_generator = test_datagen.flow_from_directory( test_dir, target_size=(150, 150), batch_size=20, class_mode='binary') test_loss, test_acc = model.evaluate_generator(test_generator, steps=50) print('test acc:', test_acc)
Found 1000 images belonging to 2 classes. test acc: 0.967999992371
MIT
samples/notebooks/week04-03-using-a-pretrained-convnet.ipynb
gu-ma/ba_218_comppx_h1901
WebApp Covid19dynstat - using Dash/JupyterDash@author: Jens Henrik Göbbert @mail: j.goebbert@fz-juelich.de The `jupyter-dash` package makes it easy to develop Plotly Dash apps from the Jupyter Notebook and JupyterLab.Just replace the standard `dash.Dash` class with the `jupyter_dash.JupyterDash` subclass. before pub...
import dash import dash_core_components as dcc import dash_html_components as html import dash_bootstrap_components as dbc from dash.dependencies import Input, Output, State import dash_player from flask_caching import Cache import os import pandas as pd #print(dcc.__version__)
_____no_output_____
BSD-3-Clause
covid19/covid19dynstat-dash.ipynb
FZJ-JSC/jupyter-jsc-dashboads
When running in JupyterHub (or Binder), call the `infer_jupyter_config` function to detect the proxy configuration. This will detect the proper request_pathname_prefix and server_url values to use when displaying Dash apps. For example: - server_url = `https://jupyter-jsc.fz-juelich.de` - request_pathname_prefix = `...
from jupyter_dash import JupyterDash JupyterDash.infer_jupyter_proxy_config()
_____no_output_____
BSD-3-Clause
covid19/covid19dynstat-dash.ipynb
FZJ-JSC/jupyter-jsc-dashboads
**Attention:** I have to run this cell twice: first press play, wait a bit and hit play again while it still shows `[*]` Create a Dash Flask serverRequests the browser to load Bootstrap
from pathlib import Path # create app app = JupyterDash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP], update_title=None, suppress_callback_exceptions=True, # because of multi-page setup ) # config app app.title = 'Covid-19-Interaktionsmod...
_____no_output_____
BSD-3-Clause
covid19/covid19dynstat-dash.ipynb
FZJ-JSC/jupyter-jsc-dashboads
Create interactive map of Germany
## load & initialize static data # => tuple-list 'counties_geojson' # => dataframe 'counties_metadf' import json # Landkreis-Geometrie vom RKI: # https://npgeo-corona-npgeo-de.hub.arcgis.com/datasets/917fc37a709542548cc3be077a786c17_0 -> ShapeFile # https://mapshaper.org -> GEOJSON with open('assets/DE-Landkreise_RKI...
_____no_output_____
BSD-3-Clause
covid19/covid19dynstat-dash.ipynb
FZJ-JSC/jupyter-jsc-dashboads
Define the top navigation bar
##################### # Disclaimer ##################### disclaimer_modal = html.Div( [ dcc.Markdown( f""" ----- ##### BSTIM-Covid19 ----- Aktuelle Daten und Vorhersage der täglich gemeldeten Neuinfektionen mit COVID-19 für Landkreise in Deutschl...
_____no_output_____
BSD-3-Clause
covid19/covid19dynstat-dash.ipynb
FZJ-JSC/jupyter-jsc-dashboads
Define the main body of the webpage https://dash-bootstrap-components.opensource.faculty.ai/docs/components/layout/ Layout in Bootstrap is controlled using the grid system.The Bootstrap grid has **twelve** columns, and **five** responsive tiers (allowing you to specify different behaviours on different screen sizes,...
##################### # Main Structure ##################### tab_height = '5vh' body_layout = dbc.Container( style={"marginTop": 100, "marginBottom": 20}, #fluid=True, children=[ ##################### # Introduction ##################### dbc.Row( ...
_____no_output_____
BSD-3-Clause
covid19/covid19dynstat-dash.ipynb
FZJ-JSC/jupyter-jsc-dashboads
Start the app
app.run_server(mode="jupyterlab", debug=True) #,port=8052,debug=True) # mode="jupyterlab" -> will open the app in a tab in JupyterLab # mode="inline" -> will open the app below this cell # mode="external" -> will displays a URL that you can click on to open the app in a browser tab
_____no_output_____
BSD-3-Clause
covid19/covid19dynstat-dash.ipynb
FZJ-JSC/jupyter-jsc-dashboads
--------------------------**Attention** If you get the error "adress in use" this can also be the case because simply your layout has an error so that a dash-app could not been started. Open the app in a new browser-tab with the url`/proxy/` where \ derives from the url of your jupyterlab and \ is by default 8050. Fo...
!echo "COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME" !lsof -i -P -n | grep LISTEN
_____no_output_____
BSD-3-Clause
covid19/covid19dynstat-dash.ipynb
FZJ-JSC/jupyter-jsc-dashboads
Topic Modeling Methods Topic modeling is a powerful tool for quickly sorting through a lot of text and documents without having to read every one. There are several methods available for this using python, as well as several libraries. Topic modeling is extremely challenging to get meaningful results. "Garbage in, gar...
import pandas as pd import re from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer, TfidfTransformer from sklearn.decomposition import NMF, LatentDirichletAllocation, TruncatedSVD from textblob import TextBlob from sklearn.preprocessing import Normalizer doc_list.read_pickle("full_proj_lemmatize...
_____no_output_____
Apache-2.0
Topic Modeling/Step 4 - Topic Modeling Method Testing.ipynb
autodidact-m/Projects
Testing ModelsTry LDA, NMF and LSA as well as adjusting of features, topics, and overlap for best results.
def print_top_words(model, feature_names, n_top_words): for topic_idx, topic in enumerate(model.components_): print("Topic #%d:" % topic_idx) print(" ".join([feature_names[i] for i in topic.argsort()[:-n_top_words - 1:-1]])) print() def modeler(corp, n_topics, n...
_____no_output_____
Apache-2.0
Topic Modeling/Step 4 - Topic Modeling Method Testing.ipynb
autodidact-m/Projects
Latent Dirchlet Allocation ModelIn natural language processing, Latent Dirichlet Allocation (LDA) is a generative statistical model that allows sets of observations to be explained by unobserved groups that explain why some parts of the data are similar. ![LDA](https://image.slidesharecdn.com/topicmodeling-14060316164...
modeler(doc_list.lem, 30, 30, LatentDirichletAllocation(n_topics=30, max_iter=5, learning_method='online', \ learning_offset=50.,random_state=0), CountVectorizer(max_df=.80, min_df=2, stop_words='english'))
_____no_output_____
Apache-2.0
Topic Modeling/Step 4 - Topic Modeling Method Testing.ipynb
autodidact-m/Projects
![](../images/lda-out.png)
LDA_mod(doc_list.lem, .95, 2, 2000,10) #df is a way to extract 'meaningful text' in this case
_____no_output_____
Apache-2.0
Topic Modeling/Step 4 - Topic Modeling Method Testing.ipynb
autodidact-m/Projects
![](../images/lda-out2.png) Notes about LDA model performanceLDA is the most frequently used model in conversations about topic modeling. LDA has proven ineffective for this project, it performs poorly at picking up subtle differences in a corpus about the same subject (as in, if I wanted to find the difference betwee...
modeler(doc_list.lem, 100, 30, TruncatedSVD(2, algorithm = 'arpack'), TfidfVectorizer(max_df=.8, min_df=2,stop_words='english'))
_____no_output_____
Apache-2.0
Topic Modeling/Step 4 - Topic Modeling Method Testing.ipynb
autodidact-m/Projects
![](../images/lsa-out.png) Notes about LSA performanceIssues similar to LDA - it's good at pulling out the law themes, but that's not really what we need. We need the law terms to not play a role at all in modeling for these topics - we know that this entire corpus is about the law, but we need to know what KIND of la...
modeler(doc_list.lem, 30, 30, NMF(n_components=30, random_state=1, alpha=.1, l1_ratio=.5), \ TfidfVectorizer(max_df=.98, min_df=2,stop_words='english'))
_____no_output_____
Apache-2.0
Topic Modeling/Step 4 - Topic Modeling Method Testing.ipynb
autodidact-m/Projects
Assignment: SQL Notebook for Peer AssignmentEstimated time needed: **60** minutes. IntroductionUsing this Python notebook you will:1. Understand the Spacex DataSet2. Load the dataset into the corresponding table in a Db2 database3. Execute SQL queries to answer assignment questions Overview of the DataSetSpace...
!pip install sqlalchemy==1.3.9 !pip install ibm_db_sa !pip install ipython-sql
Collecting sqlalchemy==1.3.9 Downloading SQLAlchemy-1.3.9.tar.gz (6.0 MB) Using legacy 'setup.py install' for sqlalchemy, since package 'wheel' is not installed. Installing collected packages: sqlalchemy Running setup.py install for sqlalchemy: started Running setup.py install for sqlalchemy: finished with st...
MIT
Week 2 - SQL/jupyter-labs-eda-sql-coursera.ipynb
pFontanilla/ibm-applied-datascience-capstone
Connect to the databaseLet us first load the SQL extension and establish a connection with the database
%load_ext sql
_____no_output_____
MIT
Week 2 - SQL/jupyter-labs-eda-sql-coursera.ipynb
pFontanilla/ibm-applied-datascience-capstone
**DB2 magic in case of old UI service credentials.**In the next cell enter your db2 connection string. Recall you created Service Credentials for your Db2 instance before. From the **uri** field of your Db2 service credentials copy everything after db2:// (except the double quote at the end) and paste it in the cell be...
%sql ibm_db_sa://gmb99703:n8jwm8hlw2k7hr^k@dashdb-txn-sbox-yp-dal09-04.services.dal.bluemix.net:50000/BLUDB %sql select TABSCHEMA, TABNAME, CREATE_TIME from SYSCAT.TABLES where TABSCHEMA='GMB99703' %sql SELECT * FROM SPACEXDATASET LIMIT 20
* ibm_db_sa://gmb99703:***@dashdb-txn-sbox-yp-dal09-04.services.dal.bluemix.net:50000/BLUDB Done. * ibm_db_sa://gmb99703:***@dashdb-txn-sbox-yp-dal09-04.services.dal.bluemix.net:50000/BLUDB Done.
MIT
Week 2 - SQL/jupyter-labs-eda-sql-coursera.ipynb
pFontanilla/ibm-applied-datascience-capstone
TasksNow write and execute SQL queries to solve the assignment tasks. Task 1 Display the names of the unique launch sites in the space mission
%sql SELECT UNIQUE LAUNCH_SITE FROM SPACEXDATASET
* ibm_db_sa://gmb99703:***@dashdb-txn-sbox-yp-dal09-04.services.dal.bluemix.net:50000/BLUDB Done.
MIT
Week 2 - SQL/jupyter-labs-eda-sql-coursera.ipynb
pFontanilla/ibm-applied-datascience-capstone