AI Clock is Ticking: Wake Up Call for Education Institutions 

After the launch of ChatGPT, every industry in the market is figuring out how to make the best out of this technology. Alongside this excitement, it has also caused concern among several startups and employees, as they fear that AI is looming over them, potentially taking away their jobs.

However, among all the AI buzz, there is one sector which appears to be carefree and is taking AI lightly without realising its consequences. It is none other than educational institutes. This approach might hurt them in the future if they don’t take necessary steps.

Whenever a new technology comes in, there are always early adopters and late majority, according to the Theory of Diffusion. In the case of foundational models and generative AI, no one had expected that it would be universities and schools which would be shying away from it while they should have been the first ones to integrate in their teaching methods.

As soon as they came to know about ChatGPT, the knee jerk reaction of the majority of the universities and colleges around the world was to ban it.

Why, just because they feared that students might use it to copy their assignments. This solution is surely not going to work in the long run. Students are smart enough to outwit their professors if they want to cheat in their assignments.

For instance, when Google Search came in, it didn’t stop students from surfing the internet for completing their assignments. To tackle the issue of plagiarism, several tools like Turnitin emerged. Similarly here professors need to come up with better solutions to handle AI. One thing is for sure, running away isn’t the solution.

Accept it or get doomed

The ongoing discussion among the AI industry revolves around the potential threat to the existence of educational institutions if they don’t adapt accordingly. Recently, a X user posted “We should decimate educational institutions with AI

Similarly, Ethan Mollick, professor at Wharton posted on X “The start of the school year is AI chaos, with many instructors just ignoring AI. I think instructors need to make active choices about AI use (which might mean embracing AI or returning to in-class tests) and there is near certainty that models will improve over the school year.”

Mollick is not alone in expressing these sentiments. “Educational institutions are completely unprepared for the AI revolution. They managed to wing it last school year, but I feel they will be completely overwhelmed this coming year,” posted Bojan Tunguz, Machine Learning scientist at NVIDIA on X.

It’s pretty much clear that those who will embrace AI will survive and those who won’t are in for a hard time.

What’s needed?

Rather than seeing AI as a threat, educators can view it as a valuable partner. AI-driven chatbots, for instance, can provide immediate responses to student inquiries, freeing up professors to focus on more complex aspects of teaching.

Echoing similar sentiments, Rajeev Kumar Singh, Associate Dean Academics at Shiv Nadar University in a recent interaction told AIM that he is optimistic about adopting AI tools in teaching methods. He explained this will give faculty some extra time to spend on discussions with students one on one.

“Let’s say I take 45 lectures and I find that in 10, I was only transferring information. So, if that can be outsourced to some technology, I can spend the entire rest of the lectures on really bigger things. If I can save that time, then I can really engage one to one with students, which can be very fruitful, it can lead to a lot of personalised assessments, learning and also relationships.”

It’s understandable that it is tough for educators and professors to start from scratch to understand this new technology. However, it is for their betterment only. Otherwise chances are pretty much that AI will replace average teachers and amplify skilled educators. Earlier this year, Harvard University announced that its coding course, CS50 will be taught by an AI instructor. So, the reality isn’t far away.

To give themselves a head start, professors can go through a five part YouTube series on ‘Practical AI for Teachers & Students’ created by Mollick. Mollick went on to say that he agrees it is a lot for instructors to handle among their other obligations, “but the tech isn’t going away.

To assist educators with AI, he has even published two papers ‘Assigning AI: Seven Approaches for Students, with Prompts’ and ‘Using AI to Implement Effective Teaching Strategies in Classrooms: Five Strategies, Including Prompts’.

Not only that OpenAI recently took initiative to educate teachers how they can use ChatGPT in schools and universities. They gave several examples on how teachers can come up with lesson plans made with the help of ChatGPT.

Moreover, universities themselves can organise sessions designed to educate both faculty and students about the implications of large language models by partnering with industry experts. For instance, Shiv Nadar University recently hosted one session titled “The New Landscape: Designing in the Times of Dall-E, Midjourney, and ChatGPT!”.

It’s not too late

The good news is that educational institutions still have time to make corrections. The process of integrating AI can begin with the admission process. Universities can consider developing their own LLMs, which would greatly assist students in navigating the admission process.

Similarly, schools and colleges can create a process that emphasises students’ critical thinking skills while still allowing them to utilize ChatGPT for assistance. There is no denying the fact that ChatGPT provides the best answers when asked the right questions.

Many believe that personalised AI assistants are going to be a thing in the future. If we extend that idea to education soon we might also get personalised AI tutors who would be teaching students according to their requirements and understanding capabilities.

This will solve Bloom’s Sigma 2 problem. Bloom’s research found that students who were taught one-on-one or in small groups and received regular feedback performed two standard deviations (2 sigma) better than their peers who received traditional classroom instruction.

One can get a rough idea of how the future is going to look from Musk’s private school he created for his children—called Ad Astra. It is quietly built inside the SpaceX campus and has partnered with Synthesis, founded by Joshua Dahn. Synthesis has created an AI Tutor which teaches students complex concepts of math through personalised games and AI tools.

The post AI Clock is Ticking: Wake Up Call for Education Institutions appeared first on Analytics India Magazine.

Hands-On with Supervised Learning: Linear Regression

Hands-On with Supervised Learning: Linear Regression
Image by Author Basic Overview

Linear regression is the fundamental supervised machine learning algorithm for predicting the continuous target variables based on the input features. As the name suggests it assumes that the relationship between the dependant and independent variable is linear. So if we try to plot the dependent variable Y against the independent variable X, we will obtain a straight line. The equation of this line can be represented by:

Equation

Where,

  • Y Predicted output.
  • X = Input feature or feature matrix in multiple linear regression
  • b0 = Intercept (where the line crosses the Y-axis).
  • b1 = Slope or coefficient that determines the line's steepness.

The central idea in linear regression revolves around finding the best-fit line for our data points so that the error between the actual and predicted values is minimal. It does so by estimating the values of b0 and b1. We then utilize this line for making predictions.

Implementation Using Scikit-Learn

You now understand the theory behind linear regression but to further solidify our understanding, let's build a simple linear regression model using Scikit-learn, a popular machine learning library in Python. Please follow along for a better understanding.

1. Import Necessary Libraries

First, you will need to import the required libraries.

import os  import pandas as pd  import numpy as np  import matplotlib.pyplot as plt  from sklearn.linear_model import LinearRegression  from sklearn.preprocessing import StandardScaler  from sklearn.metrics import mean_squared_error

2. Analyzing the Dataset

You can find the dataset here. It contains separate CSV files for training and testing. Let’s display our dataset and analyze it before proceeding forward.

# Load the training and test datasets from CSV files  train = pd.read_csv('train.csv')  test = pd.read_csv('test.csv')    # Display the first few rows of the training dataset to understand its structure  print(train.head())

Output:

Hands-On with Supervised Learning: Linear Regression
train.head()

The dataset contains 2 variables and we want to predict y based on the value x.

# Check information about the training and test datasets, such as data types and missing values  print(train.info())  print(test.info())

Output:

  RangeIndex: 700 entries, 0 to 699  Data columns (total 2 columns):   #   Column  Non-Null Count  Dtype    ---  ------  --------------  -----     0   x       700 non-null    float64   1   y       699 non-null    float64  dtypes: float64(2)  memory usage: 11.1 KB          RangeIndex: 300 entries, 0 to 299  Data columns (total 2 columns):   #   Column  Non-Null Count  Dtype    ---  ------  --------------  -----     0   x       300 non-null    int64     1   y       300 non-null    float64  dtypes: float64(1), int64(1)  memory usage: 4.8 KB

The above output shows that we have a missing value in the training dataset that can be removed by the following command:

train = train.dropna()

Also, check if your dataset contains any duplicates and remove them before feeding it into your model.

duplicates_exist = train.duplicated().any()  print(duplicates_exist)

Output:

False

2. Preprocessing the Dataset

Now, prepare the training and testing data and target by the following code:

#Extracting x and y columns for train and test dataset  X_train = train['x']  y_train = train['y']  X_test = test['x']  y_test = test['y']  print(X_train.shape)  print(X_test.shape)

Output:

(699, )  (300, )

You can see that we have a one-dimensional array. While you could technically use one-dimensional arrays with some machine learning models, it's not the most common practice, and it may lead to unexpected behavior. So, we will reshape the above to (699,1) and (300,1) to explicitly specify that we have one label per data point.

X_train = X_train.values.reshape(-1, 1)  X_test = X_test.values.reshape(-1,1)

When the features are on different scales, some may dominate the model's learning process, leading to incorrect or suboptimal results. For this purpose, we perform the standardization so that our features have a mean of 0 and a standard deviation of 1.

Before:

print(X_train.min(),X_train.max())

Output:

(0.0, 100.0)

Standardization:

scaler = StandardScaler()  scaler.fit(X_train)  X_train = scaler.transform(X_train)  X_test = scaler.transform(X_test)  print((X_train.min(),X_train.max())

Output:

(-1.72857469859145, 1.7275858114641094)

We are now done with the essential data preprocessing steps, and our data is ready for training purposes.

4. Visualizing the Dataset

It's important to first visualize the relationship between our target variable and feature. You can do this by making a scatter plot:

# Create a scatter plot  plt.scatter(X_train, y_train)  plt.xlabel('X')  plt.ylabel('Y')  plt.title('Scatter Plot of Train Data')  plt.grid(True)  # Enable grid  plt.show()  

Hands-On with Supervised Learning: Linear Regression
Image by Author

5. Create and Train the Model

We will now create an instance of the Linear Regression model using Scikit Learn and try to fit it into our training dataset. It finds the coefficients (slopes) of the linear equation that best fits your data. This line is then used to make the predictions. Code for this step is as follows:

# Create a Linear Regression model  model = LinearRegression()    # Fit the model to the training data   model.fit(X_train, y_train)    # Use the trained model to predict the target values for the test data  predictions = model.predict(X_test)    # Calculate the mean squared error (MSE) as the evaluation metric to assess model performance  mse = mean_squared_error(y_test, predictions)  print(f'Mean squared error is: {mse:.4f}')

Output:

Mean squared error is: 9.4329

6. Visualize the Regression Line

We can plot our regression line using the following command:

# Plot the regression line  plt.plot(X_test, predictions, color='red', linewidth=2, label='Regression Line')    plt.xlabel('X')  plt.ylabel('Y')  plt.title('Linear Regression Model')  plt.legend()  plt.grid(True)  plt.show()

Output:

Hands-On with Supervised Learning: Linear Regression
Image by Author Conclusion

That's a wrap! You've now successfully implemented a fundamental Linear Regression model using Scikit-learn. The skills you've acquired here can be extended to tackle complex datasets with more features. It's a challenge worth exploring in your free time, opening doors to the exciting world of data-driven problem-solving and innovation.
Kanwal Mehreen is an aspiring software developer with a keen interest in data science and applications of AI in medicine. Kanwal was selected as the Google Generation Scholar 2022 for the APAC region. Kanwal loves to share technical knowledge by writing articles on trending topics, and is passionate about improving the representation of women in tech industry.

More On This Topic

  • Comparing Linear and Logistic Regression
  • 3 Reasons Why You Should Use Linear Regression Models Instead of Neural…
  • Linear vs Logistic Regression: A Succinct Explanation
  • KDnuggets News 22:n12, March 23: Best Data Science Books for Beginners;…
  • Linear Regression for Data Science
  • Making Predictions: A Beginner's Guide to Linear Regression in Python

New Study Suggests Ecology as a Model for AI Innovation

Artificial Intelligence (AI) has often been regarded through the lens of neurology, simulating processes rooted in human cognition. However, a recently published paper from the *Proceedings of the National Academy of Sciences* (PNAS) introduces a novel perspective, suggesting ecology as a new muse for AI innovation. This convergence isn't just an academic exercise; it's presented as an urgent necessity to tackle some of the world's pressing challenges.

AI Augmenting Ecological Endeavors

Artificial Intelligence's prowess is already being harnessed by ecologists in tasks like data pattern recognition and making predictive analyses. Barbara Han, a disease ecologist, captures the transformative potential AI holds for ecology, stating, The kinds of problems that we deal with regularly in ecology… if AI could help, it could mean so much for the global good. It could really benefit humankind.”

In traditional scientific methods, understanding often emerges from studying variables in isolation or pairs. However, the multifaceted nature of ecological systems defies this approach. For instance, while trying to predict disease transmission, researchers often grapple with multitudes of interplaying factors, from environmental to socio-cultural dimensions. Integrating AI could streamline these analyses, ensuring a holistic understanding. As Shannon LaDeau points out, AI's ability to assimilate vast and varied data sources might uncover previously overlooked drivers and interactions in ecological systems.

Image: Cary Institute of Ecosystem Studies

Taking a Leaf Out of Ecology's Book

As much as AI can amplify ecological research, ecology offers treasure troves of insights to refine AI. Current AI systems, while advanced, still grapple with vulnerabilities, from misdiagnoses in healthcare to errors in autonomous vehicles. What makes ecology intriguing is its inherent resilience. Such robustness in natural systems, when translated into AI architecture, could mitigate issues like the ‘mode collapse' observed in neural networks.

Ecological studies emphasize multilayered analysis and a holistic view. This approach could help unravel peculiar behaviors seen in advanced AI systems, such as the unanticipated outputs in large language models. While scale can enhance an AI model's capabilities, the CEO of OpenAI underscores the need for alternative inspirations, hinting at ecology as a potential path for innovative thinking.

Toward a Collaborative Horizon

While AI and ecology have evolved somewhat independently, the current discourse emphasizes their deliberate convergence for mutual advancement. Such a union foresees resilient AI models, capable of adeptly modeling and understanding their ecological counterparts, fostering a virtuous cycle.

However, a word of caution emerges from the realms of data inclusivity. Kathleen Weathers, an ecosystem scientist, highlights the risks of overlooking segments of society in data, cautioning against the inadvertent creation of biased models.

To truly realize the potential of this merger, the academic and practical barriers separating these fields must be addressed. This means harmonizing terminologies, aligning methodologies, and pooling resources. As we stand on the brink of this interdisciplinary era, one can't help but envision the plethora of solutions and innovations poised to emerge from this union, equipping us better for the challenges of the future.

Understanding Supervised Learning: Theory and Overview

Understanding Supervised Learning: Theory and Overview
Image by Author

Supervised is a subcategory of machine learning in which the computer learns from the labeled dataset containing both the input as well as the correct output. It tries to find the mapping function that relates the input (x) to the output (y). You can think of it as teaching your younger brother or sister how to recognize different animals. You will show them some pictures (x) and tell them what each animal is called (y). After a certain time, they will learn the differences and will be able to recognize the new picture correctly. This is the basic intuition behind supervised learning. Before moving forward, let's take a deeper look at its workings.

How Does Supervised Learning Work?

Understanding Supervised Learning: Theory and Overview
Image by Author

Suppose that you want to build a model that can differentiate between apples and oranges based on some characteristics. We can break down the process into the following tasks:

  • Data Collection: Gather a dataset with pictures of apples and oranges, and each image is labeled as either "apple" or "orange."
  • Model Selection: We have to pick the right classifier here often known as the right supervised machine learning algorithm for your task. It is just like picking the right glasses that will help you see better
  • Training the Model: Now, you feed the algorithm with the labeled images of apples and oranges. The algorithm looks at these pictures and learns to recognize the differences, such as the color, shape, and size of apples and oranges.
  • Evaluating & Testing: To check if your model is working correctly, we will feed some unseen pictures to it and compare the predictions with the actual one.

Types of Supervised Learning

Supervised learning can be divided into two main types:

Classification

In classification tasks, the primary objective is to assign data points to specific categories from a set of discrete classes. When there are only two possible outcomes, such as "yes" or "no," "spam" or "not spam," "accepted" or "rejected," it is referred to as binary classification. However, when there are more than two categories or classes involved, like grading students based on their marks (e.g., A, B, C, D, F), it becomes an example of a multi-classification problem.

Regression

For regression problems, you are trying to predict a continuous numerical value. For example, you might be interested in predicting your final exam scores based on your past performance in the class. The predicted scores can span any value within a specific range, typically from 0 to 100 in our case.

Overview of Popular Supervised Learning Algorithms

Now, we have a basic understanding of the overall process. We will explore the popular supervised machine learning algorithms, their usage, and how they work:

1. Linear Regression

As the name suggests, it is used for regression tasks like predicting stock prices, forecasting the temperature, estimating the likelihood of disease progression, etc. We try to predict the target (dependent variable) using the set of labels (independent variables). It assumes that we have a linear relationship between our input features and the label. The central idea revolves around predicting the best-fit line for our data points by minimizing the error between our actual and predicted values. This line is represented by the equation:

Equation

Where,

  • Y Predicted output.
  • X = Input feature or feature matrix in multiple linear regression
  • b0 = Intercept (where the line crosses the Y-axis).
  • b1 = Slope or coefficient that determines the line's steepness.

It estimates the slope of the line (weight) and its intercept(bias). This line can be used further to make predictions. Although it is the simplest and useful model for developing the baselines it is highly sensitive to outliers that may influence the position of the line.

Understanding Supervised Learning: Theory and Overview
Gif on Primo.ai

2. Logistic Regression

Although it has regression in its name, but is fundamentally used for binary classification problems. It predicts the probability of a positive outcome (dependent variable) which lies in the range of 0 to 1. By setting a threshold (usually 0.5), we classify data points: those with a probability greater than the threshold belongs to the positive class, and vice versa. Logistic regression calculates this probability using the sigmoid function applied to the linear combination of the input features which is specified as:

Equation

Where,

  • P(Y=1) = Probability of the data point belonging to the positive class
  • X1 ,… ,Xn = Input Features
  • b0,….,bn = Input weights that the algorithm learns during training

This sigmoid function is in the form of S like curve that transforms any data point to a probability score within the range of 0-1. You can see the below graph for a better understanding.

Understanding Supervised Learning: Theory and Overview
Image on Wikipedia

A closer value to 1 indicates a higher confidence in the model in its prediction. Just like linear regression, it is known for its simplicity but we cannot perform the multi-class classification without modification to the original algorithm.

3. Decision Trees

Unlike the above two algorithms, decision trees can be used for both classification and regression tasks. It has a hierarchical structure just like the flowcharts. At each node, a decision about the path is made based on some feature values. The process continues unless we reach the last node that depicts the final decision. Here is some basic terminology that you must be aware of:

  • Root Node: The top node containing the entire dataset is called the root node. We then select the best feature using some algorithm to split the dataset into 2 or more sub-trees.
  • Internal Nodes: Each Internal node represents a specific feature and a decision rule to decide the next possible direction for a data point.
  • Leaf Nodes: The ending nodes that represent a class label are referred to as leaf nodes.

It predicts the continuous numerical values for the regression tasks. As the size of the dataset grows, it captures the noise leading to overfitting. This can be handled by pruning the decision tree. We remove branches that don't significantly improve the accuracy of our decisions. This helps keep our tree focused on the most important factors and prevents it from getting lost in the details.

Understanding Supervised Learning: Theory and Overview
Image by Jake Hoare on Displayr

4. Random Forest

Random forest can also be used for both the classification and the regression tasks. It is a group of decision trees working together to make the final prediction. You can think of it as the committee of experts making a collective decision. Here is how it works:

  • Data Sampling: Instead of taking the entire dataset at once, it takes the random samples via a process called bootstrapping or bagging.
  • Feature Selection: For each decision tree in a random forest, only the random subset of features is considered for the decision-making instead of the complete feature set.
  • Voting: For classification, each decision tree in the random forest casts its vote and the class with the highest votes is selected. For regression, we average the values obtained from all trees.

Although it reduces the effect of overfitting caused by individual decision trees, but is computationally expensive. One word that you will read frequently in the literature is that the random forest is an ensemble learning method, which means it combines multiple models to improve overall performance.

5. Support Vector Machines (SVM)

It is primarily used for classification problems but can handle regression tasks as well. It tries to find the best hyperplane that separates the distinct classes using the statistical approach, unlike the probabilistic approach of logistic regression. We can use the linear SVM for the linearly separable data. However, most of the real-world data is non-linear and we use the kernel tricks to separate the classes. Let's dive deep into how it works:

  • Hyperplane Selection: In binary classification, SVM finds the best hyperplane (2-D line) to separate the classes while maximizing the margin. Margin is the distance between the hyperplane and the closest data points to the hyperplane.
  • Kernel Trick: For linearly inseparable data, we employ a kernel trick that maps the original data space into a high-dimensional space where they can be separated linearly. Common kernels include linear, polynomial, radial basis function (RBF), and sigmoid kernels.
  • Margin Maximization: SVM also tries to improve the generalization of the model by increasing the maximizing margin.
  • Classification: Once the model is trained, the predictions can be made based on their position relative to the hyperplane.

SVM also has a parameter called C that controls the trade-off between maximizing the margin and keeping the classification error to a minimum. Although they can handle high-dimensional and non-linear data well, choosing the right kernel and hyperparameter is not as easy as it seems.

Understanding Supervised Learning: Theory and Overview
Image on Javatpoint

6. k-Nearest Neighbors (k-NN)

K-NN is the simplest supervised learning algorithm mostly used for classification tasks. It doesn’t make any assumptions about the data and assigns the new data point a category based on its similarity with the existing ones. During the training phase, it keeps the entire dataset as a reference point. It then calculates the distance between the new data point and all the existing points using a distance metric (Eucilinedain distance e.g.). Based on these distances, it identifies the K nearest neighbors to these data points. We then count the occurrence of each class in the K nearest neighbors and assign the most frequently appearing class as the final prediction.

Understanding Supervised Learning: Theory and Overview
Image on GeeksforGeeks

Choosing the right value of K requires experimentation. Although it is robust to noisy data it is not suitable for high dimensional datasets and has a high cost associated due to the calculation of the distance from all data points.

Wrapping Up

As I conclude this article, I would encourage the readers to explore more algorithms and try to implement them from scratch. This will strengthen your understanding of how things are working under the hood. Here are some additional resources to help you get started:

  • Mastering Machine Learning Algorithms — Second Edition
  • Machine Learning Course — Javatpoint
  • Machine Learning Specialization — Coursera

Kanwal Mehreen is an aspiring software developer with a keen interest in data science and applications of AI in medicine. Kanwal was selected as the Google Generation Scholar 2022 for the APAC region. Kanwal loves to share technical knowledge by writing articles on trending topics, and is passionate about improving the representation of women in tech industry.

More On This Topic

  • Statistics in Data Science: Theory and Overview
  • Understanding Machine Learning Algorithms: An In-Depth Overview
  • Primary Supervised Learning Algorithms Used in Machine Learning
  • KDnuggets News, June 22: Primary Supervised Learning Algorithms Used in…
  • Data Visualization: Theory and Techniques
  • What is Graph Theory, and Why Should You Care?

AI Apps Product Development Canvas – Part 2

Slide1-2

In part 1 of this series on the updated “AI Apps Development Canvas,” I introduced the updated AI Apps Product Development Design Canvas. The AI Apps Product Development Canva is one of the capstone deliverables for my “Thinking Like a Data Scientist” methodology, so getting feedback is critical to ensure that the methodology is relevant and practical.

Several folks and students tested the canvas and gave me great feedback, resulting in this updated design canvas (Figure 1).

Slide2-3

Figure 1: AI Apps Development Canvas

I will leverage the canvas in part 2 of this series to create a “Local Events Marketing Effectiveness” AI app. This is not a short exercise and reflects how comprehensively one has followed the steps and design canvases for the “Thinking Like a Data Scientist” methodology.

Example: Local Events Marketing Effectiveness App

Here is my attempt to complete the AI App Development Canvas to develop a “Local Events Marketing Effectiveness” AI app that supports store management and local / field marketing in selecting, designing, managing, and optimizing local events marketing effectiveness.

  • (1) User problem and usage scenario: Optimizing the selection, sponsorship, and participation in local community activities and events that can increase brand awareness, goodwill, and customer acquisition. The usage scenario is that the key stakeholders (store management, local marketing, field marketing, corporate marketing) can use the app to explore, evaluate, and execute local events marketing campaigns based on the predicted impact of each event on the targeted customer segments.
  • (2) Targeted users and desired outcomes: The targeted users are the key stakeholders involved in local events marketing, such as store managers, local marketers, field marketers, and corporate marketers. Their desired outcomes are to increase store traffic, sales, loyalty, and referrals by sponsoring and participating in local events that can attract and engage potential and existing customers.
  • (3) User gains or benefits: The user gains or benefits from using the app are:
    • Improved ROI of local events marketing by selecting the most effective events based on the predicted impact on customer behavior and value.
    • Enhanced customer experience by creating personalized and relevant customer interactions during and after the events.
    • Increased brand awareness and goodwill by supporting local community causes and activities that resonate with customers.
    • Reduced operational costs by automating and streamlining the planning, execution, and evaluation of local events marketing campaigns.
  • (4) Potential user impediments: The potential user impediments that may hamper the usage and adoption of the app are:
    • Poor data quality and availability for some local events or customer segments may limit the accuracy and reliability of the app’s predictions and recommendations.
    • Resistance to change from some stakeholders who may prefer to rely on their intuition or experience rather than data-driven insights for local events marketing decisions.
    • Privacy and ethical concerns from some customers who may not want their data to be used for marketing purposes or may perceive the app’s recommendations as intrusive or manipulative.
  • (5) Key business entities: The key business entities around which data must be captured and analytics must be built are:
    • Events: The local community activities and events that the app can recommend for sponsorship and participation, such as sports games, concerts, festivals, school activities, etc. The data attributes for each event may include name, date, time, location, type, category, organizer, audience size, cost, etc.
    • Customers: The potential and existing customers who may attend or be influenced by the sponsored or participated events. The data attributes for each customer may include ID, name, age, gender, location, preferences, behavior, value, loyalty, etc.
    • Campaigns: The local events marketing campaigns that the app can help plan, execute, and evaluate. The data attributes for each campaign may include ID, name, objective, budget, duration, events list, target customer segments, expected outcomes, actual outcomes, etc.
  • (6) Upstream system or application dependencies: The upstream system or application dependencies that are necessary to ensure that the correct data is being provided at the right times for the operation of the app are:
    • Data sources: The app will need to access various data sources that contain information about events, customers, and campaigns, such as internal databases, CRM systems, social media platforms, event websites, etc.
    • Data ingestion: The app must ingest, validate, and standardize the data from different sources using appropriate methods and formats, such as APIs, ETL processes, CSV files, etc.
    • Data integration: The app will need to integrate and harmonize the data from different data sources using common identifiers and schemas, such as event ID, customer ID, campaign ID, etc.
  • (7) Downstream system or application dependencies: The downstream system or application dependencies into which the results of the app must be fed or materialized are:
    • Campaign management: The app must feed the recommended events and target customer segments into the campaign management system or application that will help execute and monitor the local events marketing campaigns.
    • Customer engagement: The app must feed personalized and relevant interactions and offers into the customer engagement system or application to help communicate and interact with customers during and after the events.
    • Business intelligence: The app will need to feed the actual outcomes and performance metrics of the local events marketing campaigns into the business intelligence system or application that will help analyze and report the effectiveness and ROI of the campaigns.
  • (8) Key decisions or actions: The key decisions or actions that the user will take from using the app are:
    • Selecting the most suitable events for sponsorship and participation based on the predicted impact on customer behavior and value.
    • Segmenting and targeting the potential and existing customers who may attend or be influenced by the sponsored or participated events based on their preferences, behavior, value, loyalty, etc.
    • Creating and delivering personalized and relevant interactions and offers to customers during and after the events based on their predicted propensities and responses.
    • Evaluating and optimizing the performance and ROI of the local events marketing campaigns based on the actual outcomes and feedback.
  • (9) KPIs and metrics: The KPIs and metrics that the user will use to measure the success of the app are:
    • Customer acquisition: The number and percentage of new customers acquired due to the local events marketing campaigns.
    • Customer retention: The number and percentage of existing customers retained due to the local events marketing campaigns.
    • Customer loyalty: The number and percentage of customers who are loyal or advocates as a result of the local events marketing campaigns.
    • Customer value: The average revenue, profit, and lifetime value of customers influenced by the local events marketing campaigns.
    • Campaign ROI: The ratio of the net profit to the total cost of the local events marketing campaigns.
  • (10) Prescriptive recommendations: The prescriptive recommendations that the app must deliver to help the user make the decisions that help them achieve their desired outcomes are:
    • Event recommendation: The app must recommend the best events for sponsorship and participation based on the predicted impact on customer behavior and value, as well as the budget and objective of the campaign.
    • Customer segment recommendation: The app must recommend the optimal customer segments for targeting based on their preferences, behavior, value, loyalty, etc., as well as the event characteristics and expected outcomes.
    • Interaction and offer recommendation: The app must recommend the most effective interactions and offers to deliver to customers during and after the events based on their predicted propensities and responses, as well as the campaign objective and budget.
  • (11) Analytic (predictive) scores: The analytic (predictive) scores that will need to be created that power the prescriptive recommendations are:
    • Event impact score: The score that measures the predicted impact of each event on customer behavior and value, such as attendance, engagement, conversion, retention, loyalty, revenue, profit, etc.
    • Customer segment score: The score that measures the predicted attractiveness and profitability of each customer segment for each event, such as preference, behavior, value, loyalty, etc.
    • Interaction and offer response score: The score that measures the predicted propensity and response of each customer to each interaction and offer during and after each event, such as click-through rate, redemption rate, satisfaction rate, etc.
  • (12) Data sources: The data sources that support the creation of the ML features that will drive the predictive effectiveness of the analytic score are:
    • Internal data sources: The data sources that contain information about customers and campaigns from the organization’s systems and databases, such as CRM, POS, loyalty, etc.
    • External data sources: The data sources that contain information about events and customers from external platforms and websites, such as social media, event websites, etc.
  • (13) Data transformations: The data transformations that are necessary to prepare the data for consumption by the ML models are:
    • Data cleaning: The process of removing or correcting invalid, incomplete, inconsistent, or irrelevant data from the data sources.
    • Data encoding: The process of converting categorical or textual data into numerical or binary data that the ML models can use.
    • Data scaling: The process of transforming numerical data into a standard range or scale that can improve the performance of the ML models.
    • Data aggregation: The process of combining or summarizing data from different sources or levels into a single or higher level that can provide more meaningful insights for the ML models.
    • Data splitting: The process of dividing the data into training, validation, and testing sets that can be used to train, tune, and evaluate the ML models.
  • (14) Machine learning (ML) features: The ML features that the ML model uses to generate predictions and prescriptive recommendations are:
    • Event features: The features that describe the characteristics of each event, such as name, date, time, location, type, category, organizer, audience size, cost, etc.
    • Customer features: The features that describe the attributes of each customer, such as ID, name, age, gender, location, preferences, behavior, value, loyalty, etc.
    • Campaign features: The features that describe the details of each campaign, such as ID, name, objective, budget, duration, events list, target customer segments, expected outcomes, etc.
    • Interaction and offer features: The features that describe the content and delivery of each interaction and offer during and after each event, such as type, channel, message, offer value, timing, etc.
  • (15) Model performance: Accuracy, recall, and precision measures will evaluate how well the ML models generate accurate and reliable predictions and prescriptive recommendations for each event, customer segment, interaction, and offer.
  • (16) Model monitoring or observability: Model monitoring involves tracking and analyzing the key metrics and indicators of the app’s performance, such as data quality, data drift, model accuracy, model drift, model bias, model explainability, model robustness, model reliability, etc. These metrics and indicators can help identify and resolve issues or anomalies affecting the app’s functionality and usability.
  • (17) App software development requirements: The app software development requirements are the specifications and documentation of the app’s features, functions, interfaces, design, architecture, testing, deployment, maintenance, etc. They also include the tools and frameworks used to develop the app.
  • (18) API requirements: The API requirements are the specifications and documentation of the app’s APIs that enable the communication and exchange of data and results between the app and other systems or applications. They also include the tools and frameworks to create and manage the app’s APIs.
  • (20) Model feedback metrics: The model feedback metrics measure the actual outcomes and feedback of the local events marketing campaigns, such as attendance rate, engagement rate, conversion rate, retention rate, loyalty rate, revenue rate, profit rate, satisfaction rate, etc. They also include user satisfaction and app adoption measures, such as usage rate, retention rate, churn rate, referral rate, rating score, review score, etc.
  • (21) Model feedback methods: The model feedback methods are the techniques and sources used to gather and process the data and information about the actual outcomes and feedback of the local events marketing campaigns and the user satisfaction and adoption of the app. They may include surveys, interviews, focus groups, online reviews, social media posts, web analytics tools, etc.
  • (22) App UI / UEX requirements: The app UI / UEX requirements are the specifications and documentation of the app’s user interface (UI) and user experience (UX) design that define how the app looks and feels to the user. They also include the tools and frameworks used to create and test the app’s UI / UX design, such as wireframes, mockups, prototypes, usability testing tools, etc.
  • (23) Privacy plans: The privacy plans ensure the proper storage and management of “personal identifiable information” (PII) that follows privacy regulations like GDPR, HIPAA, CCPA
  • (24) User feedback and testing: The user feedback and testing specifications for the “Optimize Local Events Marketing” app are:
    • Plan for collecting and incorporating user feedback and testing throughout the app development process. This will help ensure that the app meets the user’s needs and expectations and identify and fix any issues or bugs that may arise.
    • Methods and sources to gather and process user feedback and testing data include surveys, interviews, focus groups, online reviews, social media posts, web analytics tools, etc.
    • Metrics and indicators to measure and evaluate user feedback and testing results, such as usage rate, retention rate, churn rate, referral rate, rating score, review score, satisfaction rate, etc.
    • Techniques and tools to analyze and visualize user feedback and testing data include descriptive statistics, sentiment analysis, text mining, word clouds, charts, graphs, dashboards, etc.
    • Procedures to incorporate user feedback and testing insights into the app design and development, such as prioritizing user requirements, modifying app features, functions, interfaces, design, architecture, testing, deployment, maintenance, etc.
  • (25) Potential Unintended Consequences (added by Neil Raden): A plan for identifying and mitigating the potential unintended consequences of using the app. These may include the negative impacts or risks that the app may have on the users, customers, events, communities, or society at large.
  • Monitor and evaluate the potential unintended consequences of the app, such as ethical frameworks, impact assessments, audits, reviews, feedback, etc.
  • Metrics and indicators to measure and report the potential unintended consequences of the app, such as fairness, transparency, accountability, privacy, security, etc.
  • Techniques and tools to prevent and address the potential unintended consequences of the app, such as data anonymization, data minimization, data quality control, model explainability, model robustness, model bias detection and correction, etc.
  • Procedures to communicate and disclose the potential unintended consequences of the app to the users, customers, events, or communities, such as consent forms, privacy policies, terms and conditions, notifications, warnings, etc.

Summary

I’m already over my word count on this baby, so I’ll leave it to the audience (and my students) to review and grade. Have fun!

Why AI Tech Honchos are Meeting Behind Closed Doors

Akin to a star-studded event with the crème de la crème of the tech industry, the latest AI Insight Forum held on Capitol Hill was nothing short of a billionaire conclave. The closed-door session brought together all the tech titans with a combined net worth of approximately $550 billion, to delve into the future of AI, with a particular focus on the widely debated topic of ‘AI regulation.’ Unlike past AI senate hearings that featured testimonies from OpenAI’s Sam Altman, Anthropic CEO Dario Amodei, among others, the recent session that assembled luminaries such as Elon Musk, Bill Gates, and many more, was not open to the public or media, which raises the question of what crucial or controversial discussions unfolded behind closed doors?

AI Insight Forum. Source: The Guardian

Applauds and Joy- What Next?

New York Senator Chuck Schumer, who was among the 60 senators that took part, called the meet a ‘very productive first-ever AI Insight Forum’, and the task ahead as an arduous one. The Congress is seeking to pass a bipartisan AI legislation within the next year which aims to mitigate the problems associated with AI risks.

The tech tycoons who attended the event lauded the session for promoting an open discussion on AI regulation. Sam Altman, Meta founder Mark Zuckerberg, NVIDIA Chief Jensen Huang, Microsoft CEO Satya Nadella, Alphabet CEO Sundar Pichhai, CEO of IBM Arvind Krishna, Palantir CEO Alex Karp, former Google CEO Eric Schmidt, HuggingFace CEO Clement Delangue, co-founder & Executive Director of the Center for Humane Technology Tristan Harris, were some of the biggies in attendance. Elon Musk referred to the meeting as a service to humanity, calling it a very important event for the future of civilization. Calling AI a ‘double-edged sword’, Musk also emphasised on the need for having a ‘referee’ to ensure companies take safe actions and protect the interests of the general public.

Zuckerberg also weighed in after the meeting saying that the Congress should engage with AI to promote innovation and establish protective measures, and said that it is better that the Government works with big tech companies on such issues.

Ringing a familiar tone from previous AI discussions, both the leaders and senators seemed to be in approval of having regulations that will possibly mitigate the dangers of AI. However, the question on how they would go about it remains hanging.

Licensing Behind Closed Doors

Senator Schumer said the closed forum facilitated an open discussion among the attendees foregoing the normal time and format restrictions that are part of such public hearings, and also said that some of the future forums will be open to the public.

With a legislation bill in mind, the possibility of bringing a licence for running large language models was hinted at by computer science professor of University of Washington, Pedro Domingos.

The notion that you should need a government license to learn and run an LLM, now being contemplated by Congress, is next-level inane. Which means it could well happen.

— Pedro Domingos (@pmddomingos) September 13, 2023

The possibility of licensing can also go two ways. With licensing, big tech companies will approach AI development with caution, and probably serve as a catalyst for responsible AI. However, if obtaining a licence is mandated, it is possible that AI development will be hindered in smaller tech companies, and they may fall behind in the race. Thus, the trickiness of manoeuvring through AI regulations cannot be blanketed across companies. Interestingly, Sam Altman in the past had mentioned that there should be no regulation on smaller companies.

Looking back at how a number of leaders signed a petition to slow the growth of AI development a few months ago, demanding OpenAI to not train advanced models such as GPT-5, if any form of regulatory bills surfaces from the Congress, the ones impacted will be large corporations. Hence, the tech honchos convened.

Proactive Approach

In the past, the US government has been indecisive of regulations around new technology. For instance, autonomous vehicles are not completed regulated in the US. Despite accidents caused by these vehicles, there is still no clear picture on any legislation for self-driving cars. Efforts by Congress to enact autonomous vehicle legislation have faced years of delay. Similarly, looking back at how cryptocurrency regulations came into picture after a few years of being in the market, and gathering up frauds and fund misplacements till then, the US government’s regulatory approach towards AI seems to be preventive.

Trying to bypass previous mistakes where the negative aftermath of certain technology/product at its nascent stage of release went unregulated, the government is taking a proactive approach towards AI regulation.

The government looks to mitigate the technology before the situation goes south. Furthermore, with the countless AI doomsday predictions by AI researchers and experts, the matter has been gravely looked at. Interestingly, in a 2016 interview, Musk told Altman about the need to democratise AI technology and how AI can be used in a bad way.

Going by how the Senate talks started four months ago, and a few companies such as OpenAI launched initiatives to democratise AI, nothing concrete has come into fruition. In the process, companies, not just in the US but across the globe are continuing to release advanced models. Looks like, if any regulation has to happen, it better happen fast.

The post Why AI Tech Honchos are Meeting Behind Closed Doors appeared first on Analytics India Magazine.

Getting Started with Scikit-learn in 5 Steps

Getting Started with Scikit-learn in 5 Steps

Introduction to Scikit-learn

When learning about how to use Scikit-learn, we must obviously have an existing understanding of the underlying concepts of machine learning, as Scikit-learn is nothing more than a practical tool for implementing machine learning principles and related tasks. Machine learning is a subset of artificial intelligence that enables computers to learn and improve from experience without being explicitly programmed. The algorithms use training data to make predictions or decisions by uncovering patterns and insights. There are three main types of machine learning:

  • Supervised learning — Models are trained on labeled data, learning to map inputs to outputs
  • Unsupervised learning — Models work to uncover hidden patterns and groupings within unlabeled data
  • Reinforcement learning — Models learn by interacting with an environment, receiving rewards and punishments to encourage optimal behavior

As you are undoubtedly aware, machine learning powers many aspects of modern society, generating enormous amounts of data. As data availability continues to grow, so does the importance of machine learning.

Scikit-learn is a popular open source Python library for machine learning. Some key reasons for its widespread use include:

  • Simple and efficient tools for data analysis and modeling
  • Accessible to Python programmers, with focus on clarity
  • Built on NumPy, SciPy and matplotlib for easier integration
  • Wide range of algorithms for tasks like classification, regression, clustering, dimensionality reduction

This tutorial aims to offer a step-by-step walkthrough of using Scikit-learn (mainly for common supervised learning tasks), focusing on getting started with extensive hands-on examples.

Step 1: Getting Started with Scikit-learn

Installation and Setup

In order to install and use Scikit-learn, your system must have a functioning Python installation. We won't be covering that here, but will assume that you have a functioning installation at this point.

Scikit-learn can be installed using pip, Python's package manager:

pip install scikit-learn

This will also install any required dependencies like NumPy and SciPy. Once installed, Scikit-learn can be imported in your Python scripts as follows:

import sklearn

Testing Your Installation

Once installed, you can start a Python interpreter and run the import command above.

Python 3.10.11 (main, May 2 2023, 00:28:57) [GCC 11.2.0] on linux  Type "help", "copyright", "credits" or "license" for more information.  >>> import sklearn

So long as you do not see any error messages, you are now ready to start using Scikit-learn!

Loading Sample Datasets

Scikit-learn provides a variety of sample datasets that we can use for testing and experimentation:

from sklearn import datasets    iris = datasets.load_iris()  digits = datasets.load_digits()

The digits dataset contains images of handwritten digits along with their labels. We can start familiarizing ourselves with Scikit-learn using these sample datasets before moving on to real-world data.

Step 2: Data Preprocessing

Importance of Data Preprocessing

Real-world data is often incomplete, inconsistent, and contains errors. Data preprocessing transforms raw data into a usable format for machine learning, and is an essential step that can impact the performance of downstream models.

Many novice practitioners often overlook proper data preprocessing, instead jumping right into model training. However, low quality data inputs will lead to low quality models outputs, regardless of the sophistication of the algorithms used. Steps like properly handling missing data, detecting and removing outliers, feature encoding, and feature scaling help boost model accuracy.

Data preprocessing accounts for a major portion of the time and effort spent on machine learning projects. The old computer science adage "garbage in, garbage out" very much applies here. High quality data inputs are a prerequisite for high performance machine learning. The data preprocessing steps transform the raw data into a refined training set that allows the machine learning algorithms to effectively uncover predictive patterns and insights.

So in summary, properly preprocessing the data is an indispensable step in any machine learning workflow, and should receive substantial focus and diligent effort.

Loading and Understanding Data

Let's load a sample dataset using Scikit-learn for demonstration:

from sklearn.datasets import load_iris  iris_data = load_iris()

We can explore the features and target values:

print(iris_data.data[0]) # Feature values for first sample  print(iris_data.target[0]) # Target value for first sample

We should understand the meaning of the features and target before proceeding.

Data Cleaning

Real data often contains missing, corrupt or outlier values. Scikit-learn provides tools to handle these issues:

from sklearn.impute import SimpleImputer    imputer = SimpleImputer(strategy='mean')    imputed_data = imputer.fit_transform(iris_data.data)

The imputer replaces missing values with the mean, which is a common — but not the only — strategy. This is just one approach for data cleaning.

Feature Scaling

Algorithms like Support Vector Machines (SVMs) and neural networks are sensitive to the scale of input features. Inconsistent feature scales can result in these algorithms giving undue importance to features with larger scales, thereby affecting the model's performance. Therefore, it's essential to normalize or standardize the features to bring them onto a similar scale before training these algorithms.

from sklearn.preprocessing import StandardScaler    scaler = StandardScaler()  scaled_data = scaler.fit_transform(iris_data.data)

StandardScaler standardizes features to have mean 0 and variance 1. Other scalers are also available.

Visualizing the Data

We can also visualize the data using matplotlib to gain further insights:

import matplotlib.pyplot as plt  plt.scatter(iris_data.data[:, 0], iris_data.data[:, 1], c=iris_data.target)  plt.xlabel('Sepal Length')  plt.ylabel('Sepal Width')  plt.show()

Data visualization serves multiple critical functions in the machine learning workflow. It allows you to spot underlying patterns and trends in the data, identify outliers that may skew model performance, and gain a deeper understanding of the relationships between variables. By visualizing the data beforehand, you can make more informed decisions during the feature selection and model training phases.

Step 3: Model Selection and Training

Overview of Scikit-learn Algorithms

Scikit-learn provides a variety of supervised and unsupervised algorithms:

  • Classification: Logistic Regression, SVM, Naive Bayes, Decision Trees, Random Forest
  • Regression: Linear Regression, SVR, Decision Trees, Random Forest
  • Clustering: k-Means, DBSCAN, Agglomerative Clustering

Along with many others.

Choosing an Algorithm

Choosing the most appropriate machine learning algorithm is vital for building high quality models. The best algorithm depends on a number of key factors:

  • The size and type of data available for training. Is it a small or large dataset? What kinds of features does it contain — images, text, numerical?
  • The available computing resources. Algorithms differ in their computational complexity. Simple linear models train faster than deep neural networks.
  • The specific problem we want to solve. Are we doing classification, regression, clustering, or something more complex?
  • Any special requirements like the need for interpretability. Linear models are more interpretable than black-box methods.
  • The desired accuracy/performance. Some algorithms simply perform better than others on certain tasks.

For our particular sample problem of categorizing iris flowers, a classification algorithm like Logistic Regression or Support Vector Machine would be most suitable. These can efficiently categorize the flowers based on the provided feature measurements. Other simpler algorithms may not provide sufficient accuracy. At the same time, very complex methods like deep neural networks would be overkill for this relatively simple dataset.

As we train models going forward, it is crucial to always select the most appropriate algorithms for our specific problems at hand, based on considerations such as those outlined above. Reliably choosing suitable algorithms will ensure we develop high quality machine learning systems.

Training a Simple Model

Let's train a Logistic Regression model:

from sklearn.linear_model import LogisticRegression    model = LogisticRegression()  model.fit(scaled_data, iris_data.target)

That's it! The model is trained and ready for evaluation and use.

Training a More Complex Model

While simple linear models like logistic regression can often provide decent performance, for more complex datasets we may need to leverage more sophisticated algorithms. For example, ensemble methods combine multiple models together, using techniques like bagging and boosting, to improve overall predictive accuracy. As an illustration, we can train a random forest classifier, which aggregates many decision trees:

from sklearn.ensemble import RandomForestClassifier    rf_model = RandomForestClassifier(n_estimators=100)   rf_model.fit(scaled_data, iris_data.target)

The random forest can capture non-linear relationships and complex interactions among the features, allowing it to produce more accurate predictions than any single decision tree. We can also employ algorithms like SVM, gradient boosted trees, and neural networks for further performance gains on challenging datasets. The key is to experiment with different algorithms beyond simple linear models to harness their strengths.

Note, however, that whether using a simple or more complex algorithm for model training, the Scikit-learn syntax allows for the same approach, reducing the learning curve dramatically. In fact, almost every task using the library can be expressed with the fit/transform/predict paradigm.

Step 4: Model Evaluation

Importance of Evaluation

Evaluating a machine learning model's performance is an absolutely crucial step before final deployment into production. Comprehensively evaluating models builds essential trust that the system will operate reliably once deployed. It also identifies potential areas needing improvement to enhance the model's predictive accuracy and generalization ability. A model may appear highly accurate on the training data it was fit on, but still fail miserably on real-world data. This highlights the critical need to test models on held-out test sets and new data, not just the training data.

We must simulate how the model will perform once deployed. Rigorously evaluating models also provides insights into possible overfitting, where a model memorizes patterns in the training data but fails to learn generalizable relationships useful for out-of-sample prediction. Detecting overfitting prompts appropriate countermeasures like regularization and cross-validation. Evaluation further allows comparing multiple candidate models to select the best performing option. Models that do not provide sufficient lift over a simple benchmark model should potentially be re-engineered or replaced entirely.

In summary, comprehensively evaluating machine learning models is indispensable for ensuring they are dependable and adding value. It is not merely an optional analytic exercise, but an integral part of the model development workflow that enables deploying truly effective systems. So machine learning practitioners should devote substantial effort towards properly evaluating their models across relevant performance metrics on representative test sets before even considering deployment.

Train/Test Split

We split the data to evaluate model performance on new data:

from sklearn.model_selection import train_test_split    X_train, X_test, y_train, y_test = train_test_split(scaled_data, iris_data.target)

By convention, X refers to features and y refers to target variable. Please note that y_test and iris_data.target are different ways to refer to the same data.

Evaluation Metrics

For classification, key metrics include:

  • Accuracy: Overall proportion of correct predictions
  • Precision: Proportion of positive predictions that are actual positives
  • Recall: Proportion of actual positives predicted positively

These can be computed via Scikit-learn's classification report:

from sklearn.metrics import classification_report    print(classification_report(y_test, model.predict(X_test)))

This gives us insight into model performance.

Step 5: Improving Performance

Hyperparameter Tuning

Hyperparameters are model configuration settings. Tuning them can improve performance:

from sklearn.model_selection import GridSearchCV    params = {'C': [0.1, 1, 10]}  grid_search = GridSearchCV(model, params, cv=5)  grid_search.fit(scaled_data, iris_data.target)

This grids over different regularization strengths to optimize model accuracy.

Cross-Validation

Cross-validation provides more reliable evaluation of hyperparameters:

from sklearn.model_selection import cross_val_score    cross_val_scores = cross_val_score(model, scaled_data, iris_data.target, cv=5)

It splits the data into 5 folds and evaluates performance on each.

Ensemble Methods

Combining multiple models can enhance performance. To demonstrate this, let's first train a random forest model:

from sklearn.ensemble import RandomForestClassifier    random_forest = RandomForestClassifier(n_estimators=100)  random_forest.fit(scaled_data, iris_data.target)

Now we can proceed to create an ensemble model using both our logistic regression and random forest models:

from sklearn.ensemble import VotingClassifier    voting_clf = VotingClassifier(estimators=[('lr', model), ('rf', random_forest)])  voting_clf.fit(scaled_data, iris_data.target)

This ensemble model combines our previously trained logistic regression model, referred to as lr, with the newly defined random forest model, referred to as rf.

Model Stacking and Blending

More advanced ensemble techniques like stacking and blending build a meta-model to combine multiple base models. After training base models separately, a meta-model learns how best to combine them for optimal performance. This provides more flexibility than simple averaging or voting ensembles. The meta-learner can learn which models work best on different data segments. Stacking and blending ensembles with diverse base models often achieve state-of-the-art results across many machine learning tasks.

# Train base models  from sklearn.ensemble import RandomForestClassifier  from sklearn.svm import SVC    rf = RandomForestClassifier()  svc = SVC()    rf.fit(X_train, y_train)  svc.fit(X_train, y_train)    # Make predictions to train meta-model  rf_predictions = rf.predict(X_test)  svc_predictions = svc.predict(X_test)    # Create dataset for meta-model  blender = np.vstack((rf_predictions, svc_predictions)).T  blender_target = y_test    # Fit meta-model on predictions  from sklearn.ensemble import GradientBoostingClassifier    gb = GradientBoostingClassifier()  gb.fit(blender, blender_target)    # Make final predictions  final_predictions = gb.predict(blender)  

This trains a random forest and SVM model separately, then trains a gradient boosted tree on their predictions to produce the final output. The key steps are generating predictions from base models on the test set, then using those predictions as input features to train the meta-model.

Moving Forward

Scikit-learn provides an extensive toolkit for machine learning with Python. In this tutorial, we covered the complete machine learning workflow using Scikit-learn — from installing the library and understanding its capabilities, to loading data, training models, evaluating model performance, tuning hyperparameters, and compiling ensembles. The library has become hugely popular due to its well-designed API, breadth of algorithms, and integration with the PyData stack. Sklearn empowers users to quickly and efficiently build models and generate predictions without getting bogged down in implementation details. With this solid foundation, you can now practically apply machine learning to real-world problems using Scikit-learn. The next step entails identifying issues that are amenable to ML techniques, and leveraging the skills from this tutorial to extract value.

Of course, there is always more to learn about Scikit-learn specifically and machine learning in general. The library implements cutting-edge algorithms like neural networks, manifold learning, and deep learning using its estimator API. You can always extend your competency by studying the theoretical workings of these methods. Scikit-learn also integrates with other Python libraries like Pandas for added data manipulation capabilities. Furthermore, a product like SageMaker provides a production platform for operationalizing Scikit-learn models at scale.

This tutorial is just the starting point — Scikit-learn is a versatile toolkit that will continue to serve your modeling needs as you take on more advanced challenges. The key is to continue practicing and honing your skills through hands-on projects. Practical experience with the full modeling lifecycle is the best teacher. With diligence and creativity, Scikit-learn provides the tools to unlock deep insights from all kinds of data.

Matthew Mayo (@mattmayo13) holds a Master's degree in computer science and a graduate diploma in data mining. As Editor-in-Chief of KDnuggets, Matthew aims to make complex data science concepts accessible. His professional interests include natural language processing, machine learning algorithms, and exploring emerging AI. He is driven by a mission to democratize knowledge in the data science community. Matthew has been coding since he was 6 years old.

More On This Topic

  • Getting Started with Scikit-learn for Classification in Machine Learning
  • Getting Started with Python Data Structures in 5 Steps
  • Getting Started with SQL in 5 Steps
  • Simplifying Decision Tree Interpretability with Python & Scikit-learn
  • How to Speed up Scikit-Learn Model Training
  • The Best Machine Learning Frameworks & Extensions for Scikit-learn

Decoding SAP Labs’ Generative AI Motto

At SAP Labs’ recent event, “Unlocking Business AI with SAP Labs India,” in Bengaluru last week, the ERP software giant revealed its ambitious plans for infusing generative AI in business solutions for the humongous client base. Alongside, the company aims to double the AI talent pool by 2024. As the largest R&D center within SAP’s global network, this expansion aims to integrate cutting-edge AI capabilities into its product lineup to address the changing demands of the corporate landscape and its global clientele.

The German tech conglomerate is currently focusing on AI innovation and collaboration, as stated by Sindhu Gangadharan, senior VP and MD of SAP Labs, at the event. They also partner with Microsoft to develop an AI ecosystem for the future. To bridge talent shortages, Sapphire Ventures, supported by SAP, has committed a substantial $1 billion USD investment for startups specializing in AI-powered enterprise technology.

In July, SAP also made strategic investments in three key generative AI companies: Aleph Alpha, Anthropic, and Cohere. Additionally, SAP plans to unveil new AI-based solutions and capabilities in its portfolio in the near future.

SAP is also committed to investing in India. Bengaluru is one of the biggest regions and hosts 40% of the research and development operations. The company intends to significantly increase its financial commitments to their Indian operations. The company is expecting its cloud revenue to increase significantly as a result of its key investments in generative

The event centered around three key themes: addressing the AI talent shortage through upskilling, introducing innovative generative AI solutions for customers, and outlining their ethical approach to AI.

Want to Stay Relevant? Upskill

Gangadharan stressed the importance of upskilling at SAP. While 34% of their workforce comprises fresh talent, including some pursuing master’s degrees at BITS Pilani, the company is also committed to enhancing the skills of mid-senior staff. Currently, they are implementing a 16-month program called “AI for Manager” in collaboration with IIM Bangalore, with the first batch recently completing the course.

“We organize global learning days and training programs to keep up with rapidly changing AI technologies. The focus is on building a strong foundational understanding of technology, problem-solving, and scalability through the training.” Gangadharan told AIM.

New Generative AI Offerings

SAP already has 350+ applications built within its portfolio, covering various use cases like cash management and document scanning. The company is adding a generative AI layer to its Business Technology Platform (BTP) to address data protection concerns and enhance data security. Even though they’re not developing their own large language model, they aim to add value to existing models. SAP’s focus is on improving business processes while ensuring decisions remain under human control.

SAP is introducing generative AI-based solutions in various domains. Back in May, SAP and Microsoft collaborated to streamline recruiting and employee development processes through the Azure OpenAI Service API. The result is their Human Capital Management tool, which uses the ChatGPT-based interface in SAP SuccessFactors to combat biases in job descriptions and promote diversity in hiring.

Additionally, their new Business Analytics tool, built on in-house models, enables faster access to insights in SAP Analytics Cloud through the “Just Ask” feature.

On the other hand, “Gen AI for Customer Innovations” presents applications like the “Smart CO2 Converter” to drive sustainability initiatives. Additionally, SAP’s “Gen AI for Developer Productivity” integrates GPT-4 into SAP BTP Business Application Studio to streamline software development, reducing data model and service generation time by 30% for improved efficiency. These solutions, aiming to empower businesses across different sectors, are going to be launched in November 2023.

Besides Microsoft, the enterprise software vendor also partnered with Google Cloud, aiming to launch a holistic data cloud powered by SAPDatasphere. This innovative solution, enhancing the RISE with SAP offering, empowers businesses to access vital data in real time. It effectively tackles a common hurdle faced by organizations, eliminating the need for extensive investments in intricate data integrations, bespoke analytics systems, and AI/NLP models to extract value from their data investments.

More recently, SAP invested in three major generative AI players: Anthropic, Cohere, and Aleph Alpha, getting the best of all worlds.

“Keeping Responsible AI at the Heart of Our Work”

Acknowledging the impact of AI on society, SAP established guiding principles for AI software development and deployment in 2018. SAP introduced this guidebook at a time when AI was just beginning to take shape.

Underlining the European influence on their approach to responsible data usage, Gangadharan emphasized, “Ethical AI is in our DNA.” Gangadharan elaborated on SAP’s philosophy, encapsulated in the three R’s: Relevant, Reliable, and Responsible.

Firstly, they emphasize the importance of aligning AI with core business processes to ensure its relevance to business requirements. Secondly, they underscore the significance of reliable data as the foundation for informed decision-making, emphasizing the necessity to authenticate data used for AI model training. Last but not least, they prioritize responsible AI, encompassing compliance with legal standards, transparent decision-making, and the establishment of a harmonious human-machine interaction balance.

Read more: Responsible AI Takes Center Stage at Google I/O Connect

The post Decoding SAP Labs’ Generative AI Motto appeared first on Analytics India Magazine.

ChatGPT is Down, I Can’t Code Anymore

ChatGPT is Down, I Can’t Code Anymore

In the fast-paced world of coding and software development, where every second counts, imagine a day without your trusty AI companion ChatGPT by your side. Oh, the horror! But wait, it happened recently. ChatGPT went down, leaving the new “programmers” stranded, and the consequences were felt far and wide.

“ChatGPT is down so I can’t code anymore now,” said someone on X. “Same. Don’t they know I have a product to ship?” bemoaned another developer. Then an actual developer chimed in to take a jab, “Stackoverflow was down so I couldn’t code anymore either.”

The #1 programmer excuse for legitimately slacking off:
ChatGPT is down https://t.co/Sk2FBtUo0R pic.twitter.com/U6WFtGPogT

— Daniel Nguyen (@daniel_nguyenx) September 12, 2023

As a fledgling programmer, understanding code that ChatGPT generates is equally important, and that only a real developer can do. “I’ve literally spent 30 minutes just asking it what does this do, why did you do that, why didn’t you do this and it’s like having a big brother programmer to explain everything,” explained a user on Reddit.

Developers use it to write boilerplate code so they don’t have to remember the exact structure of the thing they are making and then fill in the logic themselves, which is still very educational.

It’s fine to use it as long as it doesn’t become a crutch.

Dumb and AI Dumber

Yet, amid the digital despair, a question arises: Is ChatGPT actually making coders dumber? Firstly, the OG developers that do not rely on ChatGPT, maybe just a little bit on Copilot or Codey, don’t really get affected by it. But the prompt engineering developers are becoming overly reliant on this AI, to the detriment of our own skills and abilities.

Remember the good old days of coding when you had to meticulously type out every line of code, debug it manually, and spend hours scouring documentation? Well, ChatGPT has changed that landscape dramatically. It’s the virtual genie that can conjure lines of code with a few well-crafted prompts.

One coder on Reddit confessed, “I planned and started to learn new tech skills, so I wanted to learn the basics from Udemy and some YouTube courses and start building projects, but suddenly I got stuck and started using ChatGPT. It solved all, then I copied and pasted; it continued like that until I finished the project, and then my mind started questioning. What is the point of me doing this and then stopping learning and coding?”

This is the slippery slope of convenience. We’ve become so accustomed to instant solutions that we’ve forgotten the value of learning through challenges and struggles. But can we really blame ChatGPT for our desire for instant gratification? After all, it’s just a tool, albeit a powerful one.

Some believe that ChatGPT heralds the end of traditional programming jobs. “Seriously. A lot of people really don’t believe this to be true and tell themselves 100 different reasons why some kind of AI isn’t going to take their job or why this is all media hype.” But the truth is the large majority of programming jobs are going to be able to be done almost completely by AI in a matter of years.

Code and AI Coder

The demand for software is insatiable. As one wise coder puts on X, “Things that allow more software to be written generally just cause more/more complex software to be written.” In a world where automation creates new possibilities, we might find ourselves needing even more programmers to oversee and manage these advanced systems.

The vision of a fully automated society where no one needs to work is still far from reality. Self-driving cars, for instance, are not yet ubiquitous, and even when they become so, programmers will still be needed to maintain and improve them.

ChatGPT isn’t an all-powerful wizard set to render programmers obsolete, nor is it an unmitigated boon. It’s a double-edged sword that offers immense convenience while tempting us with the allure of laziness. It is just creating jobs that require coding, without learning how to do it, which honestly is a little concerning.

Controversial take:
GPT-4 is actually making me a really bad developer. I often have too little context on the intricacies of the code it generates and so my code is riddled with bugs and broken

— simp 4 satoshi (@iamgingertrash) September 13, 2023

The wise words, “Never do a job by hand that a machine can do with better quality or faster results,” come to mind. Automation is the hallmark of progress, and tools like ChatGPT exemplifies this principle. It can automate repetitive, time-consuming coding tasks, allowing humans to focus on more complex and creative aspects of programming.

In the end, ChatGPT and similar AI tools are not making us dumber. They’re making us reevaluate how we work and encouraging us to adapt to a changing landscape. And now, they are getting dumber. The danger of becoming less proficient in coding is a choice we make, not an inevitability.

After all, ChatGPT may be down for a day, but our abilities as programmers should never be offline.

The post ChatGPT is Down, I Can’t Code Anymore appeared first on Analytics India Magazine.

Vianai’s New Open-Source Solution Tackles AI’s Hallucination Problem

It's no secret that AI, specifically Large Language Models (LLMs), can occasionally produce inaccurate or even potentially harmful outputs. Dubbed as “AI hallucinations”, these anomalies have been a significant barrier for enterprises contemplating LLM integration due to the inherent risks of financial, reputational, and even legal consequences.

Addressing this pivotal concern, Vianai Systems, a frontrunner in enterprise Human-Centered AI, unveiled its new offering: the veryLLM toolkit. This open-source toolkit is aimed at ensuring more reliable, transparent, and transformative AI systems for business use.

The Challenge of AI Hallucinations

Such hallucinations, which see LLMs generating false or offensive content, have been a persistent problem. Many companies, fearing potential repercussions, have shied away from incorporating LLMs into their central enterprise systems. However, with the introduction of veryLLM, under the Apache 2.0 open-source license, Vianai hopes to build trust and promote AI adoption by providing a solution to these issues.

Unpacking the veryLLM Toolkit

At its core, the veryLLM toolkit allows for a deeper comprehension of each LLM-generated sentence. It achieves this through various functions that categorize statements based on the context pools LLMs are trained on, such as Wikipedia, Common Crawl, and Books3. With the inaugural release of veryLLM heavily relying on a selection of Wikipedia articles, this method ensures a solid grounding for the toolkit's verification procedure.

The toolkit is designed to be adaptive, modular, and compatible with all LLMs, facilitating its use in any application that utilizes LLMs. This will enhance transparency in AI-generated responses and support both current and upcoming language models.

Dr. Vishal Sikka, Founder and CEO of Vianai Systems and also an advisor to Stanford University's Center for Human-Centered Artificial Intelligence, emphasized the gravity of the AI hallucination issue. He said, “AI hallucinations pose serious risks for enterprises, holding back their adoption of AI. As a student of AI for many years, it is also just well-known that we cannot allow these powerful systems to be opaque about the basis of their outputs, and we need to urgently solve this. Our veryLLM library is a small first step to bring transparency and confidence to the outputs of any LLM – transparency that any developer, data scientist or LLM provider can use in their AI applications. We are excited to bring these capabilities, and many other anti-hallucination techniques, to enterprises worldwide, and I believe this is why we are seeing unprecedented adoption of our solutions.”

Incorporating veryLLM in hila™ Enterprise

hila™ Enterprise, another stellar product from Vianai, zeroes in on the accurate and transparent deployment of substantial language enterprise solutions across sectors like finance, contracts, and legal. This platform integrates the veryLLM code, combined with other advanced AI techniques, to minimize AI-associated risks, allowing businesses to fully harness the transformational power of reliable AI systems.

A Closer Look at Vianai Systems

Vianai Systems stands tall as a trailblazer in the realm of Human-Centered AI. The firm boasts a clientele comprising some of the globe's most esteemed businesses. Their team's unparalleled prowess in crafting enterprise platforms and innovative applications sets them apart. They are also fortunate to have the backing of some of the most visionary investors worldwide.