def graph(n,angleXaxis = 0,angleEach = 90,originCordinates=(0,0),scale = 1):
    originX , originY = originCordinates[0],originCordinates[1]
    fibOBJ = CorFibonacci()
    X,Y = fibOBJ.cordinateEachAngle(n,originCordinates=(originX,originY),angleXaxis=angleXaxis,angleEach=angleEach,scale=scale)

    plt.grid()
    plt.scatter(DX,DY)
    plt.scatter([originX],[originY])
    plt.plot(X,Y,color = "Purple",label="Fibonacci Walk")

    plt.legend()
    plt.show()    
Exemplo n.º 2
0
    def __init__(self,X,Y,n = 3):
        self.neighborhoods = n
        self.linear_regression = LinearRegression()
        self.fibOBJ = CorFibonacci()
        R = radius(X,Y)
        self.X,self.Y = X,Y
        self.RadiusPoint = R[0]
        self.radiusLength = R[1]
        self.step =self.findFuncStep() 

        self.Xfib,self.Yfib = self.fibOBJ.cordinateEachAngle(self.step,originCordinates=self.RadiusPoint)

        self.DistanceList = self.findNearestDistances(self.X,self.Y,self.Xfib,self.Yfib)
        self.dataPointDict = self.dataPoints(self.DistanceList)

        self.regs = self.regressions()

        self.CircleDict = self.circles(self.dataPointDict)
                radiusPoint, (x, y)
        ):  #Sınır Dışı olması verimisiz olması değildir.Önemli Olan bağlandığı noktadır.
            break
        else:
            step += 1
    return step


iris = load_iris()

data = pd.DataFrame(data=np.c_[iris['data'], iris['target']],
                    columns=iris['feature_names'] + ['target'])
X = data.iloc[:, 2:3].values
Y = data.iloc[:, 3:4].values

obj = CorFibonacci()
R = radius(X, Y)
RadiusPoint = R[0]
RadiusLength = R[1]
print(RadiusPoint)
print(RadiusLength)

#step = findFuncStep(RadiusPoint,RadiusLength)
#print(np.float128(RadiusPoint[0]),np.float128(RadiusPoint[1]))
Xfib, Yfib = obj.cordinateEachAngle(
    10,
    originCordinates=(float(RadiusPoint[0]),
                      float(RadiusPoint[1])))  #originCordinates=RadiusPoint

plt.scatter(RadiusPoint[0], RadiusPoint[1])  #Origin
plt.plot(Xfib, Yfib)
Exemplo n.º 4
0
 def __init__(self,metric = "minkowski",n = 3,p=2):
     self.n = n
     self.metric = metric
     self.p = p
     #self.linear_regression = LinearRegression()
     self.fibOBJ = CorFibonacci()
Exemplo n.º 5
0
class MALR():
    def __init__(self,metric = "minkowski",n = 3,p=2):
        self.n = n
        self.metric = metric
        self.p = p
        #self.linear_regression = LinearRegression()
        self.fibOBJ = CorFibonacci()
        


    def fit(self,X,Y):
        self.X,self.Y = X,Y
        metricObj = metrics(self.X,self.Y)
        R = radius(X,Y)
        self.RadiusPoint = R[0]
        self.RadX,self.RadY = np.float128(self.RadiusPoint[0])[0],np.float128(self.RadiusPoint[1])[0]
        self.RadiusPoint = (self.RadX,self.RadY)
        self.radiusLength = R[1]
        self.step = self.findFuncStep(self.RadiusPoint,self.radiusLength)
        self.Xfib,self.Yfib = self.fibOBJ.cordinateEachAngle(self.step,originCordinates=(float(self.RadiusPoint[0]),float(self.RadiusPoint[1])))
        self.areas = self.Areas(self.X,self.Y,self.Xfib,self.Yfib)
        self.XY_of_CheckPoints = self.get_XY_of_CheckPoints(self.areas)
        self.regressions()

    def findFuncStep(self,radiusPoint,radiusLength):
        step = 2
        while True:
            x,y = self.fibOBJ.cordinateEachAngle(step,originCordinates=radiusPoint)
            x,y = x[-1],y[-1]
            if radiusLength < distance(radiusPoint,(x,y)):#Sınır Dışı olması verimisiz olması değildir.Önemli Olan bağlandığı noktadır.
                break
            else:
                step += 1
        return step
        
    def Areas(self,x_train,y_train,funcX,funcY):###----
        #Burada boyut problemi var.Fibonacci dizisinin n boyutlu uzaydaki konumu
        # yapılmalıdır.Bu problemi çöz.
        #Bu problem sebebiyle veri en fazla iki boyutlu olur
        AreaPoints = dict()
        #Point => (distance,(x_Train,y_Train))
        x_train = np.ravel(x_train)
        y_train = np.ravel(y_train)        
        for data_x,data_y in zip(x_train,y_train):
            distanceToCheckPoint = [(self.get_distance([data_x,data_y],[func_x,func_y]),(data_x,data_y),(func_x,func_y)) for func_x,func_y in zip(funcX,funcY)]#Sıralama için daha optimize bir algoritma kullan
            distanceToCheckPoint = sorted(distanceToCheckPoint,key = lambda tup : tup[0])[0]
            #Burada DistanceToCheckPoint Düzeltilmelidir.
            #Burada Bir problem vardır ...
            #Bu problem kontrol noktasının neye gore kaç eleman alacağıdır.
            
            ################################################################################
            #point iteratörü  sözlüğün anahtarlarında gezer.
            #eğer point şu anki kontrol noktasına eşitse anahtar ile bu bilgileri kontrol
            #noktası altında ykler.ve flag değişkeni 1 olur
            #Fakat eğer bu durum sağlanmazsa flag 0 kalır ve ikinci koşul durumu devreye girer
            #İkinci koşul durumu ise flag yanlızca 0 ise çalışır.ÇAlıştığında ise
            #sözlükte şu anki kontrol noktası anahtar adı altında yeni bir anahtar oluşturur.
            #Ve bu anahtarı listeye eşitler.
            #Daha sonra ise bu anahtar noktası ile edinilen bu iterasyona ait bilgiler 
            #Listeye aktarılır.
            try:
                AreaPoints[distanceToCheckPoint[2]].append((distanceToCheckPoint[0],distanceToCheckPoint[1]))
                
            except KeyError:
                AreaPoints[distanceToCheckPoint[2]] = list()
                AreaPoints[distanceToCheckPoint[2]].append((distanceToCheckPoint[0],distanceToCheckPoint[1]))
            ################################################################################
            #AreaPoints[checkPoint] = (distance,(x_train,y_train))
        
            
            
        
            #Buradan sonra en yakın olan uzaklığı bulup bu
            # en yakın uzaklığı veri noktası alarak 
            # A(x_train,y_train) noktasının veri noktası
            # bulunur.Daha sonra ise predictiondan devam edilir.
            # daha sonra dönmelerin en verimli durumu
            #için WCSS metric'i kullanılır.
            
        return AreaPoints
    
    
            
            
    def get_XY_of_CheckPoints(self,areas):
            CheckPointXYDict= dict()
            for checkpoint in areas:
                X,Y = list(),list()
                for x,y in areas[checkpoint]:
                    
                    X.append(x)
                    Y.append(y)
                   
                X,Y = np.array(X),np.array(Y)
                CheckPointXYDict[checkpoint] = (X,Y)
                
            
            return CheckPointXYDict
        
    def regressions(self):
        self.regression_checkpoint_indexies = dict()
        for index in range(len(self.XY_of_CheckPoints.keys())):
            for checkPoint in self.XY_of_CheckPoints:
                X,Y = self.XY_of_CheckPoints[checkPoint]
                exec("self.linreg{} = LinearRegression()".format(index))
                exec("self.linreg{}.fit(X,Y)".format(index))
                self.regression_checkpoint_indexies[checkPoint] = index
                    
        
    def predict(self,x_test):####---
        neighbors = self.get_neighbors(x_test,self.X,self.Y,n = self.n)
        CheckPoints = self.get_predict_areas(neighbors,self.areas)
        
        y_pred = list()
        for xTest in x_test:
            checkPoint = CheckPoints[xTest]
            #X,Y = self.XY_of_CheckPoints[checkPoint]            
            RegressionIndex = self.regression_checkpoint_indexies[checkPoint]
            exec("prediction = self.linreg{}.predict(xTest)")
            y_pred.append(prediction)
        
        y_pred = np.array(y_pred)
        
        return y_pred
    
    
            
            
            
                        
            
    
    def get_elementCount_of_CheckPoint(self,CheckPoint,areas):
        for key in areas:
            if key == CheckPoint:    
                return len(areas[key])
            
        
        
    def get_predict_areas(self,neighbors,areas):###----###Şimdilik Tamamlandı.DAha şık bir kod haline getir bu fonksiyonu
        nearestPoints = list()
        for x_testData in neighbors:
            subNear = [x_testData]
            for neighs in neighbors[x_testData]:
                nearestDataCordinate = neighs[1]
                subNear.append(nearestDataCordinate)
                
            nearestPoints.append(subNear)
        
        
        checkPointDict =dict()
        
        
        for data in nearestPoints:
            #data[0] = xtestData
            #data[1] = NearestDataCordinate
            checkPointDict[data[0]] = list()
            for check_point in areas:
                for key in areas[check_point]:
                    x_train,y_train = key[1]
                    x_supposed,y_supposed = data[1]
                    if (x_train == x_supposed) and (y_train == y_supposed):
                        checkPointDict[data[0]].append((check_point,(x_train,y_train)))
        
        #dataPoint,CheckPoint
        informationDict =dict()
        
        for x_test_data in checkPointDict:
            connectedCheckPointsDict = dict()
            for check_points in checkPointDict[x_test_data]:
                #Variable explanations
                checkPoint = check_point[0]
                #x_train,y_train = check_point[1]
                
                ##############
                #Bağlantılı noktaların sayılımı
                
                try:
                    connectedCheckPointsDict[checkPoint] += 1
                except KeyError:
                    connectedCheckPointsDict[checkPoint] = 1
                
            print(list(connectedCheckPointsDict.items()))#Bırada bazı problemler var...
            maximum= max(list(connectedCheckPointsDict.items()),lambda tup:tup[1])
            ################################
            #Eğer maximum nokta sayısı eşit olan varsa eleman sayısı  en 
            #fazla olan kontrolnoktası ele alınır
            ################
            counter = [0]
            for key in connectedCheckPointsDict:    
                
                if connectedCheckPointsDict[key] == maximum[1]:
                    counter[0] += 1
                    counter.append(key)
                    
            if counter[0]>1:
                maxCP = [0,None]
                for checkPoint in counter[1:]:
                    elementCount = self.get_elementCount_of_CheckPoint(checkPoint,areas)
                    if maxCP[0] < elementCount:#Burada Daha prestijli ve zekice bir algoritma bulunmalıdır.
                        maxCP[0],maxCP[1] = elementCount,checkPoint
            
                informationDict[x_test_data] =maxCP[1] 
            
            else:
                informationDict[x_test_data] = counter[1]
                
            return informationDict
                
        
            
        
        
        
        
    def get_neighbors(self,x_test,x_train,y_train,n=3):
        ################################################################################
        #neighbors adındaki liste test küme verilerinin anahtar olacağı
        #ve bu test verisine en yakın N kadar komşusunun kordinatları ve bu 
        # noktalara uzaklığı atanır.
        ################################################################################            
        neighborDict = dict()
        for testData in x_test:    
            
            valueList = list()
            for traindatax,traindatay in zip(x_train,y_train):
                value = (self.get_distance(traindatax,testData),(traindatax,traindatay))#Burada get_distance parametrelerinde problem olabilir..
                valueList.append(value)
                
            valueList = sorted(valueList,key = lambda tup : tup[0])[:n]
            neighborDict[testData[0]] = valueList#Burada testData'nın ilk indexi ile hash edilmesi problem olbilir.
        
        return neighborDict
                
            
    def get_distance(self,x,y):
        data = metrics(x,y)
        if self.metric == "euclidean":
            return data.euclideanDistance()
           
        elif self.metric == "manhattan":
            return data.manhattanDistance()
        
        elif self.metric == "minkowski":
            return data.minkowskiDistance()
        
        elif self.metric == "chebyhev":
            return data.chebyhevDistance()
Exemplo n.º 6
0
class MultipleAreaLinearRegression():
    def __init__(self, X, Y, n=3):
        self.neighborhoods = n
        self.linear_regression = LinearRegression()
        self.fibOBJ = CorFibonacci()
        R = radius(X, Y)
        self.X, self.Y = X, Y
        self.RadiusPoint = R[0]
        self.radiusLength = R[1]
        self.step = self.findFuncStep()

        self.Xfib, self.Yfib = self.fibOBJ.cordinateEachAngle(
            self.step, originCordinates=self.RadiusPoint)

        self.DistanceList = self.findNearestDistances(self.X, self.Y,
                                                      self.Xfib, self.Yfib)
        self.dataPointDict = self.dataPoints(self.DistanceList)

        self.regs = self.regressions()

        self.CircleDict = self.circles(self.dataPointDict)

        #self.graph()

    def distance(self, X=(0, 0), Y=(0, 0)):
        distance = ((X[0] - Y[0])**2 + (X[1] - Y[1])**2)**0.5
        return distance

    def circlePoints(self, origin=(0, 0), radius=1):
        YCircle = [
            origin[1] - np.sin(np.deg2rad(i)) * radius for i in range(360)
        ]
        XCircle = [
            origin[0] - np.cos(np.deg2rad(i)) * radius for i in range(360)
        ]

        return (XCircle, YCircle)

    def circles(self, FineDistances):

        circlesList = list()
        for origin in FineDistances:
            radius = max(FineDistances[origin], key=lambda element: element[0])
            circlesList.append((origin, radius[0]))

        return circlesList

    def findFuncStep(self):
        step = 2
        while True:
            x, y = self.fibOBJ.cordinateEachAngle(
                step, originCordinates=self.RadiusPoint)
            x, y = x[-1], y[-1]
            if self.radiusLength < self.distance(
                    self.RadiusPoint, (x, y)
            ):  #Sınır Dışı olması verimisiz olması değildir.Önemli Olan bağlandığı noktadır.
                break
            else:
                step += 1
        return step

    def findNearestDistances(self, Xdata, Ydata, Xfunc, Yfunc):
        Xdata, Ydata, Xfunc, Yfunc = np.ravel(Xdata), np.ravel(
            Ydata), np.ravel(Xfunc), np.ravel(
                Yfunc)  #Daha iyi veri görütüsü için.
        distanceN = list()
        for xd, yd in zip(Xdata, Ydata):
            dist = [(self.distance(X=(xd, yd), Y=(x, y)), (x, y), (xd, yd))
                    for x, y in zip(Xfunc, Yfunc)]
            dist = sorted(dist,
                          key=lambda tup: tup[0])  #İlk indekse göre sıralar.
            dataPoint = dist[0]  #En yakın veri
            distanceN.append(dataPoint)

        return distanceN

    def dataPoints(self, FineDistances):

        dataPointDict = dict()
        for distance, A, D in FineDistances:
            try:
                dataPointDict[A].append((distance, D))

            except KeyError:
                dataPointDict[A] = list()
                dataPointDict[A].append((distance, D))

        return dataPointDict

    def prediction(self, x_test):  #Prediction problemini çöz

        predictionNears = list()
        for x_pred in x_test:  #tahmin edilecek veride
            distances = list()
            for real in self.regs:  #eğitim verisinde sınıflandırılmış sözlük anahtarları
                for x in real["trainPointsX"]:  #eğitim kümesinin x kısmı
                    dist = abs(x - x_pred)
                    distances.append((dist, x))
                distances = sorted(distances,
                                   key=lambda tup: tup[0])[:self.neighborhoods]

                predictionNears.append(
                    (x_pred, distances))  #test veri ile en yakın N noktanın X

        #Test kümesinde en yakın n adet değer bulunur.

        predictions = list()
        for regression in self.regs:
            y_pred = eval("self.linReg{}.predict(x_test)".format(
                regression["prediction"]))
            rmseMetric = eval(
                "self.LinReg{}.rmse_metric(y_test,y_pred)".format(
                    regression["prediction"]))
            predictions.append((regression["origin"], rmseMetric))

    def regressions(self):
        index = 1
        predictionlist = list()
        for key in self.dataPointDict:
            predictionDict = {
                "origin": key,
                "prediction": None,
                "trainPointsX": list(),
                "trainPointsY": list()
            }
            Xparted = [element[1][0] for element in self.dataPointDict[key]]
            Yparted = [element[1][1] for element in self.dataPointDict[key]]
            exec("self.linReg{} = LinearRegression()".format(index))
            exec("self.linReg{}.fit(Xparted,Yparted)".format(index))
            predictionDict['prediction'] = index
            predictionDict['x_points'] = Xparted
            predictionDict['y_points'] = Yparted

            predictionlist.append(predictionDict)

            index += 1

        return predictionlist

    def graph(self):
        plt.grid()
        plt.scatter(X, Y)
        for tup in self.CircleDict:
            circleX, circleY = self.circlePoints(origin=tup[0], radius=tup[1])
            plt.plot(circleX, circleY, color="black")

        plt.plot(self.Xfib, self.Yfib, color="Purple", label="Fibonacci Walk")
        plt.legend()
        plt.show()