forked from ardanlabs/gotraining
/
exercise2.go
82 lines (66 loc) · 1.77 KB
/
exercise2.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
// All material is licensed under the Apache License Version 2.0, January 2004
// http://www.apache.org/licenses/LICENSE-2.0
// go build
// ./exercise2
// Sample program to calculate a mean squared error.
package main
import (
"encoding/csv"
"fmt"
"io"
"log"
"math"
"os"
"strconv"
)
func main() {
// Open the continuous observations and predictions.
f, err := os.Open("../../data/continuous.csv")
if err != nil {
log.Fatal(err)
}
defer f.Close()
// Create a new CSV reader reading from the opened file.
reader := csv.NewReader(f)
// observed and predicted will hold the parsed observed and predicted values
// form the continous data file.
var observed []float64
var predicted []float64
// line will track row numbers for logging.
line := 1
// Read in the records looking for unexpected types in the columns.
for {
// Read in a row. Check if we are at the end of the file.
record, err := reader.Read()
if err == io.EOF {
break
}
// Skip the header.
if line == 1 {
line++
continue
}
// Read in the observed and predicted values.
observedVal, err := strconv.ParseFloat(record[0], 64)
if err != nil {
log.Printf("Parsing line %d failed, unexpected type\n", line)
continue
}
predictedVal, err := strconv.ParseFloat(record[1], 64)
if err != nil {
log.Printf("Parsing line %d failed, unexpected type\n", line)
continue
}
// Append the record to our slice, if it has the expected type.
observed = append(observed, observedVal)
predicted = append(predicted, predictedVal)
line++
}
// Calculate the mean squared error.
var mSE float64
for idx, oVal := range observed {
mSE += math.Pow(oVal-predicted[idx], 2) / float64(len(observed))
}
// Output the MSE value to standard out.
fmt.Printf("\nMSE = %0.2f\n\n", mSE)
}