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

Golang e data science oficial v1

  • 1.
    Golang e DataScience Minha Primeira API Rodrigo Pinheiro @_rodrigopa_
  • 2.
    Agenda ● Como ●Por quê Go? ● Collections ● Álgebra linear ● Estatística ● Probabilidade ● Gráficos 2
  • 3.
    Como surgiu aideia? 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 typeVector []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
  • 7.
  • 8.
    linalg func Add(x, ycollections.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 serefere 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 - InterfaceSort 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
  • 19.
  • 20.
  • 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? ● CriarAPI 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
  • 25.
  • 26.
  • 27.
  • 28.