SlideShare uma empresa Scribd logo
Golang e Data Science
Minha Primeira API
Rodrigo Pinheiro
@_rodrigopa_
Agenda ● Como
● Por quê Go?
● Collections
● Álgebra linear
● Estatística
● Probabilidade
● Gráficos
2
Como surgiu a ideia?
3
Repositório - https://github.com/twgophers
● collections
○ Vector
○ Matrix
○ Zip
○ Counter
● linalg
● statistics
● probability
● nvd3-go-template
4
collections - Vetores
● São objetos que podem ser adicionados e
podem ser multiplicados por números.
5
collections - Vetores
collections.Vector
type Vector []float64
func (v Vector) Len() int
func (v Vector) Less(i, j int) bool
func (v Vector) Swap(i, j int)
func (v Vector) Max() float64
func (v Vector) Min() float64
Arrays ou Slices?
6
collections - Vetores
7
linalg
func Add(x, y collections.Vector) collections.Vector
func Subtract(x, y collections.Vector) collections.Vector
func Dot(x, y collections.Vector) float64
func SumOfSquares(sample collections.Vector) float64
func SquaredDistance(x, y collections.Vector) float64
func Distance(x, y collections.Vector) float64
8
linalg
func TestAdd(t *testing.T) {
cases := []struct {
x, y, want collections.Vector
}{
{collections.Vector{1.0, 1.0}, collections.Vector{0.0, 0.0}, collections.Vector{1.0,1.0}},
...
{collections.Vector{}, collections.Vector{2.0}, collections.Vector{}},}
for _, c := range cases {
got := Add(c.x, c.y)
if !reflect.DeepEqual(got, c.want)
t.Errorf("Add(%v, %v) want: %v; got: %v",c.x, c.y, c.want, got)
...
9
Estatística
● Estatística se refere a matemática
e técnicas utilizadas para
entender os dados.
10
Estatística
func Mean(sample collections.Vector) float64 {
check(sample)
return Sum(sample) / float64(sample.Len())
}
func check(sample collections.Vector) {
if sample.Empty() {
panic("Operation Not allowed with empty sample")
}
}
11
Estatística
import "testing"
func TestMeanPanicsWhenEmptySlice(t *testing.T) {
defer func() {
if recover() == nil {
t.Errorf("Expected mean panic when empty sample")
}
}()
Mean(collections.Vector{})
}
12
Estatística
func Median(sample collections.Vector) float64 {
check(sample)
sort.Float64s(sample)
half := sample.Len() / 2
if oddSize(sample) {
return sample[half]
}
return Mean(collections.Vector{sample[half-1], sample[half]})
}
13
Estatística - Interface Sort
package sort
type Interface interfacet {
Len() float64
Less(i, j int) bool
Swap(i, j int)
}
type Vector []float64
func (v Vector) Len() int {
return len(v)
}
func (v Vector) Less(i, j int) bool {
return v[i] < v[j]
}
func (v Vector) Swap(i, j int) {
v[i], v[j] = v[j], v[i]
} 14
Probabilidade
● Probabilidade é uma forma de
quantificar as incertezas
associadas com um evento escolhido
de um conjunto/universo de
eventos.
P(E)
15
Probabilidade
func Binomial(p float64, n int) (result int64, err error) {
if !(0.0 <= p && p <= 1.0) {
return -1, errors.New(fmt.Sprintf("Invalid probability p: %f", p))
}
if n <= 0 {
return -1, errors.New(fmt.Sprintf("Invalid parameter n: %d", n))
}
for i := 1; i <= n; i++ {
result += BernoulliTrial(p)
}
return result, nil
}
16
Probabilidade
func TestBinomial(t *testing.T) {
…
wantPositive, wantNegative := calculateMenWithError(c.p, c.n)
if got < wantNegative || got > wantPositive {
...
}
}
func calculateMenWithError(p float64, n int) (float64, float64) {
firstMean := mean(p, n)
meanMoreErrorTax := firstMean + 0.03*firstMean
meanLessErrorTax := firstMean - 0.03*firstMean
return meanMoreErrorTax, meanLessErrorTax
}
17
Gráficos Em Go
● Bibliotecas nativas em Go para
renderização de gráficos são
pobres.
Solução?
18
Gráficos Em JS
basic-line-chart01.html
lineChart.html
lineChart-csv.html
NVD3.js
19
Gráficos Em JS
20
Gráficos Em JS - Templates
● Um template é uma string ou um
arquivo contendo uma ou mais
partes entre chaves duplas,
{{...}}, chamadas ações.
21
Gráficos Em JS - Templates
function sinAndCos() {
var cos = [];
{{range .}}
cos.push({x: {{.X}}, y: {{.Y}}})
{{end}}
return ...
}
22
Gráficos Em JS - Templates
func init() {
t = template.Must(template.ParseFiles("templates/index.html",
"templates/js.tmpl"))
data = []Data_type{
Data_type{X: 1950, Y: 300.2},
...
Data_type{X: 2000, Y: 10289.7},
}
}
t.ExecuteTemplate(f, "index.html", data) 23
Próximos Pasos?
● Criar API para busca e download de
dados;
● Melhorar a visualização dos gráficos;
● Implementar algoritmos de machine
learning;
● Implementar especificação BLAS - Basic
Linear Algebra Subprograms
24
Repositório -
https://github.com/twgophers
25
Agradecimentos
26
27
28

Mais conteúdo relacionado

PPT
Funçoes, graficos by gledson
PDF
12 algoritmos e funcoes recursivas
PDF
14 algoritmos de classificacao de tabelas
PDF
Estudo de Funções com o Software Winplot
PPTX
As funcionalidades do winplot no ensino de funções
PDF
MATEMÁTICA- FUNÇÕES - AULA 1
PDF
Aula: busca e ordenação
PPTX
Matemática no winplot - sandra de souza
Funçoes, graficos by gledson
12 algoritmos e funcoes recursivas
14 algoritmos de classificacao de tabelas
Estudo de Funções com o Software Winplot
As funcionalidades do winplot no ensino de funções
MATEMÁTICA- FUNÇÕES - AULA 1
Aula: busca e ordenação
Matemática no winplot - sandra de souza

Mais procurados (20)

DOC
Utilizando o Winplot como recurso ao ensino da matemática
PPS
Gráficos de funções de 1° e 2° graus
PPT
Função afim
PPTX
Aula 09 08-2013
PDF
Aula1 funcaoquadrática
PDF
Função de 1º Grau.
PDF
Tarefa 7 execução do planejamento
PPT
Função polinomial do 1º grau
PDF
Projeto Final da disciplina Informatica e Internet
PPT
Função afim 2013-2014
PPT
Funções
PPTX
Função do 1º Grau
PPSX
Objeto de aprendizagem funcao afim
PDF
Função do 1º grau
PPT
Funcoes1 2
PPT
Matematica função.ppt [salvo automaticamente]
PPT
Função do 1º grau em ppt
DOCX
Programação Estruturada 2 - Aula 02 - Código Fonte
PDF
Resumo função afim pdf
PPT
Funcão Afim
Utilizando o Winplot como recurso ao ensino da matemática
Gráficos de funções de 1° e 2° graus
Função afim
Aula 09 08-2013
Aula1 funcaoquadrática
Função de 1º Grau.
Tarefa 7 execução do planejamento
Função polinomial do 1º grau
Projeto Final da disciplina Informatica e Internet
Função afim 2013-2014
Funções
Função do 1º Grau
Objeto de aprendizagem funcao afim
Função do 1º grau
Funcoes1 2
Matematica função.ppt [salvo automaticamente]
Função do 1º grau em ppt
Programação Estruturada 2 - Aula 02 - Código Fonte
Resumo função afim pdf
Funcão Afim
Anúncio

Semelhante a Golang e data science oficial v1 (20)

PDF
Computação científica com numpy e scipy
PDF
Aula actionscript basico
PDF
06 variavel-aleatoria
PDF
Manual winplot
PDF
Apostila de treinamento de Octave parte 1
PDF
Cartilha de Octave para Matematica Computacional.pdf
PDF
Sbc scipy
PDF
Sbc scipy
PDF
Booklet reais
PDF
programação de computadores - java e programação de computadores
DOCX
Aulas de estrutura de dados por Ayrton Yagami
PPT
Solução de equações não lineares weslley
PPSX
Função Quadrática
PPTX
Elementos de Matemática Básica - Funções
PDF
mod4-estruturas-dadosestaticas-ordenacao
PDF
Objetos Pythonicos - compacto
PDF
Python para quem sabe Python (aula 2)
ODP
Linguagem R
PPTX
As Novidades Do C# 4.0 - NetPonto
DOC
Repetições e vetores
Computação científica com numpy e scipy
Aula actionscript basico
06 variavel-aleatoria
Manual winplot
Apostila de treinamento de Octave parte 1
Cartilha de Octave para Matematica Computacional.pdf
Sbc scipy
Sbc scipy
Booklet reais
programação de computadores - java e programação de computadores
Aulas de estrutura de dados por Ayrton Yagami
Solução de equações não lineares weslley
Função Quadrática
Elementos de Matemática Básica - Funções
mod4-estruturas-dadosestaticas-ordenacao
Objetos Pythonicos - compacto
Python para quem sabe Python (aula 2)
Linguagem R
As Novidades Do C# 4.0 - NetPonto
Repetições e vetores
Anúncio

Último (7)

DOC
CODIGO PARA AUTOMATIZAR A JOGABILIDADE SUPER MARIO
PDF
Evolução em código: algoritmos genéticos com PHP
DOC
COMO AUTOMATIZR JOGOS SUPER NINTENDO ATRAVES DA PROGRAMAÇÃO
PPTX
Curso de Windows 11 resumido na prática.pptx
PDF
Dos requisitos ao código: como criar código rastreável em PHP
PPTX
Mapeamento de Objeto para Tabela Relacional
PDF
apresentacao introducao computacao ead.pdf
CODIGO PARA AUTOMATIZAR A JOGABILIDADE SUPER MARIO
Evolução em código: algoritmos genéticos com PHP
COMO AUTOMATIZR JOGOS SUPER NINTENDO ATRAVES DA PROGRAMAÇÃO
Curso de Windows 11 resumido na prática.pptx
Dos requisitos ao código: como criar código rastreável em PHP
Mapeamento de Objeto para Tabela Relacional
apresentacao introducao computacao ead.pdf

Golang e data science oficial v1

  • 1. Golang e Data Science Minha Primeira API Rodrigo Pinheiro @_rodrigopa_
  • 2. Agenda ● Como ● Por quê Go? ● Collections ● Álgebra linear ● Estatística ● Probabilidade ● Gráficos 2
  • 3. Como surgiu a ideia? 3
  • 4. Repositório - https://github.com/twgophers ● collections ○ Vector ○ Matrix ○ Zip ○ Counter ● linalg ● statistics ● probability ● nvd3-go-template 4
  • 5. collections - Vetores ● São objetos que podem ser adicionados e podem ser multiplicados por números. 5
  • 6. collections - Vetores collections.Vector type Vector []float64 func (v Vector) Len() int func (v Vector) Less(i, j int) bool func (v Vector) Swap(i, j int) func (v Vector) Max() float64 func (v Vector) Min() float64 Arrays ou Slices? 6
  • 8. linalg func Add(x, y collections.Vector) collections.Vector func Subtract(x, y collections.Vector) collections.Vector func Dot(x, y collections.Vector) float64 func SumOfSquares(sample collections.Vector) float64 func SquaredDistance(x, y collections.Vector) float64 func Distance(x, y collections.Vector) float64 8
  • 9. linalg func TestAdd(t *testing.T) { cases := []struct { x, y, want collections.Vector }{ {collections.Vector{1.0, 1.0}, collections.Vector{0.0, 0.0}, collections.Vector{1.0,1.0}}, ... {collections.Vector{}, collections.Vector{2.0}, collections.Vector{}},} for _, c := range cases { got := Add(c.x, c.y) if !reflect.DeepEqual(got, c.want) t.Errorf("Add(%v, %v) want: %v; got: %v",c.x, c.y, c.want, got) ... 9
  • 10. Estatística ● Estatística se refere a matemática e técnicas utilizadas para entender os dados. 10
  • 11. Estatística func Mean(sample collections.Vector) float64 { check(sample) return Sum(sample) / float64(sample.Len()) } func check(sample collections.Vector) { if sample.Empty() { panic("Operation Not allowed with empty sample") } } 11
  • 12. Estatística import "testing" func TestMeanPanicsWhenEmptySlice(t *testing.T) { defer func() { if recover() == nil { t.Errorf("Expected mean panic when empty sample") } }() Mean(collections.Vector{}) } 12
  • 13. Estatística func Median(sample collections.Vector) float64 { check(sample) sort.Float64s(sample) half := sample.Len() / 2 if oddSize(sample) { return sample[half] } return Mean(collections.Vector{sample[half-1], sample[half]}) } 13
  • 14. Estatística - Interface Sort package sort type Interface interfacet { Len() float64 Less(i, j int) bool Swap(i, j int) } type Vector []float64 func (v Vector) Len() int { return len(v) } func (v Vector) Less(i, j int) bool { return v[i] < v[j] } func (v Vector) Swap(i, j int) { v[i], v[j] = v[j], v[i] } 14
  • 15. Probabilidade ● Probabilidade é uma forma de quantificar as incertezas associadas com um evento escolhido de um conjunto/universo de eventos. P(E) 15
  • 16. Probabilidade func Binomial(p float64, n int) (result int64, err error) { if !(0.0 <= p && p <= 1.0) { return -1, errors.New(fmt.Sprintf("Invalid probability p: %f", p)) } if n <= 0 { return -1, errors.New(fmt.Sprintf("Invalid parameter n: %d", n)) } for i := 1; i <= n; i++ { result += BernoulliTrial(p) } return result, nil } 16
  • 17. Probabilidade func TestBinomial(t *testing.T) { … wantPositive, wantNegative := calculateMenWithError(c.p, c.n) if got < wantNegative || got > wantPositive { ... } } func calculateMenWithError(p float64, n int) (float64, float64) { firstMean := mean(p, n) meanMoreErrorTax := firstMean + 0.03*firstMean meanLessErrorTax := firstMean - 0.03*firstMean return meanMoreErrorTax, meanLessErrorTax } 17
  • 18. Gráficos Em Go ● Bibliotecas nativas em Go para renderização de gráficos são pobres. Solução? 18
  • 21. Gráficos Em JS - Templates ● Um template é uma string ou um arquivo contendo uma ou mais partes entre chaves duplas, {{...}}, chamadas ações. 21
  • 22. Gráficos Em JS - Templates function sinAndCos() { var cos = []; {{range .}} cos.push({x: {{.X}}, y: {{.Y}}}) {{end}} return ... } 22
  • 23. Gráficos Em JS - Templates func init() { t = template.Must(template.ParseFiles("templates/index.html", "templates/js.tmpl")) data = []Data_type{ Data_type{X: 1950, Y: 300.2}, ... Data_type{X: 2000, Y: 10289.7}, } } t.ExecuteTemplate(f, "index.html", data) 23
  • 24. Próximos Pasos? ● Criar API para busca e download de dados; ● Melhorar a visualização dos gráficos; ● Implementar algoritmos de machine learning; ● Implementar especificação BLAS - Basic Linear Algebra Subprograms 24
  • 27. 27
  • 28. 28