Here are some basic code examples for AI-related tasks:
Python Codes
1. Chatbot using NLTK and Tkinter
import nltk
from nltk.stem.lancaster import LancasterStemmer
stemmer = LancasterStemmer()
import tkinter as tk
from tkinter import messagebox
Tokenize and stem input
def tokenize_stem(input_string):
tokens = nltk.word_tokenize(input_string)
stemmed_tokens = [stemmer.stem(token) for token in tokens]
return stemmed_tokens
Chatbot response
def respond(input_string):
# Basic response logic
if "hello" in input_string:
return "Hello! How can I assist you?"
else:
return "I didn't understand that."
Create GUI
root = (link unavailable)()
root.title("Chatbot")
Create input and output fields
input_field = tk.Text(root, height=10, width=40)
output_field = tk.Text(root, height=10, width=40)
Create send button
def send_message():
input_string = input_field.get("1.0", tk.END)
tokens = tokenize_stem(input_string)
response = respond(input_string)
output_field.insert(tk.END, response + "\n")
send_button = tk.Button(root, text="Send", command=send_message)
Layout GUI
input_field.pack()
send_button.pack()
output_field.pack()
root.mainloop()
2. Simple Neural Network using Keras
from keras.models import Sequential
from keras.layers import Dense
import numpy as np
Create dataset
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
y = np.array([[0], [1], [1], [0]])
Create neural network model
model = Sequential()
model.add(Dense(2, input_dim=2, activation='relu'))
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
Train model
model.fit(X, y, epochs=1000, verbose=0)
Make predictions
predictions = model.predict(X)
print(predictions)
3. Basic Machine Learning using Scikit-learn
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
Load iris dataset
iris = load_iris()
X = iris.data
y = iris.target
Split dataset into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
Create logistic regression model
model = LogisticRegression()
Train model
model.fit(X_train, y_train)
Make predictions
predictions = model.predict(X_test)
print("Accuracy:", accuracy_score(y_test, predictions))
Java Codes
1. Simple AI using Java
import java.util.Scanner;
public class SimpleAI {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter your name:");
String name = scanner.nextLine();
System.out.println("Hello, " + name + "!");
}
}
2. Java Neural Network using Deeplearning4j
import org.deeplearning4j.nn.conf.MultiLayerConfiguration;
import org.deeplearning4j.nn.conf.NeuralNetConfiguration;
import org.deeplearning4j.nn.multilayer.MultiLayerNetwork;
import org.nd4j.linalg.factory.Nd4j;
public class JavaNeuralNetwork {
public static void main(String[] args) {
MultiLayerConfiguration conf = new NeuralNetConfiguration.Builder()
.seed(123)
.list()
.layer(0, new DenseLayer.Builder().nIn(784).nOut(250).activation("relu").build())
.layer(1, new OutputLayer.Builder().nIn(250).nOut(10).activation("softmax").build())
.pretrain(false).backprop(true).build();
MultiLayerNetwork model = new MultiLayerNetwork(conf);
model.init();
}
}
C++ Codes
1. Simple AI using C++
#include <iostream>
#include <string>
int main() {
std::string name;
std::cout << "Enter your name: ";
std::cin >> name;
std::cout << "Hello, " << name << "!";
return 0;
}
2. C++ Neural Network using Caffe
#include <caffe/caffe.hpp>
int main() {
caffe::NetParameter net_param;
net_param.AddLayer()->set_type(caffe::LayerParameter_LayerTypeINNER_PRODUCT);
caffe::Net<float