7.Demonstrate how to build a logistic regression model using Go.
Building a logistic regression model involves fitting a logistic function to a set of data points to
predict the probability of a binary outcome. Here's an example Go program that demonstrates
how to build a logistic regression model using the gradient descent algorithm
package main
import (
"fmt"
"math"
)
func main() {
// Example training dataset
x := [][]float64{{1, 1}, {1, 2}, {2, 1}, {2, 2}, {3, 3}, {4, 4}, {4, 5}, {5, 4}}
y := []int{0, 0, 0, 0, 1, 1, 1, 1}
// Train the logistic regression model
theta0, theta1, theta2 := trainLogisticRegression(x, y, 0.01, 1000)
// Predict using the trained model
predicted := predictLogisticRegression(x, theta0, theta1, theta2)
// Display the trained model and predictions
fmt.Printf("Trained Model: y = 1 / (1 + exp(%.2f + %.2fx1 + %.2fx2))\n", theta0, theta1,
theta2)
fmt.Println("Predicted Probabilities:", predicted)
}
// Function to train a logistic regression model using gradient descent
func trainLogisticRegression(x [][]float64, y []int, learningRate float64, numIterations int)
(float64, float64, float64) {
m := len(x)
n := len(x[0])
theta0 := 0.0
theta1 := 0.0
theta2 := 0.0
for iter := 0; iter < numIterations; iter++ {
gradient0 := 0.0
gradient1 := 0.0
gradient2 := 0.0
for i := 0; i < m; i++ {
predicted := sigmoid(theta0 + theta1*x[i][0] + theta2*x[i][1])
gradient0 += (predicted - float64(y[i]))
gradient1 += (predicted - float64(y[i])) * x[i][0]
gradient2 += (predicted - float64(y[i])) * x[i][1]
}
gradient0 /= float64(m)
gradient1 /= float64(m)
gradient2 /= float64(m)
theta0 -= learningRate * gradient0
theta1 -= learningRate * gradient1
theta2 -= learningRate * gradient2
}
return theta0, theta1, theta2
}
// Function to predict probabilities using a trained logistic regression model
func predictLogisticRegression(x [][]float64, theta0, theta1, theta2 float64) []float64
{
m := len(x)
predicted := make([]float64, m)
for i := 0; i < m; i++
{
predicted[i] = sigmoid(theta0 + theta1*x[i][0] + theta2*x[i][1])
}
return predicted
}
// Function to compute the sigmoid function
func sigmoid(z float64) float64 {
return 1 / (1 + math.Exp(-z))