-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtask 1.py
155 lines (121 loc) · 4.98 KB
/
task 1.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
# py file used for task 1 define din the requirements
#!/usr/bin/env python
# coding: utf-8
# # Logistic regression
# In[10]:
#import required libraries
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, precision_recall_fscore_support
from PIL import Image
import os
# Load and preprocess the dataset
data_path = 'captions.csv'
image_folder = 'Images'
data = pd.read_csv(data_path, names=['description'], header=None)
data = data.iloc[:1000] # Reduce dataset to 1000 items
image_files = sorted(os.listdir(image_folder))[:1000]
def process_image(image_path):
img = Image.open(image_path).convert('L')
img = img.resize((64, 64), Image.ANTIALIAS)
return np.array(img).flatten()
image_features = np.array([process_image(os.path.join(image_folder, img)) for img in image_files])
vectorizer = TfidfVectorizer(max_features=500)
text_features = vectorizer.fit_transform(data['description']).toarray()
features = np.hstack((image_features, text_features))
labels = np.random.randint(0, 2, size=len(data))
# Model training and evaluation
X_train, X_test, y_train, y_test = train_test_split(features, labels, test_size=0.2, random_state=42)
model = LogisticRegression(max_iter=1000)
model.fit(X_train, y_train)
predictions = model.predict(X_test)
accuracy = accuracy_score(y_test, predictions)
precision, recall, f1, _ = precision_recall_fscore_support(y_test, predictions, average='binary')
# Print results
print("Logistic Regression Results:")
print(f"Accuracy: {accuracy:.4f}")
print(f"Precision: {precision:.4f}")
print(f"Recall: {recall:.4f}")
print(f"F1-Score: {f1:.4f}")
# # Support vector machine
# In[12]:
#import required libraries
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score, precision_recall_fscore_support
from PIL import Image
import os
# Load and preprocess the dataset
data_path = 'captions.csv'
image_folder = 'Images'
data = pd.read_csv(data_path, names=['description'], header=None)
data = data.iloc[:1000] # Reduce dataset to 1000 items
image_files = sorted(os.listdir(image_folder))[:1000]
def process_image(image_path):
img = Image.open(image_path).convert('L')
img = img.resize((64, 64), Image.ANTIALIAS)
return np.array(img).flatten()
image_features = np.array([process_image(os.path.join(image_folder, img)) for img in image_files])
vectorizer = TfidfVectorizer(max_features=500)
text_features = vectorizer.fit_transform(data['description']).toarray()
features = np.hstack((image_features, text_features))
labels = np.random.randint(0, 2, size=len(data))
# Model training and evaluation
X_train, X_test, y_train, y_test = train_test_split(features, labels, test_size=0.2, random_state=42)
model = SVC()
model.fit(X_train, y_train)
predictions = model.predict(X_test)
accuracy = accuracy_score(y_test, predictions)
precision, recall, f1, _ = precision_recall_fscore_support(y_test, predictions, average='binary')
# Print results
print("SVM Results:")
print(f"Accuracy: {accuracy:.4f}")
print(f"Precision: {precision:.4f}")
print(f"Recall: {recall:.4f}")
print(f"F1-Score: {f1:.4f}")
# # Decision tree
# In[15]:
#import required libraries
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score, precision_recall_fscore_support
from PIL import Image
import os
# Load and preprocess the dataset
data_path = 'captions.csv'
image_folder = 'Images'
data = pd.read_csv(data_path, names=['description'], header=None)
data = data.iloc[:1000] # Reduce dataset to 1000 items
image_files = sorted(os.listdir(image_folder))[:1000]
def process_image(image_path):
img = Image.open(image_path).convert('L')
img = img.resize((64, 64), Image.ANTIALIAS)
return np.array(img).flatten()
image_features = np.array([process_image(os.path.join(image_folder, img)) for img in image_files])
vectorizer = TfidfVectorizer(max_features=500)
text_features = vectorizer.fit_transform(data['description']).toarray()
features = np.hstack((image_features, text_features))
labels = np.random.randint(0, 2, size=len(data))
# Model training and evaluation
X_train, X_test, y_train, y_test = train_test_split(features, labels, test_size=0.2, random_state=42)
model = DecisionTreeClassifier()
model.fit(X_train, y_train)
predictions = model.predict(X_test)
accuracy = accuracy_score(y_test, predictions)
precision, recall, f1, _ = precision_recall_fscore_support(y_test, predictions, average='binary')
# Print results
print("Decision Tree Results:")
print(f"Accuracy: {accuracy:.4f}")
print(f"Precision: {precision:.4f}")
print(f"Recall: {recall:.4f}")
print(f"F1-Score: {f1:.4f}")
# In[ ]: