20 Python Codes for Small AI Projects

 


As we’ve always done in our “Gifts” section, where we offer free codes and complete projects – yes, completely free! These projects or codes usually cost money elsewhere, just to get a single project. But here, in our “Gifts” section, we give you a bunch of codes or projects every day for free. So the least you can do to support us is share it with your friends.



1. Simple Chatbot

import random
responses = ["Hi there!", "How can I help you?", "Goodbye!"]
while True:
user = input("You: ")
if user.lower() == "bye":
print("Bot: Goodbye!")
break
print("Bot:", random.choice(responses))

Explanation: A basic chatbot that replies with random responses.


2. Sentiment Analysis

from textblob import TextBlob
text = input("Enter a sentence: ")
blob = TextBlob(text)
print("Sentiment score:", blob.sentiment.polarity)

Explanation: Uses TextBlob to detect if text is positive or negative.


3. Predicting Values (Linear Regression)

from sklearn.linear_model import LinearRegression
X = [[1],[2],[3],[4],[5]]
y = [2,4,6,8,10]
model = LinearRegression().fit(X, y)
print(model.predict([[6]]))

Explanation: A simple linear regression model predicting future values.


4. AI Password Generator

import random, string
password = ''.join(random.choices(string.ascii_letters + string.digits, k=12))
print(password)

Explanation: Generates a strong random password.


5. Display Handwritten Digits (MNIST)

from tensorflow.keras.datasets import mnist
import matplotlib.pyplot as plt
(x_train, _), _ = mnist.load_data()
plt.imshow(x_train[0], cmap='gray')
plt.show()

Explanation: Loads MNIST dataset and shows a digit image.


6. Spam Email Detection

from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
emails = ["Win a prize now!", "Meeting at 5pm", "Claim your free gift"]
labels = [1, 0, 1]
cv = CountVectorizer()
X = cv.fit_transform(emails)
model = MultinomialNB().fit(X, labels)
print(model.predict(cv.transform(["Free prize just for you"])))

Explanation: Classifies if an email is spam or not.


7. Movie Recommendation

movies = {
"Action": ["Mad Max", "Die Hard"],
"Comedy": ["The Mask", "Step Brothers"]
}
genre = input("Choose Action/Comedy: ")
print("Recommended:", movies.get(genre, "Not found"))

Explanation: Simple movie recommendation based on user input.


8. Random Text Generator

import random
text = "AI is great. AI is the future. AI changes the world."
words = text.split()
for i in range(10):
print(random.choice(words), end=" ")

Explanation: Generates random sentences using given text.


9. Face Detection

import cv2
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
img = cv2.imread("face.jpg")
faces = face_cascade.detectMultiScale(img, 1.1, 4)
print("Faces found:", len(faces))

Explanation: Detects faces in an image using OpenCV.


10. Speech to Text

import speech_recognition as sr
r = sr.Recognizer()
with sr.Microphone() as source:
print("Speak:")
audio = r.listen(source)
print(r.recognize_google(audio))

Explanation: Converts spoken words into text.


11. Simple AI Image Creation

from PIL import Image, ImageDraw
img = Image.new('RGB', (200, 200), color='white')
d = ImageDraw.Draw(img)
d.text((50, 90), "AI!", fill='black')
img.show()

Explanation: Creates and displays an image with text.


12. Student Score Prediction

import numpy as np
from sklearn.linear_model import LinearRegression
hours = np.array([1,2,3,4,5]).reshape(-1,1)
scores = np.array([20,40,60,80,100])
model = LinearRegression().fit(hours, scores)
print("Predicted score for 6 hours:", model.predict([[6]]))

Explanation: Predicts student grades based on study hours.


13. Convert Image to Grayscale

import cv2
img = cv2.imread("image.jpg", cv2.IMREAD_GRAYSCALE)
cv2.imwrite("compressed.jpg", img)

Explanation: Converts a colored image to black-and-white.


14. Object Detection Setup

import cv2
net = cv2.dnn.readNetFromCaffe("deploy.prototxt","res10_300x300_ssd_iter_140000.caffemodel")
image = cv2.imread("face.jpg")
(h, w) = image.shape[:2]
print("Image ready for object detection!")

Explanation: Loads a pre-trained object detection model.


15. Weather Prediction via API

import requests
city = "New York"
url = f"http://api.weatherapi.com/v1/current.json?key=YOUR_KEY&q={city}"
data = requests.get(url).json()
print(data["current"]["temp_c"], "°C")

Explanation: Fetches real-time weather data from an API.


16. Pre-Trained Image Classifier

from tensorflow.keras.applications import MobileNetV2
model = MobileNetV2(weights='imagenet')
print("Model loaded!")

Explanation: Loads a pre-trained deep learning model.


17. AI Guessing Game

import random
num = random.randint(1, 10)
guess = int(input("Guess 1-10: "))
print("Correct!" if guess == num else f"Nope, it was {num}")

Explanation: Simple number guessing game with randomness.


18. Text Summarizer

from gensim.summarization import summarize
text = """Artificial Intelligence is transforming the world in many ways..."""
print(summarize(text, ratio=0.5))

Explanation: Summarizes long text into short summaries.


19. Sales Data Analysis

import pandas as pd
data = {"Month": ["Jan","Feb","Mar"], "Sales":[200,300,400]}
df = pd.DataFrame(data)
print(df.describe())

Explanation: Analyzes sales data using Pandas.


20. Text to Speech

import pyttsx3
engine = pyttsx3.init()
engine.say("Hello, AI world!")
engine.runAndWait()

Explanation: Converts text into speech output.

Post a Comment

0 Comments