TypeError: zip argument #1 must support iteration is code from nearest mean classifier code for machine learning
I created a program code to simulate a nother program code to understand it
the original code come from machine learning code representing the nearest mean classifier.
This is my simulated code
def method_1():
d = list()
for i in range(3):
for j in range(3):
method_2(sum_func, [i, j])
return "End_of_Code!"
def method_2(fn, x):
x = iter(x)
r = next(x)
for e in x:
r = fn(r, e)
return r
def sum_func(a, b):
return map(sum, zip(a, b))
it shows up this error:
TypeError: zip argument #1 must support iteration
This is the original one it should do the what is being described above
Nearest mean classifier (25 P) We consider one such trainable model, which operates in two steps:
(1) Compute the average point for each class, (2) classify new points to be of the class whose average point is nearest to the point to predict.
For this classifier, we convert the attributes smoker and diet to real values (for smoker: yes=1.0 and no=0.0, and for diet: good=0.0 and poor=1.0), and use the modified distance function:
d(a,b) = (a[0] - b[0]) ** 2 + ((a[1] - b[1]) / 50.0) ** 2 + (a[2] - b[2]) ** 2
We adopt an object-oriented approach for building this classifier.
Implement the methods train and predict of the class NearestMeanClassifier
This is the original code:
# This represent method_2() function
def reduce(fn, iterable):
iterable = iter(iterable)
reduced = next(iterable)
for element in iterable:
reduced = fn(reduced, element)
return reduced
def d_continuous(a, b): return (a[0] - b[0]) ** 2 + ((a[1] - b[1]) / 50.0) ** 2 + (a[2] - b[2]) ** 2
class NearestMeanClassifier:
def _collect_classes(self, dataset):
class_collection = {}
for datum, label in dataset:
try:
class_collection[label].append(datum)
except KeyError:
class_collection[label] = [datum]
return class_collection
#These two functions representing method_1() function:
def _map_collection_mean(self, class_collection):
for label, data in class_collection.items():
class_collection[label] = self._calc_data_mean(data)
return class_collection
def _calc_data_mean(self, data):
total_vector = reduce(self._sum_vectors, data)
return tuple(map(lambda x: x / len(data), total_vector))
# This represents sum_func()
def _sum_vectors(self, a, b):
return map(sum, zip(a, b))
def train(self, dataset):
class_collection = self._collect_classes(dataset)
self.means = self._map_collection_mean(class_collection)
def predict(self, x):
nearest_label = None
smallest_distance = float('inf')
for label, mean in self.means.items():
current_distance = d_continuous(x, mean)
if current_distance < smallest_distance:
smallest_distance = current_distance
nearest_label = label
return nearest_label
Comments
Post a Comment