Thursday, 23 February 2023

Creating a simple AI program in R programming !

Sure! Here's a simple AI program in R programming that uses a decision tree algorithm to predict whether a person is likely to buy a car based on their age and income.

First, let's create a dataset that contains information about people's age, income, and whether they bought a car or not.

R
# Create dataset age <- c(25, 35, 45, 55, 65, 75) income <- c(20000, 30000, 40000, 50000, 60000, 70000) bought_car <- c(0, 0, 1, 1, 1, 1) df <- data.frame(age, income, bought_car)

Next, let's split the dataset into a training set and a test set.

R
# Split dataset into training and test sets library(caTools) set.seed(123) split <- sample.split(df$bought_car, SplitRatio = 0.7) training_set <- subset(df, split == TRUE) test_set <- subset(df, split == FALSE)

Now, let's train a decision tree model on the training set.

R
# Train decision tree model library(rpart) model <- rpart(bought_car ~ age + income, data = training_set, method = "class")

Finally, let's use the model to make predictions on the test set.

R
# Make predictions on test set predictions <- predict(model, test_set, type = "class")

And that's it! Here's the complete code:

Rde
# Create dataset age <- c(25, 35, 45, 55, 65, 75) income <- c(20000, 30000, 40000, 50000, 60000, 70000) bought_car <- c(0, 0, 1, 1, 1, 1) df <- data.frame(age, income, bought_car) # Split dataset into training and test sets library(caTools) set.seed(123) split <- sample.split(df$bought_car, SplitRatio = 0.7) training_set <- subset(df, split == TRUE) test_set <- subset(df, split == FALSE) # Train decision tree model library(rpart) model <- rpart(bought_car ~ age + income, data = training_set, method = "class") # Make predictions on test set predictions <- predict(model, test_set, type = "class")

No comments:

Post a Comment