Feature Writeup

For this project, I have created a database called hotlines that stores the data for the numbers and names of hotlines. I have also added columns to the user database.

From VSCode using SQLite3 Editor, show your unique collection/table in database, display rows and columns in the table of the SQLite database.

Therapy SQLite Database:

image

Database Code:

class Hotline(db.Model):
    __tablename__ = 'hotlines'

    id = db.Column(db.Integer, primary_key=True)
    _name = db.Column(db.String(255), unique=False, nullable=False)
    _number = db.Column(db.String(255), unique=False, nullable=False)

    def __init__(self, name, number):
        self._name = name
        self._number = number

    @property
    def name(self):
        return self._name
    
    @name.setter
    def name(self, name):
        self._name = name
    
    @property
    def number(self):
        return self._number
    
    @number.setter
    def location(self, number):
        self._number = number
    
    def __str__(self):
        return json.dumps(self.read())

    def create(self):
        try:
            db.session.add(self)
            db.session.commit()
            return self
        except IntegrityError:
            db.session.remove()
            return None

    def read(self):
        return {
            "id": self.id,
            "name": self.name,
            "number": self.number,
        }

From VSCode model, show your unique code that was created to initialize table and create test data.

Initialization Code (Testing Data):

def initHotlines():
    with app.app_context():
        db.create_all()
        hotlines = [
            Hotline(name="National Domestic Violence Hotline", number="1-800-799-SAFE"),
            Hotline(name="Elder Abuse Hotline", number="1-800-252-8966"),
            Hotline(name="Eating Disorders Awareness and Prevention", number="1-800-931-2237"),
            Hotline(name="Family Violence Prevention Center", number="1-800-313-1310"),
            Hotline(name="Compulsive Gambling Hotline", number="1-410-332-0402"),
            Hotline(name="Homeless", number="1-800-231-6946"),
            Hotline(name="American Family Housing", number="1-888-600-4357"),
            Hotline(name="GriefShare", number="1-800-395-5755"),
            Hotline(name="United STates Missing Children Hotline", number="1-800-235-3525"),
        ]
        for hotline in hotlines:
            try:
                hotline.create()
            except IntegrityError:
                db.session.rollback()
                print(f"Record exists")

Lists and Dictionaries

Blog Python API code and use of List and Dictionaries.

In VSCode using Debugger, show a list as extracted from database as Python objects.

Read List in Debugger:

  • I currently have an issue where my code is able to fetch data from the backend however, due to an error (it maybe be from the unknown tuple error that I still have) it will not let me see the lists that are shown from the Debugger.

Image

Image

API code that fetches from the backend

image

GET, POST Code:

class _Read(Resource):
        def get(self):
            hotlines = Hotline.query.all()
            json_ready = [hotline.read() for hotline in hotlines]
            return jsonify(json_ready)
    class _Create(Resource):
        def post(self):
            body = request.get_json()
            # Fetch data from the form
            name = body.get('name')
            if name is None or len(name) < 2:
                return {'message': f'Name is missing, or is less than 2 characters'}, 400
            # validate location
            number = body.get('number')
            if number is None or len(number) < 2:
                return {'message': f'Number is missing, or is less than 2 characters'}, 400
            # success returns json of user
            if number:
                    #return jsonify(user.read())
                    return number.read()
                # failure returns error
            return {'message': f'Record already exists'}, 400   

    # building RESTapi endpoint, method distinguishes action
    api.add_resource(_Read, '/')
    api.add_resource(_Create, '/create')

Algorithmic Conditions to validate Post:

name = body.get('name')
if name is None or len(name) < 2:
    return {'message': f'Name is missing, or is less than 2 characters'}, 400
# validate number
number = body.get('number')
if number is None or len(number) < 2:
    return {'message': f'Number is missing, or is less than 2 characters'}, 400
# success returns json of user
if number:
#return jsonify(user.read())
    return number.read()

In Postman, show URL request and Body requirements for GET, POST methods.

GET: image

POST: image

Show the JSON response data for 200 success conditions: image

Show the JSON response for error for 400 when missing body on a POST request in Postman: image

In Postman, show the JSON response for error for 404 when providing an unknown user ID to a UPDATE request:

The code retrieves the user’s cookie and decodes it to update the user’s information. This ensures that only the logged-in user’s data can be updated, preventing the use of an unknown user ID. This security measure restricts access to only the user’s own data for updates.

Show response of JSON objects from fetch:

image

Image

Describe fetch and method that obtained the Array of JSON objects in JavaScript code:

The js code uses the fetch function to make an HTTP GET request to the specified API endpoint (“http://127.0.0.1:8086/api/hotline/”) and retrieve an array of JSON objects. It specifies the request method as ‘GET’ and the request headers (‘Content-Type’: ‘application/json;charset=utf-8’) in the options object. Once the response is received and parsed into a JavaScript array, the code processes the data to populate an HTML table.

Show code that performs iteration and formatting of data into HTML in JavaScript code:

image

image image

image

In JavaScript code, show and describe code that handles failure. Describe how the code shows failure to the user in the Chrome Browser screen:

else if (response.status === 400) {
    alert("Seach unsuccessful");
}

If the response given was 400 instead, this code will run giving an alert to the user that there was a problem

image

In JavaScript code, show and describe code that handles success. Describe how code shows success to the user in the Chrome Browser screen:

if (search.status === 200) {
    alert("Search successful!");
    window.location.reload();

If the resopnse from the backend is 200, meaning that it was successful, the code will continue and run an alert message that displays to the user that the search was successful, then the page and the table will reload and show the searched hotline(s).

ML Feature Writeup

Show algorithms and preparation of data for analysis. This includes cleaning, encoding, and one-hot encoding.

def preprocess_data(self):
    if self.data is None:
        raise ValueError("Data not loaded. Call load_data() first.")

    # Dropping unnecessary columns
    self.data.drop(['alive', 'who', 'adult_male', 'class', 'embark_town', 'deck'], axis=1, inplace=True)
    
    # Converting 'sex' column to numerical format
    self.data['sex'] = self.data['sex'].apply(lambda x: 1 if x == 'male' else 0)
    
    # Converting 'alone' column to numerical format
    self.data['alone'] = self.data['alone'].apply(lambda x: 1 if x == True else 0)
    
    # One-hot encoding 'embarked' column
    self.encoder = OneHotEncoder(handle_unknown='ignore')
    self.encoder.fit(self.data[['embarked']])
    onehot = self.encoder.transform(self.data[['embarked']]).toarray()
    cols = ['embarked_' + val for val in self.encoder.categories_[0]]
    self.data[cols] = pd.DataFrame(onehot)
    
    # Dropping the original 'embarked' column
    self.data.drop(['embarked'], axis=1, inplace=True)
    
    # Dropping rows with missing values
    self.data.dropna(inplace=True)

  • Unnecessary columns such as ‘alive’, ‘who’, etc., are dropped.
  • The ‘sex’ column is converted to a numerical format, where ‘male’ is represented as 1 and ‘female’ as 0.
  • The ‘alone’ column, which is boolean, is converted to a numerical format where True is represented as 1 and False as 0.
  • The ‘embarked’ column is one-hot encoded, creating new columns for each category (‘S’, ‘C’, ‘Q’) with binary values indicating presence or absence.
  • Finally, rows with missing values are dropped to ensure clean data for analysis.

Show algorithms and preparation for predictions.

def predict_survival_probability(self, new_passenger):
    if self.model_logreg is None:
        raise ValueError("Models not trained. Call train_models() first.")

    # Preprocess the new passenger's data
    new_passenger['sex'] = new_passenger['sex'].apply(lambda x: 1 if x == 'male' else 0)
    new_passenger['alone'] = new_passenger['alone'].apply(lambda x: 1 if x == True else 0)
    onehot = self.encoder.transform(new_passenger[['embarked']]).toarray()
    cols = ['embarked_' + val for val in self.encoder.categories_[0]]
    new_passenger[cols] = pd.DataFrame(onehot, index=new_passenger.index)
    new_passenger.drop(['embarked'], axis=1, inplace=True)
    new_passenger.drop(['name'], axis=1, inplace=True)

    # Predict survival probability using the trained logistic regression model
    dead_proba, alive_proba = np.squeeze(self.model_logreg.predict_proba(new_passenger))
    print('Death probability: {:.2%}'.format(dead_proba)) 
    print('Survival probability: {:.2%}'.format(alive_proba)) 
    return dead_proba, alive_proba
  • The method checks if the logistic regression model has been trained. If not, it raises an error.
  • The passenger’s name is dropped as it’s not used for prediction.
  • The survival probability for the new passenger is predicted using the trained logistic regression model (model_logreg) and printed out.

Discuss concepts and understanding of Linear Regression algorithms:

  • Linear regression is a supervised machine learning method that is used by the Train Using AutoML tool and finds a linear equation that best describes the correlation of the explanatory variables with the dependent variable. This is achieved by fitting a line to the data using least squares.
  • Linear regression is a data analysis technique that predicts the value of unknown data by using another related and known data value. It mathematically models the unknown or dependent variable and the known or independent variable as a linear equation.

Discuss concepts and understanding of Decision Tree analysis algorithms:

  • Decision trees use multiple algorithms to decide to split a node into two or more sub-nodes. The creation of sub-nodes increases the homogeneity of resultant sub-nodes. In other words, we can say that the purity of the node increases with respect to the target variable.
  • A decision tree algorithm is a machine learning algorithm that uses a decision tree to make predictions. It follows a tree-like model of decisions and their possible consequences. The algorithm works by recursively splitting the data into subsets based on the most significant feature at each node of the tree.