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 |
|---|---|---|---|---|---|
Now that your model has finished training it is time to test it out! You can do so by running the next cell. | new_x = 7.0
prediction = model.predict([new_x])[0]*100.
print(50+7*50)
print(prediction) | 400
[400.1458]
| MIT | Tensorflow/Courses/0_Intro_to_tf/2_Week1_Assignmen_normalized.ipynb | maxtcurie/Artificial_Intelligence |
Handwritten Number Recognition with TFLearn and MNISTIn this notebook, we'll be building a neural network that recognizes handwritten numbers 0-9. This kind of neural network is used in a variety of real-world applications including: recognizing phone numbers and sorting postal mail by address. To build the network, w... | # Import Numpy, TensorFlow, TFLearn, and MNIST data
import numpy as np
import tensorflow as tf
import tflearn
import tflearn.datasets.mnist as mnist | _____no_output_____ | MIT | intro-to-tflearn/TFLearn_Digit_Recognition.ipynb | tanmaysinha987/deep-Learning |
Retrieving training and test dataThe MNIST data set already contains both training and test data. There are 55,000 data points of training data, and 10,000 points of test data.Each MNIST data point has:1. an image of a handwritten digit and 2. a corresponding label (a number 0-9 that identifies the image)We'll call th... | # Retrieve the training and test data
trainX, trainY, testX, testY = mnist.load_data(one_hot=True) | _____no_output_____ | MIT | intro-to-tflearn/TFLearn_Digit_Recognition.ipynb | tanmaysinha987/deep-Learning |
Visualize the training dataProvided below is a function that will help you visualize the MNIST data. By passing in the index of a training example, the function `show_digit` will display that training image along with it's corresponding label in the title. | # Visualizing the data
import matplotlib.pyplot as plt
%matplotlib inline
# Function for displaying a training image by it's index in the MNIST set
def show_digit(index):
label = trainY[index].argmax(axis=0)
# Reshape 784 array into 28x28 image
image = trainX[index].reshape([28,28])
plt.title('Training... | _____no_output_____ | MIT | intro-to-tflearn/TFLearn_Digit_Recognition.ipynb | tanmaysinha987/deep-Learning |
Building the networkTFLearn lets you build the network by defining the layers in that network. For this example, you'll define:1. The input layer, which tells the network the number of inputs it should expect for each piece of MNIST data. 2. Hidden layers, which recognize patterns in data and connect the input to the ... | # Define the neural network
def build_model():
# This resets all parameters and variables, leave this here
tf.reset_default_graph()
#### Your code ####
# Include the input layer, hidden layer(s), and set how you want to train the model
net=tflearn.input_data(None,trainX.shape[1])
net=tflear... | _____no_output_____ | MIT | intro-to-tflearn/TFLearn_Digit_Recognition.ipynb | tanmaysinha987/deep-Learning |
Training the networkNow that we've constructed the network, saved as the variable `model`, we can fit it to the data. Here we use the `model.fit` method. You pass in the training features `trainX` and the training targets `trainY`. Below I set `validation_set=0.1` which reserves 10% of the data set as the validation s... | # Training
model.fit(trainX, trainY, validation_set=0.1, show_metric=True, batch_size=100, n_epoch=20) | _____no_output_____ | MIT | intro-to-tflearn/TFLearn_Digit_Recognition.ipynb | tanmaysinha987/deep-Learning |
TestingAfter you're satisified with the training output and accuracy, you can then run the network on the **test data set** to measure it's performance! Remember, only do this after you've done the training and are satisfied with the results.A good result will be **higher than 95% accuracy**. Some simple models have b... | # Compare the labels that our model predicts with the actual labels
# Find the indices of the most confident prediction for each item. That tells us the predicted digit for that sample.
predictions = np.array(model.predict(testX)).argmax(axis=1)
# Calculate the accuracy, which is the percentage of times the predicate... | _____no_output_____ | MIT | intro-to-tflearn/TFLearn_Digit_Recognition.ipynb | tanmaysinha987/deep-Learning |
Pandas | import numpy as np
import pandas as pd | _____no_output_____ | MIT | docs/Pandas.ipynb | hotbaby/mmn |
Pandas提供了3种数据类型,分别是`Series`、`DataFrame`和`Panel`。* `Series`用于保存一维数据* `DataFrame` 用于保存二维数据* `Panel`用于保存三维或者可变维数据 Series数据结构 `Series`本质上是一个带索引的一维数组。 指定索引: | s = pd.Series([1,3,2,4], index=['a', 'b', 'c', 'd'])
s.index
s.values | _____no_output_____ | MIT | docs/Pandas.ipynb | hotbaby/mmn |
默认索引: | s = pd.Series([1, 3, 2, 4])
s.index
s.values | _____no_output_____ | MIT | docs/Pandas.ipynb | hotbaby/mmn |
DataFrame数据结构 创建DataFrame | df = pd.DataFrame({'x': ['a', 'b', 'c'],
'y': range(1, 4),
'z': [2, 5, 3]})
df
df.columns
df.values | _____no_output_____ | MIT | docs/Pandas.ipynb | hotbaby/mmn |
查看数据内容 * `df.info()` 查看DataFrame属性信息* `df.head()` 查看DataFrame前五行数据信息* `df.tail()` 查看DataFrame后五行数据信息 选取多列 * df.loc* df.iloc | df[['x', 'y']]
df.loc[:, ['x', 'y']]
df.iloc[:, [0, 1]] | _____no_output_____ | MIT | docs/Pandas.ipynb | hotbaby/mmn |
单行过滤 | df[df.z>=3] | _____no_output_____ | MIT | docs/Pandas.ipynb | hotbaby/mmn |
重新定义列名 | df.rename(columns={'x': 'X'}, inplace=True)
df
df.columns = ['X', 'Y', 'Z']
df | _____no_output_____ | MIT | docs/Pandas.ipynb | hotbaby/mmn |
数据的多重索引 | df = pd.DataFrame({
'X': list('ABCABC'),
'year': [2010] * 3 + [2011] * 3,
'Value': [1, 3, 4, 3, 5, 2]
})
df
df.set_index(['X', 'year']) | _____no_output_____ | MIT | docs/Pandas.ipynb | hotbaby/mmn |
表格的变换 | df = pd.DataFrame({
'X': list('ABC'),
'2010': [1, 3, 4],
'2011': [3, 5, 2]
})
df
df_melt = pd.melt(df, id_vars='X', var_name='year', value_name='value')
df_melt | _____no_output_____ | MIT | docs/Pandas.ipynb | hotbaby/mmn |
* `id.vars('X')`表示由标识变量构成的向量,用于标识观测的变量* `variable_name('year')`表示用于保存原始变量名的变量名称* `value.name('value')`表示用于保存原始值的名称 | df_pivot = df_melt.pivot_table(index='X', columns='year', values='value')
df_pivot.reset_index(inplace=True)
df_pivot | _____no_output_____ | MIT | docs/Pandas.ipynb | hotbaby/mmn |
变量的变换 * `apply`的操作对象是`DataFrame`的某一列(`axis`=0)或者某一列(`axis`=1)* `applymap`的操作对象是元素级,作用于每个`DataFrame`的每个数据 表格的排序 `df.sort_values(by, ascending=True)` | df
df.sort_values('2010', ascending=False)
df.sort_values('2011', ascending=True)
df.sort_values(by=['X', '2010'], ascending=False) | _____no_output_____ | MIT | docs/Pandas.ipynb | hotbaby/mmn |
表格拼接 | df1 = pd.DataFrame({
'x': ['a', 'b', 'c'],
'y': range(1, 4),
})
df2 = pd.DataFrame({
'z': ['B', 'D', 'H'],
'g': [2, 5, 3]
})
df3 = pd.DataFrame({
'x': ['g', 'd'],
'y': [2, 5]
}) | _____no_output_____ | MIT | docs/Pandas.ipynb | hotbaby/mmn |
横轴方向连接 | pd.concat([df1, df2], axis=1) | _____no_output_____ | MIT | docs/Pandas.ipynb | hotbaby/mmn |
纵轴方向连接 | pd.concat([df1, df3], axis=0).reset_index() | _____no_output_____ | MIT | docs/Pandas.ipynb | hotbaby/mmn |
表的融合 | df1 = pd.DataFrame({
'x': list('abc'),
'y': range(1, 4)
})
df2 = pd.DataFrame({
'x': list('abd'),
'z': [2, 5, 3]
})
df3 = pd.DataFrame({
'g': list('abd'),
'z': [2, 5, 3]
})
df1
df2
df3 | _____no_output_____ | MIT | docs/Pandas.ipynb | hotbaby/mmn |
只保留左表的所有数据 | pd.merge(df1, df2, how='left', on='x') | _____no_output_____ | MIT | docs/Pandas.ipynb | hotbaby/mmn |
只保留右表的数据 | pd.merge(df1, df2, how='right', on='x') | _____no_output_____ | MIT | docs/Pandas.ipynb | hotbaby/mmn |
保留两个表中公共的部分信息 | pd.merge(df1, df2, how='inner', on='x') | _____no_output_____ | MIT | docs/Pandas.ipynb | hotbaby/mmn |
保留两个表的所有信息 | pd.merge(df1, df2, how='outer', on='x') | _____no_output_____ | MIT | docs/Pandas.ipynb | hotbaby/mmn |
表格分组操作 | df = pd.DataFrame({
'X': list('ABC'),
'2010': [1, 3, 4],
'2011': [3, 5, 2]
})
df | _____no_output_____ | MIT | docs/Pandas.ipynb | hotbaby/mmn |
按行或列操作 按行求和 | df[['2010', '2011']].apply(lambda x: x.sum(), axis=1) | _____no_output_____ | MIT | docs/Pandas.ipynb | hotbaby/mmn |
按列求和 | df[['2010', '2011']].apply(lambda x: x.sum(), axis=0) | _____no_output_____ | MIT | docs/Pandas.ipynb | hotbaby/mmn |
多列运算 | df['2010_2011'] = df[['2010', '2011']].apply(lambda x: x['2010'] + 2 * x['2011'], axis=1)
df | _____no_output_____ | MIT | docs/Pandas.ipynb | hotbaby/mmn |
分组操作 | df = pd.DataFrame({
'X': list('ABC'),
'2010': [1, 3, 4],
'2011': [3, 5, 2]
})
df_melt = pd.melt(df, id_vars=['X'], var_name='year', value_name='value')
df_melt | _____no_output_____ | MIT | docs/Pandas.ipynb | hotbaby/mmn |
按`year`分组求均值 | df_melt.groupby('year').mean() | _____no_output_____ | MIT | docs/Pandas.ipynb | hotbaby/mmn |
按`year`和`x`两列分组求均值 | df_melt.groupby(['year', 'X']).mean()
df_melt.groupby(['year', 'X'], as_index=False).mean() | _____no_output_____ | MIT | docs/Pandas.ipynb | hotbaby/mmn |
分组聚合 | df_melt.groupby(['X', 'year']).aggregate([np.mean, np.median]) | _____no_output_____ | MIT | docs/Pandas.ipynb | hotbaby/mmn |
分组运算:`transform()`函数 | df_melt['percentage'] = df_melt.groupby('X')['value'].transform(lambda x: x/s.sum())
df_melt | _____no_output_____ | MIT | docs/Pandas.ipynb | hotbaby/mmn |
分组筛选:`filter()`函数 | df_melt.groupby('X').filter(lambda x: x['value'].mean()>2) | _____no_output_____ | MIT | docs/Pandas.ipynb | hotbaby/mmn |
Toy Datasets | # For Base cohort
age = 45
lab1 = 3.4
lab2 = 5000
pcond1 = 0.3
pcat1 = 0.5
mean = [age, lab1, lab2]
cov = [[14, 3, 100],
[3, 2, 50],
[100, 50, 25000]]
np.random.seed(42)
x = np.random.multivariate_normal(mean, cov, config['nbase'])
x[x< 0] = 0
lab3 = np.random.beta(1, 2, size=config['nbase'])
x = np.... | Distribution of age
Before balancing -1.2072887363365403
After balancing -0.18460449201331947
Distribution of lab1
Before balancing -1.127079119575515
After balancing -0.1807599351241777
Distribution of lab2
Before balancing 0.8934273136316265
After balancing 0.31464657671400276
Distribution of lab3
Before balanc... | MIT | cohortbalancer-function.ipynb | csrinesh/balance_cohort |
Índice 1 - Análise de Sentimentos: uma introdução 2 - Carregando os pacotes necessários 3 - Conectando com a API do Twitter 3.1 - Autenticação 3.2 - Obtendo os tweets 4 - Text Mining 5 - Manipulação de dados 5.1 - Tokenização 5.2 - Núvem de palavras 6 - Removendo as Stopwords 7 - Dicionário Léxico 8 - Resultados... | #Install
install.packages("twitteR")
install.packages("rvest")
install.packages("tidyverse")
install.packages("tidytext")
install.packages("tm") # for text mining
install.packages("SnowballC") # for text stemming
install.packages("wordcloud") # word-cloud generator
install.packages("RColorBrewer") # color palettes
in... | Warning message:
"package 'twitteR' was built under R version 3.6.1"Warning message:
"package 'rvest' was built under R version 3.6.1"Loading required package: xml2
Warning message:
"package 'xml2' was built under R version 3.6.1"Warning message:
"package 'tidyverse' was built under R version 3.6.1"-- Attaching package... | MIT | SentimentAnalysisOnTwitterWithR.ipynb | JPedro-loureiro/Sentiment-Analysis-on-Twitter-R |
3 - Conectando com a API do Twitter 3.1 - AutenticaçãoApós instalarmos e carregarmos todos os pacotes necessários, iremos efetuar a conexão com o Twitter através do pacote "TwitteR". Para isso precisamos das chaves de autenticação da API do twitter. | #API's and Token's keys
API_key = "hhrTn58RfcBoxjpGdvQbLTf6v"
API_secret_key = "r6zON2bTvFv8qlaEDWWaIowRknxRxc97EGENdSBfdXZlFmkmrm"
Access_token = "4928132291-OFnrrwGy5FKHLPePkUsxLA5exJwrbJ7l51azMWV"
Access_token_secret = "q7inW05npl3S70yRihMkJdasF0roZyrlzZW46D1XTSbDd"
#OAuth
setup_twitter_oauth(API_key, API_secret_ke... | [1] "Using direct authentication"
| MIT | SentimentAnalysisOnTwitterWithR.ipynb | JPedro-loureiro/Sentiment-Analysis-on-Twitter-R |
3.2 - Obtendo os TweetsEm seguida, iremos criar uma função que solicita ao usuário uma palavra chave ou hashtag a ser buscada, a quantidade de tweets por dia, o idioma, a localidade e as datas iniciais e finais nas quais a pesquisa será feita. De posse destas informações, a função irá buscar os tweets de acordo com os... | #Search Twitters
search_twiter <- function(){
#This function search for a specific number of tweets per day in a range of dates
#Return a Tibble whith 3 columns: 1- TweetID; 2- Date; 3- Tweet;
#Search string
search_string <- paste(readline(prompt = "A wordkey or a hashtag: "), " -filter:retweets") #An exempl... | A wordkey or a hashtag: flamengo
The number of tweets per day: 500
Language (ex.: pt): pt
Tweets locale (ex.: br): br
The inicial date (yyyy-mm-dd): 2019-07-16
The final date (yyyy-mm-dd): 2019-07-23
| MIT | SentimentAnalysisOnTwitterWithR.ipynb | JPedro-loureiro/Sentiment-Analysis-on-Twitter-R |
Vamos dar uma olhada nos tweets que coletamos! | head(tweets_df) | _____no_output_____ | MIT | SentimentAnalysisOnTwitterWithR.ipynb | JPedro-loureiro/Sentiment-Analysis-on-Twitter-R |
4 - Text MiningNote que temos 3500 observações e 3 colunas na nossa tabela. Porém, a terceira coluna é uma lista que contém todas as informações sobre os tweets coletados. É importante ter em mente que um tweet não é representado apenas pelo seu texto, mas sim por outras informações também, como por exemplo, o seu ID,... | #Cleaning tweets
clean_tweets <- function(tweets){
#Getting tweets texts
tweets = sapply(tweets, function(x) x$text)
#Remove retweet entities
tweets = gsub('(RT|via)((?:\\b\\W*@\\w+)+)', "", tweets)
#Remove Hashtags
tweets = gsub('#\\w+', "", tweets)
#Remove links
tweets = gsub('http\\w+', "... | _____no_output_____ | MIT | SentimentAnalysisOnTwitterWithR.ipynb | JPedro-loureiro/Sentiment-Analysis-on-Twitter-R |
Embora os tweets ainda apresentem alguns caracteres estranhos, podemos dizer que temos nossos textos devidamente coletados. Estes caracteres estranhos serão tratados mais adiante. | head(tweets_df) | _____no_output_____ | MIT | SentimentAnalysisOnTwitterWithR.ipynb | JPedro-loureiro/Sentiment-Analysis-on-Twitter-R |
5 - Manipulação de dados 5.1 - TokenizaçãoNeste tópico iremos fazer a manipulação dos dados. O objetivo aqui é ter uma tabela onde cada registro possui uma única palavra, mantendo sempre a referência a qual tweet esta palavra pertence. Isso será muito útil para as análises seguintes. | #Tokenization
tweets_tokens <- tweets_df %>%
unnest_tokens(words, tweets)
head(tweets_tokens, 25) | _____no_output_____ | MIT | SentimentAnalysisOnTwitterWithR.ipynb | JPedro-loureiro/Sentiment-Analysis-on-Twitter-R |
5.2 - Núvem de palavrasA fim de visualizar as palavras que são mais comuns dentre os tweets, vamos criar uma outra função que gera uma núvem de palavras. | wc <- function(tweets_tokens){
plot <- tweets_tokens %>%
group_by(words) %>%
summarise(freq = n()) %>%
filter(words != "ifood")
wordcloud(words = plot$words, freq = plot$freq, min.freq = 1,
max.words=200, random.order=FALSE, rot.per=0.35,
colors=brewer.pal(8, "Dark2"))
}
wc(... | _____no_output_____ | MIT | SentimentAnalysisOnTwitterWithR.ipynb | JPedro-loureiro/Sentiment-Analysis-on-Twitter-R |
6 - StopwordsNote que a palavra mais comum é "flamengo" pois é o tema da nossa pesquisa e é seguida por várias outras palavras que não tem muito peso semântico.Essas palavras são conhecidas como "stopwords". As stopwords são palavras que são comumente usadas e não possuem grande relevância para a semântica do texto. C... | #Stopwords
stopwords <- stopwords(language = "pt", source = "stopwords-iso")
stopwords <- tibble(stopwords)
head(stopwords)
tweets_tokens <- tweets_tokens %>%
anti_join(stopwords, by = c("words" = "stopwords")) | _____no_output_____ | MIT | SentimentAnalysisOnTwitterWithR.ipynb | JPedro-loureiro/Sentiment-Analysis-on-Twitter-R |
7 - Dicionário LéxicoAté aqui, o que fizemos foi apenas limpar e manipular os dados. Neste tópico daremos início à análise de sentimentos.O primeiro passo consiste em carregarmos o dicionário léxico. Este dicionário léxico contém uma coluna que indica qual a polaridade das palavras, ou seja, se uma palavra é tida como... | #LexiconPT
lex_pt <- oplexicon_v3.0
head(lex_pt) | _____no_output_____ | MIT | SentimentAnalysisOnTwitterWithR.ipynb | JPedro-loureiro/Sentiment-Analysis-on-Twitter-R |
Em seguida iremos cruzar as palavras dos tweets com as palavras do dicionário léxico, atribuindo uma polaridade para cada palavra dos tweets. Para isso, usaremos a função "inner_join". | tweets_tokens <- tweets_tokens %>%
inner_join(lex_pt, by = c("words" = "term")) %>%
select(tweetID, date, words, polarity)
head(tweets_tokens) | _____no_output_____ | MIT | SentimentAnalysisOnTwitterWithR.ipynb | JPedro-loureiro/Sentiment-Analysis-on-Twitter-R |
Agora iremos visualizar novamente uma núvem de palavras para entender como a retirada das stopwords e cruzamento com o dicionário léxico afetaram nossos tweets. | wc(tweets_tokens) | _____no_output_____ | MIT | SentimentAnalysisOnTwitterWithR.ipynb | JPedro-loureiro/Sentiment-Analysis-on-Twitter-R |
8 - ResultadosApós feita a polarização das palavras contidas nos tweets, vamos utilizar esses dados para extrair melhores informações dos textos. 8.1 - Top 10 tweets "positivos" | #Most positive tweets
top_10_pos <- tweets_tokens %>%
group_by(tweetID) %>%
summarise(polarity = sum(polarity)) %>%
arrange(desc(polarity)) %>%
head(10)
#Ordering
top_10_pos$tweetID <- factor(top_10_pos$tweetID,
levels = unique(top_10_pos$tweetID[order(top_10_pos$polarity,
... | _____no_output_____ | MIT | SentimentAnalysisOnTwitterWithR.ipynb | JPedro-loureiro/Sentiment-Analysis-on-Twitter-R |
8.2 - Top 10 tweets "negativos" | #Most negative tweets
top_10_neg <- tweets_tokens %>%
group_by(tweetID) %>%
summarise(polarity = sum(polarity)) %>%
arrange(polarity) %>%
head(10)
#Ordering
top_10_neg$tweetID <- factor(top_10_neg$tweetID,
levels = unique(top_10_neg$tweetID)[order(top_10_neg$polarity,
... | _____no_output_____ | MIT | SentimentAnalysisOnTwitterWithR.ipynb | JPedro-loureiro/Sentiment-Analysis-on-Twitter-R |
8.3 - Overview da análise de sentimentosO gráfico a seguir categoriza os tweets como "positivos", "negativos" e "neutros" e mostra qual a quantidade de tweets por categoria. | #Sentiment Analysis Overview
tweets_tokens %>%
group_by(tweetID) %>%
summarise(polarity = sum(polarity)) %>%
mutate(class = ifelse(polarity > 0, "positive",
ifelse(polarity < 0, "negative", "neutral"))) %>%
count(class) %>%
ggplot(aes(factor(class), n, fill = class)) +
geom_col() +
... | _____no_output_____ | MIT | SentimentAnalysisOnTwitterWithR.ipynb | JPedro-loureiro/Sentiment-Analysis-on-Twitter-R |
8.4 - Análise de sentimentos em série temporalEste gráfico mostra como foi a sentimento dos usuários em relação ao tema ao longo do período determinado na busca. | #Time series
tweets_tokens %>%
group_by(date) %>%
summarise(polarity = sum(polarity)) %>%
ggplot(aes(date, polarity, group = 1)) +
geom_line() +
ggtitle("Polarity x Date") | _____no_output_____ | MIT | SentimentAnalysisOnTwitterWithR.ipynb | JPedro-loureiro/Sentiment-Analysis-on-Twitter-R |
Linear Discriminate Analysis (LDA) | import numpy as np
import matplotlib.pyplot as plt
# data generation
mean1=np.array([0,0])
mean2=np.array([4,5])
var=np.array([[1,0.1],[0.1,1]])
np.random.seed(0)
data1=np.random.multivariate_normal(mean1,var,500)
data2=np.random.multivariate_normal(mean2,var,500)
data=np.concatenate((data1,data2))
label=np.concatena... | KNN Training accuracy = 100.0
KNN Testing accuracy = 100.0
| Apache-2.0 | Dimensionality Reduction/LDA/LDA_Algo.ipynb | Abhi10398/Machine-Learning |
LDA multiclass 1. 3 class Sythetic data2. Homework: Mnist 3 class and 10 class | import numpy as np
import matplotlib.pyplot as plt
mean1=np.array([0,0])
mean2=np.array([4,5])
mean3=np.array([-5,-4])
var=np.array([[1,0.1],[0.1,1]])
np.random.seed(0)
data1=np.random.multivariate_normal(mean1,var,500)
data2=np.random.multivariate_normal(mean2,var,500)
data3=np.random.multivariate_normal(mean3,var,50... | KNN Training accuracy = 99.93333333333332
KNN Testing accuracy = 100.0
| Apache-2.0 | Dimensionality Reduction/LDA/LDA_Algo.ipynb | Abhi10398/Machine-Learning |
Test suite for Jupyter-notebook First stepImport ipycompss library | import pycompss.interactive as ipycompss | _____no_output_____ | Apache-2.0 | compss/programming_model/bindings/python/src/pycompss/tests/resources/notebook/simple.ipynb | eflows4hpc/compss |
Second step Initialize COMPSs runtime | ipycompss.start(graph=True, trace=True, debug=True) | _____no_output_____ | Apache-2.0 | compss/programming_model/bindings/python/src/pycompss/tests/resources/notebook/simple.ipynb | eflows4hpc/compss |
Third stepImport task module before annotating functions or methods | from pycompss.api.task import task | _____no_output_____ | Apache-2.0 | compss/programming_model/bindings/python/src/pycompss/tests/resources/notebook/simple.ipynb | eflows4hpc/compss |
Other declarations | MY_GLOBAL = 2
class myClass(object):
def __init__(self):
self.value = 1
def divide(a, b):
def is_zero(value):
if value == 0:
raise True
else:
return False
if not is_zero(b):
return a / b
else:
raise Exception("Can not divide by 0.")
def mu... | _____no_output_____ | Apache-2.0 | compss/programming_model/bindings/python/src/pycompss/tests/resources/notebook/simple.ipynb | eflows4hpc/compss |
Fourth stepDeclare functions and decorate with @task those that should be tasks | @task(returns=int)
def test(val1):
return multiply(val1, val1)
@task(returns=int)
def test2(val2, val3):
return val2 + val3
@task(returns=int)
def test3(val2, val3):
return divide(val2, val3) | _____no_output_____ | Apache-2.0 | compss/programming_model/bindings/python/src/pycompss/tests/resources/notebook/simple.ipynb | eflows4hpc/compss |
Fifth stepInvoke tasks | a = test(2)
b = test2(a, 5)
c = test3(a, 2) | _____no_output_____ | Apache-2.0 | compss/programming_model/bindings/python/src/pycompss/tests/resources/notebook/simple.ipynb | eflows4hpc/compss |
Sixt step Import compss_wait_on module and synchronize tasks | from pycompss.api.api import compss_wait_on
result = compss_wait_on(b) | _____no_output_____ | Apache-2.0 | compss/programming_model/bindings/python/src/pycompss/tests/resources/notebook/simple.ipynb | eflows4hpc/compss |
Only those results being sychronized with compss_wait_on will have a valid value | print("Results: ")
print("a: ", a)
print("b: ", b)
print("c: ", c)
print("result: ", result) | _____no_output_____ | Apache-2.0 | compss/programming_model/bindings/python/src/pycompss/tests/resources/notebook/simple.ipynb | eflows4hpc/compss |
Stop COMPSs runtime. All data will be synchronized in the main program | ipycompss.stop(sync=True)
print("Results after stopping PyCOMPSs: ")
print("a: ", a)
print("b: ", b)
print("c: ", c)
print("result: ", result) | _____no_output_____ | Apache-2.0 | compss/programming_model/bindings/python/src/pycompss/tests/resources/notebook/simple.ipynb | eflows4hpc/compss |
CHECK THE RESULTS FOR THE TEST | from pycompss.runtime.management.classes import Future
if a == 4 and isinstance(b, Future) and result == 9 and c == 2:
print("RESULT=EXPECTED")
else:
raise Exception("RESULT=UNEXPECTED") | _____no_output_____ | Apache-2.0 | compss/programming_model/bindings/python/src/pycompss/tests/resources/notebook/simple.ipynb | eflows4hpc/compss |
AirBnB Data anaylst 1. Business Understanding: This project aims to follow the CRISP-DM to address the three questions which related to business or real-world applications. The dataset is picked up from Kaggle, contributed by AirBnB, which contains the rent data about Seattle. I would like to process whole data and t... | # import libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
% matplotlib inline
#load data
listing = pd.read_csv('listings.csv')
## to check the feature of the dataset, then fliter
listing.columns.values | _____no_output_____ | CNRI-Python | Project1.ipynb | Howie4PP/Airbnb_Data_Analyst |
Q1. What features influence the rating of house? 2.1 Pre-processing data - the null value columns | ## check the missing value
listing.isnull().mean().sort_values()
## calculate how many column has missing value
miss_num = np.sum(listing.isnull().mean() != 0)
miss_num
# visulize the missing data
plt.figure(figsize=(20,8))
(listing.isnull().sum(axis = 0).sort_values(ascending=False)[:miss_num]/len(listing)*100).plo... | _____no_output_____ | CNRI-Python | Project1.ipynb | Howie4PP/Airbnb_Data_Analyst |
As we can see above, the features of "security_deposit", "monthly_price", "square_feet" and "license" are missing more than 50% values, and these features are unnecessary for the project, thus, I will drop them. Technically, I will make a copy of original data. | #back up dataset
listing_backup = listing.copy()
# drop the columns which lose more than 50% missing value
listing = listing.drop(['security_deposit', 'monthly_price', 'square_feet', 'license'], axis = 1)
## check again, I have dropped them all
listing.isnull().mean().sort_values()
# check and summary the column of mi... | _____no_output_____ | CNRI-Python | Project1.ipynb | Howie4PP/Airbnb_Data_Analyst |
Currently, the dataset has 88 features. Although the column of 'Weekly_price' quite close 50%, it may will be used, just keep it first. However, I think the dataset still contain some outliers and useless data, I will continue to process. 2.2 Processing the outliers and useless data 2.2.1, As the final target is pred... | def drop_columns(m_columns):
listing.drop(columns = m_columns, inplace = True)
drop_columns = ['id', 'notes']
drop_columns(drop_columns) | _____no_output_____ | CNRI-Python | Project1.ipynb | Howie4PP/Airbnb_Data_Analyst |
2.2.2 When I check the features, I found the values of some columns are link, which also could be defined as useless data. | ## the column contains key word of 'url'
url_col=[col for col in listing.columns.values if 'url' in col]
url_col
drop_columns(url_col) | _____no_output_____ | CNRI-Python | Project1.ipynb | Howie4PP/Airbnb_Data_Analyst |
2.2.3 Furthermore, there are some wired values, which means whole column only one value. I think those data won't help me to predict, drop it! | unique_col=[col for col in listing.columns.values if listing[col].nunique()==1]
unique_col
drop_columns(unique_col) | _____no_output_____ | CNRI-Python | Project1.ipynb | Howie4PP/Airbnb_Data_Analyst |
2.2.4 Next, after checking again, I think some columns that contains 'host', which may not be relevant for the prediction. For instance, 'host_id', 'host_name', 'host_since', 'host_location', 'host_about', 'host_verifications', 'host_neighbourhood'. Same operate as before. Drop it. | drop_cols=['host_id', 'host_name', 'host_since', 'host_location', 'host_about', 'host_verifications', 'host_neighbourhood']
drop_columns(drop_cols) | _____no_output_____ | CNRI-Python | Project1.ipynb | Howie4PP/Airbnb_Data_Analyst |
2.2.5 Lastly, the unstructured and redundant data. Some columns, such as City, State, Street, smart_location, latitude and longitude, could be represented by other value - zipcode. Therefore, they can be dropped | drop_cols=['city','street','state','smart_location','latitude','longitude', 'neighbourhood_cleansed']
drop_cols ## It shows what is the columns I will drop
drop_columns(drop_cols)
#drop columns containing unstructured data
drop_cols=['name','summary', 'space', 'description', 'neighborhood_overview','transit', 'first_re... | _____no_output_____ | CNRI-Python | Project1.ipynb | Howie4PP/Airbnb_Data_Analyst |
2.3 Filling up missing value and transferring categorical data 2.3.1 transferring categorical data | # Creating a table to visual the total value
pd.merge(pd.DataFrame(listing.dtypes,columns=['datatype']).reset_index(),
pd.DataFrame(pd.DataFrame(listing.iloc[0]).reset_index()),on='index')
# get the name of columns which contain categorical data
listing.select_dtypes(include=['object']).columns
# to check uniq... | _____no_output_____ | CNRI-Python | Project1.ipynb | Howie4PP/Airbnb_Data_Analyst |
2.3.2 Engineering for 'amenities' column Next I will engineer 'amenities' column to extract categorical variables. Since the amenities column is in the form of list of amenities, I will extract each amenity and it would be its own categorical feature for each listing. | # process the data of amenities column, splite it first
listing.amenities = listing.amenities.str.replace("[{}]", "")
amenities_col = listing.amenities.str.get_dummies(sep = ",")
listing_cleaned = pd.merge(listing, amenities_col, left_index=True, right_index=True)
# drop the amenities column now that is has been oneho... | _____no_output_____ | CNRI-Python | Project1.ipynb | Howie4PP/Airbnb_Data_Analyst |
2.3.3 Checking missing value and filling up | # check what column has missing value
listing_cleaned.isnull().mean().sort_values()
# summary the missing value column and to find out what is value of them, ready to fill up
missing_cols = ['beds','host_listings_count','host_total_listings_count','bedrooms','bathrooms',
'host_response_rate','review_sco... | beds : [ 1. 7. 2. 3. 15. 5. 4. 6. 9. 8. nan 10.]
host_listings_count : [ 3. 6. 2. 1. 5. 9. 4. 36. 354. 8. 37. 7. 34. 10.
13. 21. 11. 169. 48. 502. 12. nan 18. 19. 15. 84. 163. 17.]
host_total_listings_count : [ 3. 6. 2. 1. 5. 9. 4. 36. 354. 8. 37. 7. 34. ... | CNRI-Python | Project1.ipynb | Howie4PP/Airbnb_Data_Analyst |
As we can see, for the host_acceptance_rate column, there are only 3 unique values, which including Nan. Hence, I will drop this column as it does not offer an useful information. | #drop host_acceptance_rate column
listing_cleaned.drop(columns='host_acceptance_rate',inplace=True) | _____no_output_____ | CNRI-Python | Project1.ipynb | Howie4PP/Airbnb_Data_Analyst |
Weekly price be dropped. In my mind, firstly, it lost almost 50% data, it is not an accurate data. Next, it could be the target value to be predicted, but not an independant value. | # drop the weekly_price column
listing_cleaned.drop(columns='weekly_price',inplace=True)
# Transfer String to float
dollar_cols = ['cleaning_fee', 'extra_people', 'price']
listing_cleaned[dollar_cols]=listing_cleaned[dollar_cols].replace('[\$,]', '', regex=True).astype(float)
percent_cols = ['host_response_rate']
listi... | _____no_output_____ | CNRI-Python | Project1.ipynb | Howie4PP/Airbnb_Data_Analyst |
There are many missing values in review related features because these are new listings and don't get reviewed yet. In reality, travellers usually prefer listings with high number of reviews and high review scores. It might be possible to use a form of clustering to make a better estimate for this feature by looking at... | # fill up missing value with mean of their column
for x in missing_cols:
listing_cleaned[x] = listing_cleaned[x].fillna(listing_cleaned[x].mean())
# check whether the missing value is appear
listing_cleaned.isnull().mean().sort_values() | _____no_output_____ | CNRI-Python | Project1.ipynb | Howie4PP/Airbnb_Data_Analyst |
3. Modelling Base on the Q1 of business understanding, I will check which feature influnce the rating of the house. Thus, 'review_scores_rating' would be the target(dependent) variable. | # split the data into different column, prepare to create a model
y = listing_cleaned['review_scores_rating']
X = listing_cleaned.drop(['review_scores_rating'], axis = 1)
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeRegressor ### I use Decision Tree as there are a lot of fea... | _____no_output_____ | CNRI-Python | Project1.ipynb | Howie4PP/Airbnb_Data_Analyst |
Apparently, many reiviews that has a extermely imporant coefficients with the rating! More reviews which means the house always be the best choice, and people would follow this trend when they are choosing. Besides, we can see that price is an important factor for rating (I think so, price always play a key role, ... | # loading data
calendar = pd.read_csv('calendar.csv')
calendar.head() | _____no_output_____ | CNRI-Python | Project1.ipynb | Howie4PP/Airbnb_Data_Analyst |
4.2 Pre-processing data | # a lot of missing value in 'Price', but we are not interest it. :)
calendar.isnull().sum()
# drop the column that I dont use
alendar.drop(columns = 'price').head(5)
# to find out when is busy days
popular_time=calendar[calendar['available']=='f']
#group dataset by date
popular_time=popular_time.groupby('date')['listi... | _____no_output_____ | CNRI-Python | Project1.ipynb | Howie4PP/Airbnb_Data_Analyst |
It could no be clearly see from this graph, we still need to sort it | # to list the data that what I need
popular_time.sort_values(ascending=False).head(50) | _____no_output_____ | CNRI-Python | Project1.ipynb | Howie4PP/Airbnb_Data_Analyst |
As we can see, January and July are the popular time for this area. Then, combining the results of question 1 and question 2, whatever is a host or a customer, they could make a strategy that how to improve the rating or attract the customer. Q3.Could we create a model to predict the price? Actually same with Q1, I wo... | # We use the data after cleaning
y_st = listing_cleaned.price
X_st = listing_cleaned.drop(['price'], axis = 1)
X_train_st, X_test_st, y_train_st, y_test_st = train_test_split(X_st, y_st, test_size = .20, random_state=42)
# Check the datasets
print(X_train_st.shape, y_train_st.shape)
print( X_test_st.shape, y_test_st.... | The r-squared for the model is: 0.412996290368991
| CNRI-Python | Project1.ipynb | Howie4PP/Airbnb_Data_Analyst |
Import LIbraries | import pandas as pd
import numpy as np | _____no_output_____ | MIT | Notebooks/Preview_Data_Visualization.ipynb | BrunoGeraldine/Python_Zero_To_DS |
Loading Data | data = pd.read_csv( 'datasets/kc_house_data.csv' )
# Ploting data
data.head() | _____no_output_____ | MIT | Notebooks/Preview_Data_Visualization.ipynb | BrunoGeraldine/Python_Zero_To_DS |
Business questions: 1. How many homes are available for purchase? | # Counting number of lines the same number of houses
# len(data['id'].unique())
# Or using .drop function (remove od duplicados e conta novamente)
# Estrategy:
# 1. Select "id" column;
# 2. Remov repeated value;
# 3. Count the number of unique values.
houses = len(data['id'].drop_duplicates())
print('The number of avai... | The number of avaible houses are 21436
| MIT | Notebooks/Preview_Data_Visualization.ipynb | BrunoGeraldine/Python_Zero_To_DS |
2. How many attributes do houses have? | # Estrategy:
# 1. Count the number os columns;
# 2. Remove values "id", "date" (they are not attributes):
attributes = len(data.drop(['id', 'date'], axis = 1).columns)
print('The houses have {} attributes'.format(attributes)) | The houses have 19 attributes
| MIT | Notebooks/Preview_Data_Visualization.ipynb | BrunoGeraldine/Python_Zero_To_DS |
3. What are the attributes of houses? | ## Estrategy:
# 1. Plot the columns.
attributes2 = data.drop(['id', 'date'], axis=1).columns
print('The attributes are: {}'.format(attributes2)) | The attributes are: Index(['price', 'bedrooms', 'bathrooms', 'sqft_living', 'sqft_lot', 'floors',
'waterfront', 'view', 'condition', 'grade', 'sqft_above',
'sqft_basement', 'yr_built', 'yr_renovated', 'zipcode', 'lat', 'long',
'sqft_living15', 'sqft_lot15'],
dtype='object')
| MIT | Notebooks/Preview_Data_Visualization.ipynb | BrunoGeraldine/Python_Zero_To_DS |
4. What is the most expensive house (house with the highest sale price)? | # Estrategy:
# 1. Arrange the price column from highest to lowest
# 2. Apply reset index to recount rows and ensure correct result;
# 3. Collect the value and id from the first row.
data[['id','price']].sort_values('price', ascending=False).head() # 1
exphouse = data[['id','price']].sort_values('price', ascending=Fal... | The most expensive House is: id 6762700020 price U$7700000.0
| MIT | Notebooks/Preview_Data_Visualization.ipynb | BrunoGeraldine/Python_Zero_To_DS |
5. Which house has the most bedrooms? | # Estrategy:
# 1. Arrange the bedroom column from highest to lowest;
# 2. Apply reset index to recount rows and ensure correct result;
# 3. Collect the value and id from the first row.
data[["id","bedrooms"]].sort_values("bedrooms", ascending=False).head() # 1
bedroomsid = data[['id','bedrooms']].sort_values('bedrooms'... | The house with the most bedrooms is 2402100895 and have 33 bedroomns
| MIT | Notebooks/Preview_Data_Visualization.ipynb | BrunoGeraldine/Python_Zero_To_DS |
6. What is the sum total of bedrooms in the dataset? | # Estrategy:
# 1. Filter the columns "bedrooms" and sum this value.
bedroomsnumber = data['bedrooms'].sum()
print('There are a total of {} bedrooms'.format(bedroomsnumber)) | There are a total of 72854 bedrooms
| MIT | Notebooks/Preview_Data_Visualization.ipynb | BrunoGeraldine/Python_Zero_To_DS |
7. How many houses have 2 bathrooms? | # Estrategy:
# 1. Find the number of houses whit 2 bathrooms;
# 2. Select columns "id" and "bathroom";
# 3. Sum the number of houses.
data.loc[data['bathrooms'] == 2, ['id', 'bathrooms']] # 1
bethroomsum = data.loc[data['bathrooms'] == 2, ['id', 'bathrooms']].shape # 2 and 3
print('There are a total of {} bethrooms'.f... | There are a total of (1930, 23) bethrooms
| MIT | Notebooks/Preview_Data_Visualization.ipynb | BrunoGeraldine/Python_Zero_To_DS |
8. What is the average price of all houses in the dataset? | # Estrategy:
# 1. Find the average price of houses.
# Ps.: Use numpy's round() function to select only 2 number after point.
averageprice = np.round(data['price'].mean(), 2)
print('The average price of the houses is: U${}'.format(averageprice ))
# the function data.dtypes show us what types variables we have.
data.dtyp... | _____no_output_____ | MIT | Notebooks/Preview_Data_Visualization.ipynb | BrunoGeraldine/Python_Zero_To_DS |
9. What is the average price only houses whit 2 bathroom? | # Estrategy:
# 1. Find only the average price of houses whit 2 bathroms.
avg_bath = np.round(data.loc[data['bathrooms'] == 2, 'price'].mean(), 2)
print('The average price for houses whit 2 bathrooms is U${}'.format(avg_bath)) | The average price for houses whit 2 bathrooms is U$457889.72
| MIT | Notebooks/Preview_Data_Visualization.ipynb | BrunoGeraldine/Python_Zero_To_DS |
10. What is the minimum price between 3 bedroom homes? | # Estrategy:
# 1. Select only 3 bedroom house and arrange ascending by price
min_price_bed = data.loc[data['bedrooms'] == 3, 'price'].min(),
print('The minimum price for houses whit 3 bedrooms is U${}'.format(min_pricebed)) | The minimum price for houses whit 3 bedrooms is U$82000.0
| MIT | Notebooks/Preview_Data_Visualization.ipynb | BrunoGeraldine/Python_Zero_To_DS |
11. How many homes have more than 300 square meters in the living room? | # Estrategy:
# 1. Select only houses whit mor than 300ft² of living room and read the number of lines.
data['m2'] = data['sqft_living'] * 0.093
sqft_300 = len(data.loc[data['m2'] > 300, 'id'])
print('There are {} houses whit mor than 300ft² in the living room.'.format(sqft_300)) | There are 2258 houses whit mor than 300ft² in the living room.
| MIT | Notebooks/Preview_Data_Visualization.ipynb | BrunoGeraldine/Python_Zero_To_DS |
Se quiser fazer a converção de ft² para m² basta usar o seguinte raciocionio: (1 ft² = 0.093 m²) data['m²']=data['sqft_living'] * 0.093 - (aqui substituimos a variavel sqft_living pela m² ja convertendo o valor) len(data.loc[data['m²'] > 300, 'id']) 12. How many homes have more than 2 floors? | # Estrategy:
# 1. Select only houses whit mor than 300ft² of living room and read the number of lines.
floor_2 = data.loc[data['floors'] > 2, 'id'].size
print('There are {} houses whit mor than 2 floors.'.format(floor_2)) | There are 782 houses whit mor than 2 floors.
| MIT | Notebooks/Preview_Data_Visualization.ipynb | BrunoGeraldine/Python_Zero_To_DS |
13. How many houses have a waterfront view? | # Estrategy:
# 1. Select only houses whit waterfront view and read the number of lines.
waterfront_view = len(data.loc[data['waterfront'] != 0, 'id'])
print('There are {} houses whit waterfront view.'.format(waterfront_view)) | There are 163 houses whit waterfront view.
| MIT | Notebooks/Preview_Data_Visualization.ipynb | BrunoGeraldine/Python_Zero_To_DS |
14. Of the houses with a waterfront view, how many have 3 bedrooms? | # Estrategy:
# 1. Select only houses whit waterfront view and read how many have 3 bedrooms.
data.columns
waterfront_bed = data.loc[(data['waterfront'] != 0) & (data['bedrooms'] == 3), "id"].size
print('Of the houses whit waterfront, {} houses have 3 bedrooms.'.format(waterfront_bed)) | Of the houses whit waterfront, 64 houses have 3 bedrooms.
| MIT | Notebooks/Preview_Data_Visualization.ipynb | BrunoGeraldine/Python_Zero_To_DS |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.