0% found this document useful (0 votes)
11 views6 pages

Python Machine Learning Programs

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views6 pages

Python Machine Learning Programs

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

SHREE MEDHA DEGREE COLLEGE, BALLARI

6. Python program to demonstrate the supervised machine


learning.

# Import required libraries


import numpy as np
from sklearn.linear_model import LinearRegression
X = [Link]([[1, 2], [2, 3], [3, 4], [4, 5]])
Y = [Link](X, [Link]([3, 2])) + 7
# Create a linear regression model
model = LinearRegression()
# Train the model using the input data and output labels
[Link](X, Y)
# Now, let's predict the output for new input data
new_input = [Link]([[5, 6]])
predicted_output = [Link](new_input)
print(f"Predicted output for new input: {predicted_output[0]}")

OUTPUT :

Predicted output for new input: 34.0

DEPT. OF COMPUTER SCIENCE Page | 1


SHREE MEDHA DEGREE COLLEGE, BALLARI

7. Python program to predict the price of the car using decision


tree.
from [Link] import DecisionTreeRegressor
from sklearn.model_selection import train_test_split
import numpy as np
# Sample car data (replace with your actual data)
data = {
'mileage': [20000, 40000, 15000, 35000],
'year': [2018, 2015, 2020, 2017],
'model': ["Acura", "Toyota", "BMW", "Honda"],
'price': [25000, 18000, 30000, 22000]
}
# Convert data to NumPy arrays
features = [Link]([data['mileage'], data['year']]).T
labels = [Link](data['price'])
# Split data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(features, labels,
test_size=0.2, random_state=42)
# Create and train the decision tree model
model = DecisionTreeRegressor()
[Link](X_train, y_train)
# Predict price for a new car (replace with values)
new_car = [50000, 2012]
# Make prediction
predicted_price = [Link]([new_car])[0]
# Print result
print(f"Predicted price for new car: ${round(predicted_price, 2)}")

OUTPUT :
Predicted price for new car: $22000.0

DEPT. OF COMPUTER SCIENCE Page | 2


SHREE MEDHA DEGREE COLLEGE, BALLARI

8. Python program of weather prediction model that predicts


whether or not there’ll be rain on a particular day.

from [Link] import DecisionTreeClassifier


# Sample weather data (replace with real data collection)
data = [
[10, 70, False], # Sunny, High Pressure, No Rain
[15, 60, True], # Cloudy, Medium Pressure, Rain
[5, 90, False], # Foggy, High Pressure, No Rain
[20, 50, True], # Rainy, Low Pressure, Rain
]
# Features (predictors)
features = ["Temperature", "Pressure", "Cloudy"]
target = ["Rain"]
# Transform data into numerical features (replace with actual data processing)
X = [[d[0], d[1]] for d in data]
y = [d[2] for d in data]
# Train the decision tree model
model = DecisionTreeClassifier()
[Link](X, y)
# Predict rain for a new day (replace with actual values)
new_day = [18, 65]
# Make prediction
prediction = [Link]([new_day])[0]
# Print result
rain_text = "Rain" if prediction else "No Rain"
print(f"Prediction for new day: {rain_text}")

OUTPUT :

Prediction for new day: Rain

DEPT. OF COMPUTER SCIENCE Page | 3


SHREE MEDHA DEGREE COLLEGE, BALLARI

9. Python program to classify the emails as spam or not spam.

from sklearn.naive_bayes import MultinomialNB


from sklearn.feature_extraction.text import CountVectorizer
# Sample email data (replace with your data loading)
emails = ["This is a normal email", "Click this link to win a prize!",
"Important update from your bank"]
labels = ["not spam", "spam", "not spam"]
# Feature extraction (convert text to numerical features)
vectorizer = CountVectorizer()
features = vectorizer.fit_transform(emails)
# Train the Naive Bayes model
model = MultinomialNB()
[Link](features, labels)
# Classify a new email
new_email = "Free money just for you!"
new_features = [Link]([new_email])
prediction = [Link](new_features)[0]
# Print the prediction
print(f"New email is classified as: {prediction}")

OUTPUT :

New email is classified as: not spam

DEPT. OF COMPUTER SCIENCE Page | 4


SHREE MEDHA DEGREE COLLEGE, BALLARI

11. Python program that demonstrates text classification using


scikit-learn and a Naive Bayes classifier.

from sklearn.naive_bayes import MultinomialNB


from sklearn.feature_extraction.text import TfidfVectorizer
# Sample text data (replace with your data)
documents = ["This movie was absolutely amazing!",
"The restaurant food was very disappointing.",
"I would recommend this book to everyone."]
labels = ["positive", "negative", "positive"]
# Feature extraction with TF-IDF
vectorizer = TfidfVectorizer()
features = vectorizer.fit_transform(documents)
# Train the Naive Bayes model
model = MultinomialNB()
[Link](features, labels)
# Classify a new piece of text
new_text = "This product is terrible."
new_features = [Link]([new_text])
prediction = [Link](new_features)[0]
# Print the prediction
print(f"New text classified as: {prediction}")

OUTPUT :

New text classified as: positive

DEPT. OF COMPUTER SCIENCE Page | 5


SHREE MEDHA DEGREE COLLEGE, BALLARI

12. Python program using the PIL (Pillow) library to illustrate


basic image processing operations like opening an image,
resizing it, applying a filter, and saving the processed image.
From PIL import Image, ImageFilter
# Open an image
image_path = “your_image.jpg”
original_image = [Link](image_path)
# Resize the image
new_size = (300, 200) # Specify the new width and height
resized_image = original_image.resize(new_size)
# Apply a filter (e.g., Gaussian blur)
blurred_image = resized_image.filter([Link](radius=5))
# Save the processed image
output_path = “processed_image.jpg”
blurred_image.save(output_path)
print(“Image processing complete. Saved as”, output_path)

OUTPUT:

Image processing complete. Saved as processed_image

Your Image Processing Image

DEPT. OF COMPUTER SCIENCE Page | 6

Common questions

Powered by AI

The Decision Tree Classifier structure for binary classification, such as predicting rain likelihood, focuses on segmenting data based on distinct feature criteria leading to 'yes/no' outcomes ('Rain' or 'No Rain'). It assesses predictor contributions toward classification outcomes. Conversely, in regression tasks like car price prediction, the Decision Tree Regressor operates to fit continuous response variables, attempting to minimize variance within discrete partitions for precise value estimation, demonstrating its flexibility in handling continuous outcomes over pure categorical results.

A Decision Tree Regressor can be used by first converting the car data into NumPy arrays for features such as mileage and year, and labels like price. Using train_test_split from sklearn, split the data into training and testing sets to prevent overfitting and generalize model performance. Fit the Decision Tree Regressor with training data using model.fit(X_train, y_train). For predictions, use model.predict() with new data such as mileage and year, which illustrates the regression output, in this case, a predicted car price.

To create and utilize a linear regression model using Python's Scikit-learn, first import the necessary libraries like numpy and LinearRegression from sklearn.linear_model. Next, prepare your input and output data arrays, as shown in X and Y. Initialize the LinearRegression model and fit it using the model.fit(X, Y) method. You can then predict outcomes for new data inputs using model.predict(new_input), as demonstrated where new_input is an array of new data.

Using a Naive Bayes classifier for sentiment analysis involves several considerations. This includes ensuring that sentiment-laden terms in text data are effectively captured, which is achieved by constructing robust word representations through TF-IDF vectorization. Challenges may arise in handling context nuances, sarcasm, or imbalanced data leading to potential classification biases. The model's assumption of feature independence might overlook interdependencies between sentiment words, influencing the identification of positive or negative sentiments, often requiring post-processing or advanced models to handle omnipresent semantics accurately.

Data features for weather prediction include temperature and pressure, extracted from the dataset to serve as inputs (X). The classification target, whether it rains or not, is labeled as y. The DecisionTreeClassifier from sklearn is then trained with these features using model.fit(X, y). For predicting new instances, such as a day's temperature and pressure, the model predicts if rain will occur using model.predict(), showcasing the application of the model to derive conclusions from specific environmental conditions.

Decision tree algorithms are highly interpretable as they visually map input feature splits leading to particular outputs, enhancing understanding of feature contributions toward predictions, such as rain forecasting. Unlike black-box models like deep learning, decision trees offer clear pathways of reasoning, identifying significant conditions (e.g., pressure thresholds) directly influencing outcomes (rain). Their straightforward splits help stakeholders interpret decision logic, aiding transparent insight into machine-based reasoning without abstruse computations, reaffirming their value in applications necessitating explainability for responsible decision-making.

Implementing an image processing pipeline using Python's PIL involves opening an image using Image.open and performing operations like resizing with the resize method, which resizes the image to specified dimensions to possibly reduce file size or meet specific display requirements. Applying filters such as Gaussian blur through ImageFilter.GaussianBlur adds effects by manipulating pixel values to alter appearance, enabling applications in feature extraction or downplaying unnecessary details. The processed image is saved with Image.save, finalizing changes while the implications affect both aesthetic and analytical uses, illustrating pre-processing significance in computer vision tasks.

A Linear Regression Model's outcome hinges on data quality, model parameters like coefficients derived during training, and how well the initial assumptions align with data characteristics (linearity). Factors include the model's capacity to generalize correlations observed between predictors and response in training data to unseen inputs (new data). Its effectiveness is influenced by data representation accuracy, outlier robustness, and variance-bias trade-off. Precise forecasts rely on alignment of model projections with inherent data patterns, highlighting the essential synchronization needed in data and model dynamics for robust predictions.

TF-IDF vectorization, unlike CountVectorizer, weighs the terms based on their frequency in the document relative to the entire corpus size, emphasizing lesser common terms if they convey more distinctive meaning yet occur infrequently, thus prioritizing crucial semantic information. CountVectorizer only represents raw frequency, which might overshadow term significance in diverse corpuses. TF-IDF is often preferred in large datasets where semantic accuracy is required, as it mitigates the effect of common words' dominance, offering nuanced text representations suitable for precise text classification objectives.

Spam detection using the Naive Bayes classifier involves converting text into numerical features with CountVectorizer. This vectorization converts a text corpus into a matrix showcasing word frequency, enabling pattern recognition by the MultinomialNB model from sklearn. The classifier is trained with vectorized email data and spam/non-spam labels. Upon receiving new text, the model predicts its class by analyzing the vectorized structure, allowing sophisticated spam detection based on learnings from the word distribution and occurrence patterns.

You might also like