VishnuAravind12 / vishnu

CSA Blog
MIT License
1 stars 1 forks source link

The Association between CB and PBL #8

Open VishnuAravind12 opened 8 months ago

VishnuAravind12 commented 8 months ago

Problem 1: Arrays/Arraylists

This problem involved tackling a series of challenges related to arrays, particularly focusing on summing elements and analyzing the uniqueness of sums in a two-dimensional array context. The principles that I used to solve this problem all hinged on working with arrays, which are ubiquitous in our team's project. Here is an example:

for (int iteration = 0; iteration < maxIterations; iteration++) {
    List<Double> predictions = predict(x_train);
    // Update coefficients and intercept
    double interceptGradient = 0.0;
    List<Double> slopeGradients = new ArrayList<>(coefficients.size());

    for (int i = 0; i < slopeGradients.size(); i++) {
        slopeGradients.set(i, 0.0);
    }

    for (int i = 0; i < x_train.size(); i++) {
        double predicted = predictions.get(i);
        interceptGradient += predicted - y_train.get(i);
        for (int j = 0; j < coefficients.size() - 1; j++) {
            slopeGradients.set(j, slopeGradients.get(j) + (predicted - y_train.get(i)) * x_train.get(i));
        }
    }

    intercept -= learningRate * interceptGradient / x_train.size();
    for (int i = 0; i < coefficients.size() - 1; i++) {
        coefficients.set(i, coefficients.get(i) - learningRate * slopeGradients.get(i) / x_train.size());
    }
}

From our Group Final Project, specifically the Logistic Regression Model, the above is an excerpt of code that really showcases the capabilities of ArrayLists in Java. The model is used, in tandem with a linear regressor, to project a player's stats. The key part of the code that highlights the use of ArrayLists is in the train method, where we update the coefficients and intercept for the regression model. This part is crucial because it iteratively adjusts the model parameters based on the training data to improve the model's predictions.

In this excerpt, I used ArrayLists to manage and dynamically update the coefficients and slope gradients. Unlike fixed-size arrays, ArrayLists in Java can resize dynamically, which is particularly useful in machine learning contexts like ours where the number of features (and thus coefficients) can vary. Through the use of the get and set methods, we efficiently update the slope gradients and coefficients during each iteration of the training process.

Problem 2: Classes

This problem tasked me with developing the HiddenWord class, the key component of a word-guessing game where the player attempts to guess a hidden word. This assignment required me to encapsulate both data and logic within a cohesive class structure. As expected, proper class design was used widely throughout our team project, as it vital for a functioning application. Here is an example:

package com.nighthawk.spring_portfolio.nbapredictor.monte_carlo;

public class PlayerStats {
    private int points;
    private int rebounds;
    private int assists;

    // Getters and setters
    public int getPoints() {
        return points;
    }

    public void setPoints(int points) {
        this.points = points;
    }

    public int getRebounds() {
        return rebounds;
    }

    public void setRebounds(int rebounds) {
        this.rebounds = rebounds;
    }

    public int getAssists() {
        return assists;
    }

    public void setAssists(int assists) {
        this.assists = assists;
    }
}

The PlayerStats class is a great example of class desgin from our project, and a perfect example of a Plain Old Java Object (POJO). The context of PlayerStats is to hold individual basketball players' statistical data, such as points, rebounds, and assists. This class forms the base layer in our application's hierarchy, as it's the most granular level of data representation.

The fields for the statistical data are kept private, ensuring that the internal representation of a player's stats is hidden from other parts of the program, safeguarding the integrity of the data.For each private field in the PlayerStats class, there getter and setter methods. The getters allow other parts of the program to read the player's statistics, while the setters enable the modification of these stats under specific conditions defined in the program.

The PlayerStats class plays a critical role in the broader structure of our project. It serves as the building block for more complex classes like Player and GameTeam. In the Player class, PlayerStats is used to represent the individual stats of a player. The GameTeam class leverages uses Player class to form a complete team.

Problem 3: 2D Arrays

The problem aimed to have me develop an efficient way to represent and manipulate a sparse array, which is a two-dimensional array with most of its elements being zeros. The primary objectives were to retrieve specific element values from this sparse structure and to modify the array by removing columns, all while maintaining the integrity of the array's structure.

2D Arrays, in their traditional form, have not been used in our project yet. owever, we expect this to soon be remedied with the introduction of the neural network for moneyline NBA game predictions. The incorporation of neural networks will naturally lead us into the realm of 2D arrays, as they are essential in representing the complex, multi-dimensional data structures typical in machine learning models. 2D arrays, in this context, will be pivotal for handling weights, biases, and activations within the network layers. With one-hot-encoding, 2D arrays tend to get a little 0-heavy, so spare arrays could be a viable option for improving model performance.

However, there are somewhat untraditional 2D Arrays scattered through our backend. One of them would be the GameTeams class:

package com.nighthawk.spring_portfolio.nbapredictor.monte_carlo;

import java.util.List;

public class GameTeams {
    private List<Player> teamA;
    private List<Player> teamB;

    // Constructors
    public GameTeams() {}

    public GameTeams(List<Player> teamA, List<Player> teamB) {
        this.teamA = teamA;
        this.teamB = teamB;
    }

    // Getters and setters
    public List<Player> getTeamA() {
        return teamA;
    }

    public void setTeamA(List<Player> teamA) {
        this.teamA = teamA;
    }

    public List<Player> getTeamB() {
        return teamB;
    }

    public void setTeamB(List<Player> teamB) {
        this.teamB = teamB;
    }
}

The GameTeams class can appear as a 2D Array due to its two teams, which can be viewed as two rows. Within these "rows" are "columns" of players.

Problem 4: Methods and Control Structures

In this problem, my task centered around implementing a system capable of representing and managing diverse groups of numbers, each defined in distinct ways. This challenge required me to design a flexible and dynamic structure with the use of various methods and control structures. This involved creating methods that could accurately identify whether a number belonged to a specific group and applying control structures such as loops and conditional statements to navigate and manipulate these groups.

Here is an examples of methods and control structures being used in our team project:

double sum = 0;
int totalPlayers = 0;

List<Player> allPlayers = new ArrayList<>(teamsData.getTeamA());
allPlayers.addAll(teamsData.getTeamB());

for (Player player : allPlayers) {
    sum += calculateFantasyPoints(player);
    totalPlayers++;
}

double mean = sum / totalPlayers;
double squaredDifferenceSum = 0;

for (Player player : allPlayers) {
    double difference = calculateFantasyPoints(player) - mean;
    squaredDifferenceSum += difference * difference;
}

double variance = squaredDifferenceSum / totalPlayers;
return Math.sqrt(variance);

The above excerpt is from the MonteCarloSimulator class in our NBA Predictor project, which is designed for simulating and predicting fantasy points in NBA games. The calculateStandardDeviation is crucial for accurately capturing the variability in player performances, thereby enabling us to generate more realistic and reliable fantasy point projections.

In developing this method, we employed enhanced for loops to iterate through lists of players, aggregating their fantasy points. This step was essential to calculate the mean fantasy points, laying the groundwork for further calculations. We then used another loop to compute the sum of squared differences from the mean, a critical step in determining the variance of the players' performances. Finally, the standard deviation was derived by taking the square root of this variance.

Reflection

Reflecting on the FRQs and their crossover with our group's final project has been an enlightening experience.

I now am aware of my shortcomings in time management. Piecing bits of code into a cohesive and running program within the 15-minute time limit proved to be difficult. Moreover, I've identified specific technical areas where I need to deepen my understanding. Notably, the concept of interfaces in Java presented a challenge. Grasping the use of interfaces, which are crucial for defining contracts in OOP and ensuring a modular codebase, is something I need to focus on.

I also encountered some cool aspects of programming that were very informative. For instance, learning about the use of StringBuilder was a revelation in terms of efficient string manipulation and memory management. The discovery and application of iterators to safely modify collections while iterating through them was another highlight, as it resolved issues I faced with traditional for loops.

Pointing out the association between the CB problems and the PBL code has helped me realize the immense potential of using our team project as a practical platform for AP exam preparation. Approaching our project with a mindset aligned more closely with the AP Computer Science A exam requirements could aid in improving my coding skills.

As we continue with our project in Trimester 3, I plan to deliberately incorporate features that draw upon elements from all four types of AP CSA exam questions - Methods and Control Structures, Classes, Array/ArrayLists, and 2D Arrays. Especially 2D Arrays, as their traditional forms have not seen use in our project yet.

jm1021 commented 8 months ago

FRQ1 association is great. Have you ever done the Titanic, at the bottom of my article you can put in data on whether you would live or die.

Java does have strongly typed problem that for logistic regression you would need all your data to be double. Your work is exciting to see and I like the fantasy examples.

jm1021 commented 8 months ago

FRQ2 and using POJO is powerful and foundational to Java or any OOP

jm1021 commented 8 months ago

FRQ3 using 1D Array of Class/Objects is the way to have a 2D array in Java for mixed data types. However, this is not considered a 2D array from many coding discussions. Depending on data type(s) in Class/Objects you can even have more dimensions. However, as you state in learning models we need to transfer everything into numbers for ML. It is curious to me, without something like Pandas that handles int and float in its arrays, if we just default to float for arrays when doing ML.

jm1021 commented 8 months ago

FRQ4 I think of much differently. This is an example of implements and extends and implements is the power of Java. When CB talks about Methods and Control structures it is similar to your example. However, CB tends to use a lot of Static in these type of associations, this is very aggravating to me. The language is being taught by people that do not have an purist Java bones.

jm1021 commented 8 months ago

The reflection you made is powerful and shows that PBL and learning a language can be tightly coupled. Even, as you suggest, to look at things like ML and 2D arrays.

4/3.6 on this portion of final.

LiavB2 commented 8 months ago

Very Nice FRQ VishnuAravind12!

Tirth-Thakkar commented 8 months ago

FRQs

FRQ 1:

FRQ 2:

FRQ 3:

FRQ 4:

Total: 4.0/3.6

Connection:

FRQ 1

FRQ 2

FRQ 3

FRQ 4

Total: 3.90/3.6

jm1021 commented 8 months ago

FRQs

FRQ 1:

  • Part A: Code properly creates the arraySum method and indicates proper understanding of for loops
  • Part B: Represents a good understanding of using the prior written methods in the prior question and a good understanding of for loops and indexing arrays
  • Part C: Good usage of nested for loops that matched my implementation with being able to compare with the next elements in the list and properly return a value for whether or not the array was diverse or not.
  • Reflections: The reflections were insightful and gave good insight about the problem and how it was done overall an excellent understanding of the question was demonstrated here.
  • Score: 1/0.9

FRQ 2:

  • General: Interesting use of Scanner for testing for passing in user input interesting method of learning more Java concepts than those that are covered in the course
  • General: Interesting use of the String Builder instead of a more conventional solution that was to use a String and explanation
  • Good implementation of the constructor for the HiddenWord class as with the proper instance variables and arguments in the constructor
  • Proper usage of conditional statements to be able to concatenate to the String builder to be able to create the properly returned string good understanding was demonstrated
  • Reflection: Good reflection on the understanding of memory to more efficiently create a program and this insight into the immutable nature of strings. Also an interesting idea on adding the sense of intractability to the program.
  • Score: 1.0/0.9

FRQ 3:

  • General: Good addition of the addEntry method to match the constructor usage demonstrated in the example code that was an insightful addition to the program
  • Part A: Good usage of the for loop to be able to find the matching element in the entries Array list and the conditional statement was also insightfully implemented
  • Part B: Good addition of the toString method to SparseArrayEntry to allow for easy printing and testing however in the context of the problem it would be best to not change the template code
  • Part B: Good use of the iterator pattern to be able to remove and find the values from within the entries ArrayList that was able to be adjusted and changed meeting all aspects of the problem
  • Reflection: The reflection was insightful and mentioned the difficulties they had when they went through the problem.
  • Score: 1.0/0.9

FRQ 4:

  • Part A: A good understanding of interfaces and the ability to declare the interface was properly demonstrated along with the needed types as specified by the problem.
  • Part B: Good understanding of how to implement a constructor and the instance variables that need to be declared for the class, the constructor was properly declared and the conditional statement was properly used.
  • Part C: Good declaration of the multiple groups class, and a good creation of the constructor to match the usage patterns as specified by the problem.
  • Part C: Nice creation of the addGroup method to add more versatility to the program without changing the constructor.
  • Part C: Good usage of a for each loop then operating on the elements within the array list with their contains methods to return the proper value with a good condition.
  • Reflections: The reflection was insightful giving insight on their struggles with the problem and the needed understanding with a good explanation of the reasoning about their implementation.
  • Score: 1/0.90

Total: 4.0/3.6

Connection:

FRQ 1

  • Code showcases a good understanding of ArrayList through the usage of a regression model that demonstrates a far greater extension of the usage of ArrayList while also utilizing the benefits of ArrayLists and the ability for them to dynamically resize
  • Along with machine learning concepts being an interesting addition to traditional FRQ concepts and the usage in a video game or player context
  • Also demonstrates a good understanding of ArrayList methods, and the ability to best utilize them depending on the contexts at hand also shows a proper understanding of the concepts needed to successfully apply Java
  • Score: 1/0.90

FRQ 2

  • Good representation of a POJO and deceleration of a class for a clear structure to hold player data and statistics that can be set and added using the needed setters and getter methods while also serving as a good point to be able to build off for the project functionality
  • There is a good understanding of the private and public attributes based on what can and cannot be accessed to maximize project functionality
  • Good understanding of the usage of the PlayerStats class in relation to the rest of the program to be able to build off of these features in a good demonstration of object-oriented programming.
  • However, there could have been an instance of a custom constructor to initialize instance variables to demonstrate an ability to declare this outside of a non-FRQ context
  • Score 1/0.90

FRQ 3

  • Interesting insight into the possible use of Sparse Arrays similar to those in the problem to improve performance by removing unnecessary entries
  • While not using 2D arrays the usage of a 2d array list through the balance of the multiple teams indicates an understanding in this general pattern represented
  • While also explaining how they may be implemented in the future for model weights in training.
  • However, there could have been the inclusion of 1D arrays to showcase an understanding of the nuances of Arrays compared to ArrayLists through the usage of a 1D array as in this context given they have different elements and different structures, the reflection does add to this however a demonstration as well would have been useful.
  • Score: 0.95/0.90

FRQ 4

  • There is a good understanding of implementing control structures that are different than those of the problem such as the use of the class method that was used to capture variability through an understanding of enhanced for loops to indicate a good understanding of this system
  • I would have otherwise also liked to have seen a use of interfaces and other more object-orientated control structures between the classes which would be very useful in an ML application or possibly the implementation of the collections interface when creating JSON these would have indicated the best understanding which doesn't appear to be seen here
  • Score: 0.95/0.90

Total: 3.90/3.6

Outstanding crossover review