Why is Python most preferred for machine learning?Artificial intelligence and machine learning are evidently what the future holds. Today, almost every company has a machine learning-based program to aid in its operations. We all want smarter recommendations, better personalization, and of course, i...
Solving a linear system of equations
public class App {
public static void main(String[] args) throws Exception {
// First, define the tolerance
double epsilon = 5E-6;
// Define maximum number of iterations
int maxIters = 500;
// Define the initial values/seed (x0^0)
double[] x0 = {0,0,0,0,0,0};
// Define the matrix of coefficients
double[][] M = {
{4, -1, 0, -2, 0, 0}, // coefficients for first equation
{-1, 4, -1, 0, -2, 0}, // second equation
{0, -1, 4, 0, 0, -2}, // third
{-1, 0, 0, 4, -1, 0}, // fourth
{0, -1, 0, -1, 4, -1}, // ...
{0, 0, -1, 0, -1, 4} // last equation
};
// Define vector b (equalities)
double[] b = {-1, 0, 1, -2, 1, 2};
// Call method
Jacobi(M, b, x0, epsilon, maxIters);
System.out.println("");
GaussSeidel(M, b, x0, epsilon, maxIters);
}
public static void Jacobi(double[][] M, double[] b, double[] x0, double epsilon, int maxIters)
{
System.out.println(" *** JACOBI METHOD *** ");
System.out.println("Solving the following system:");
System.out.println("Number of variables: " + b.length);
System.out.println("Toleance: " + epsilon);
System.out.println("Max. number of iterations: " + maxIters);
System.out.println("The system is:\n");
// Define initial error
double err = 1E+10; // a rally big number
// Define number of equations/variables
int N = b.length;
// Print equations so user can see them
for(int i = 0; i < N; i++)
{
for(int j = 0; j < N; j++)
{
System.out.print(M[i][j]+"*x" + (j+1) + " ");
}
System.out.print("= " + b[i] + "\n");
}
System.out.println("");
System.out.println("Starting iterations... ");
// Start iterations
double[] xold = x0; // varray to store old values (from previous iteration)
double[] xnew = xold.clone(); // array to store the result of the new iteration
int iterCounter = 0; // variable to count the iterations
double xi, erri; // helper variables to be used in the method
while(err > epsilon)
{
iterCounter++;
// Jacobi Method
for(int i = 0; i < N ;i++)
{
xi = b[i];
for(int j = 0; j < N; j++)
{
if(i != j)
xi -= M[i][j] * xold[j];
}
xi = xi/M[i][i];
xnew[i] = xi;
}
// Calculate errors and pick maximum
/*
For this method the error is calculated as the difference between the old solution and
the new one.
*/
double maxErr = -1;
for(int i = 0; i < N; i++)
{
erri = Math.abs((xnew[i]-xold[i]));
if(erri > maxErr)
maxErr = erri;
}
xold = xnew.clone(); // For the next iteration, the old_values are the new_values in this one
err = maxErr;
System.out.println("Iteration " + iterCounter + ", Err: " + err);
if(iterCounter == maxIters) // reached maximum number of iterations
{
System.out.println("Maximum number of iterations reached. Last error: " + err);
break;
}
}
// Display results only if the system converged
if(iterCounter < maxIters && err <= epsilon)
{
System.out.println("");
System.out.println("Convergence achieved in " + iterCounter + " iterations. Min error was: " + err);
System.out.println("The solution is:");
for(int i = 0; i < N; i++)
{
System.out.println("x[" + (i+1) + "] = " + xnew[i]);
}
}
}
public static void GaussSeidel(double[][] M, double[] b, double[] x0, double epsilon, int maxIters)
{
System.out.println(" *** GAUSS-SEIDEL METHOD *** ");
System.out.println("Solving the following system:");
System.out.println("Number of variables: " + b.length);
System.out.println("Toleance: " + epsilon);
System.out.println("Max. number of iterations: " + maxIters);
System.out.println("The system is:\n");
// Define initial error
double err = 1E+10; // a rally big number
// Define number of equations/variables
int N = b.length;
// Display equations
for(int i = 0; i < N; i++)
{
for(int j = 0; j < N; j++)
{
System.out.print(M[i][j]+"*x" + (j+1) + " ");
}
System.out.print("= " + b[i] + "\n");
}
System.out.println("");
System.out.println("Starting iterations... ");
// Start iterations
double[] x = x0; // vector of solutions is setted to the initial values
int iterCounter = 0; // variable to count interations
double xi, erri; // helper variables
double sigma; // helper variable for gauss-Seidel method
// Start iterations
while(err > epsilon)
{
iterCounter++;
// Gauss-Seidel method
for(int i = 0; i < N ;i++)
{
sigma = 0;
for(int j = 0; j < N; j++)
{
if(i != j)
sigma += M[i][j]*x[j];
}
xi = (b[i]-sigma)/M[i][i];
x[i] = xi;
}
// Calculate errors and pick maximum
/*
For this method the error is calculated as the value of the functions for the current solution.
The method converges when the value of the function f(xi)-bi = 0 is less than epsilon
*/
double maxErr = -1;
for(int i = 0; i < N; i++)
{
erri = 0;
for(int j = 0; j < N; j++)
{
erri += M[i][j]*x[j];
}
erri -= b[i];
erri = Math.abs(erri);
if(erri > maxErr)
maxErr = erri;
}
//xold = xnew.clone(); // the results of this iterations are the old for the next iteration
err = maxErr;
System.out.println("Iteration " + iterCounter + ", Err: " + err);
if(iterCounter == maxIters) // reached max number of iters
{
System.out.println("Maximum number of iterations reached. Last error: " + err);
break;
}
}
if(iterCounter < maxIters && err <= epsilon) // display results only if system converged
{
System.out.println("");
System.out.println("Convergence achieved in " + iterCounter + " iterations. Min error was: " + err);
System.out.println("The solution is:");
for(int i = 0; i < N; i++)
{
System.out.println("x[" + (i+1) + "] = " + x[i]);
}
}
}
}
Python Gradebook Analyser Tool
# Define a helper function to know if the entered input is a number (float) or no
def isNumber(str):
try:
float(str)
return True
except ValueError:
return False
# First, display the tool's greet message
print("Welcome to the gradebook analyzer!")
# Display some instructions
print("This tool will analyze the grades for students and will output the average grade for each student.")
print("You must specify the number of students and the grades for each one. Note that grades must be between 0 and 100.")
print("")
# To keep asking user for inputs when he/she enters an invalid value, we will use
# a while loop
# The following variable is used to know when to stop the main loop
stop = 0
talk_state = 0 # This variable is used to know in which state of the user-program conversation we are at
students = [] # This list is used to hold lists for each student
# Each sub list will contain the grades for each student
averages = []
while stop == 0:
if talk_state == 0: # Ask for number of students
# Now, ask user for number of students
Nstudents = input("How many students are in the class? ")
# Check if input is valid
if not isNumber(Nstudents) or int(Nstudents) < 1:
print("Invalid number of students. Quantity must be at least 1.")
else:
Nstudents = int(Nstudents)
talk_state = 1 # Move to next state
elif talk_state == 1:
# Now, enter a for loop from 0 to Nstudents - 1
for i in range(Nstudents):
"""
In order to keep asking to user for student_i's grades, we will
use another while-loop that will be exited when user enters "No"
"""
exit_loop = 0
student_id = i+1
student_scores = list()
while exit_loop == 0:
score = input("Enter student " + str(student_id) + "'s assignment score: ")
if not isNumber(score) or float(score) < 0.0 or float(score) > 100.0:
print("Invalid score. Score range is from 0 to 100.")
else:
student_scores.append(float(score))
invalid_option = 1
while invalid_option == 1:
option = input("Enter another score?: ")
if option.lower() in ['yes', 'no']: # A valid option entered
invalid_option = 0
if option.lower() == 'no':
exit_loop = 1
# Display average
if len(student_scores) > 0:
avg_grade = sum(student_scores)/len(student_scores)
else:
avg_grade = 0
averages.append(avg_grade)
# Append to main list
students.append(student_scores)
print("Student " + str(student_id) + "'s average was: {0:.1f}".format(avg_grade))
else:
print("Invalid option. Please enter Yes or No.")
talk_state = 2
elif talk_state == 2: # Display overall average
# Calculate class average
class_avg = sum(averages)/len(averages)
print("Class average: " + str(class_avg))
# Display how many As, Bs, Cs, etc
As = 0
Bs = 0
Cs = 0
Ds = 0
Fs = 0
for averg in averages:
if averg >= 90.0:
As += 1
elif averg >= 80 and averg <= 89.9:
Bs += 1
elif averg >= 70 and averg <= 79.9:
Cs += 1
elif averg >= 60 and averg <= 69.9:
Ds += 1
elif averg < 60:
Fs += 1
print("As: " + str(As))
print("Bs: " + str(Bs))
print("Cs: " + str(Cs))
print("Ds: " + str(Ds))
print("Fs: " + str(Fs))
talk_state = 3 # Move to next state
elif talk_state == 3:
invalid_option = 1
while invalid_option == 1:
option = input("Would you like to analyzer another class (yes/no)? ")
if option.lower() in ['yes', 'no']:
invalid_option = 0
if option.lower() == 'yes':
averages = []
students = []
talk_state = 0
else:
stop = 1
print("Thank you for using the gradebook analyzer!")