def fit(self, k, X_train, y_train):
        n, m = X_train.shape
        self.fcm = FCM(n_clusters=k)
        fcm = self.fcm.fit(X_train)
        V = fcm.centers
        U = fcm.u
        self.G = np.ndarray(shape=(n, k))
        self.C = np.zeros(shape=(k, m, m))
        for i in range(k):
            sm = 0
            for j in range(n):
                diff = np.array(X_train[j] - V[i]).reshape(-1, 1)
                self.C[i] += (U[j, i]**m) * diff * (diff.transpose())
                sm += U[j, i]**m
            self.C[i] /= sm
        self.C = np.array([np.linalg.inv(c) for c in self.C])

        for i in range(k):
            for j in range(n):
                diff = np.array(X_train[j] - V[i]).reshape(-1, 1)
                self.G[j, i] = np.exp(
                    -self.gamma * (diff.transpose().dot(self.C[i])).dot(diff))

        ohe = OneHotEncoder(sparse=False)
        Y = ohe.fit_transform(y_train)
        self.W = np.linalg.inv(self.G.T.dot(self.G)).dot(self.G.T).dot(Y)
        return self
Esempio n. 2
0
 def __init__(self, config, log):
     Sender.__init__(self, config, log)
     self.base_deeplink_url = config.get('Messenger', 'base_deeplink_url')
     app = generate_fcm_app(
         config.get('Messenger', 'google_application_credentials'))
     self.FCM = FCM(app)
     self.canonical_ids = []
     self.unregistered_devices = []
Esempio n. 3
0
def fzclustering(users_skills, n_clusters_range, fuzzpar, plot=False):
    X = users_skills
    n_clusters_range = list(n_clusters_range)

    fzmodels = {}
    times = []
    fpcs = []

    # Find the best number of clusters
    for n_clusters_ in n_clusters_range:
        # another library
        start = time.time()
        fuzzy_fcm = FCM(n_clusters=n_clusters_,
                        max_iter=50,
                        m=fuzzpar,
                        error=1e-5,
                        random_state=37)
        fuzzy_fcm.fit(X)
        end = time.time()
        times.append(end - start)

        #print("Number of fuzzy clusters " + str(n_clusters_) + ' duration: ' + str((end - start)))

        fcm_centers = fuzzy_fcm.centers
        fcm_labels = fuzzy_fcm.predict(X)

        fuzzy_clustering_coeff = fuzzy_fcm.partition_coefficient
        pec = fuzzy_fcm.partition_entropy_coefficient

        fpcs.append(fuzzy_clustering_coeff)

        fzmodels[
            n_clusters_] = fcm_centers, fcm_labels, fuzzy_clustering_coeff, fuzzy_fcm

    best_centers = max(fzmodels.values(), key=lambda x: x[2])

    if plot:
        plt.figure()
        plt.title(f"Fuzzy c-means over number of clusters")
        plt.xlabel("Number of clusters")
        plt.xticks(n_clusters_range)
        plt.ylabel("Fuzzy partition coefficient")
        plt.plot(n_clusters_range, fpcs)
        plt.tight_layout()
        plt.savefig(f"clustering_Fuzzy_1.png")
        plt.close()

    return best_centers, times
def fzclustering(users_skills, n_clusters_range, plot=False):
    X = users_skills
    n_clusters_range = list(n_clusters_range)

    fzmodels_2 = {}

    fpcs_2 = []

    # Find the best number of clusters
    for n_clusters_ in n_clusters_range:
        # another library
        fuzzy_fcm = FCM(n_clusters=n_clusters_, max_iter=50, m=1.2, error=1e-5, random_state=88)
        fuzzy_fcm.fit(X)

        fcm_centers = fuzzy_fcm.centers
        fcm_labels = fuzzy_fcm.predict(X)

        fuzzy_clustering_coeff = fuzzy_fcm.partition_coefficient
        pec = fuzzy_fcm.partition_entropy_coefficient

        fpcs_2.append(fuzzy_clustering_coeff)

        fzmodels_2[n_clusters_] = fcm_centers, fcm_labels, fuzzy_clustering_coeff

    best_centers_2 = max(fzmodels_2.values(), key=lambda x: x[2])

    if plot:
        plt.figure()
        plt.title(f"Fuzzy c-means over number of clusters")
        plt.xlabel("Number of clusters")
        plt.xticks(n_clusters_range)
        plt.ylabel("Fuzzy partition coefficient (FPC)")
        plt.plot(n_clusters_range, fpcs_2)
        plt.tight_layout()
        plt.savefig(f"Fuzzy partition coefficient")
        plt.close()

    return best_centers_2
Esempio n. 5
0
def fcm_trials(k, m=1.2, rtrials=5):
    models = [FCM(k, m, data) for _ in range(rtrials)]
    training_err = [model.train(data) for model in models]
    results = [(err[-1], model) for err, model in zip(training_err, models)]
    results = sorted(results, key=lambda x: x[0])

    # Plot results for each FCM trial
    for i, trial in enumerate(results):
        final_err = round(trial[0], 2)
        model = trial[1]
        plt.title(f'Trial {i+1} FCM Cluster Assignments (SSE={final_err})')
        plotKClusters(model, k, data)
        plt.show()

    # Select and show bes model from r trials
    lowest_sse = round(results[0][0], 2)
    best_model = results[0][1]
    plt.title(f'Best FCM model (SSE={lowest_sse})')
    plotKClusters(best_model, k, data)
    plt.show()
class RBF:
    def __init__(self, gamma=0.1):
        self.gamma = gamma
        self.G = None
        self.C = None
        self.W = None
        self.fcm = None

    def fit(self, k, X_train, y_train):
        n, m = X_train.shape
        self.fcm = FCM(n_clusters=k)
        fcm = self.fcm.fit(X_train)
        V = fcm.centers
        U = fcm.u
        self.G = np.ndarray(shape=(n, k))
        self.C = np.zeros(shape=(k, m, m))
        for i in range(k):
            sm = 0
            for j in range(n):
                diff = np.array(X_train[j] - V[i]).reshape(-1, 1)
                self.C[i] += (U[j, i]**m) * diff * (diff.transpose())
                sm += U[j, i]**m
            self.C[i] /= sm
        self.C = np.array([np.linalg.inv(c) for c in self.C])

        for i in range(k):
            for j in range(n):
                diff = np.array(X_train[j] - V[i]).reshape(-1, 1)
                self.G[j, i] = np.exp(
                    -self.gamma * (diff.transpose().dot(self.C[i])).dot(diff))

        ohe = OneHotEncoder(sparse=False)
        Y = ohe.fit_transform(y_train)
        self.W = np.linalg.inv(self.G.T.dot(self.G)).dot(self.G.T).dot(Y)
        return self

    def predict(self, X_test):
        n, m = X_test.shape
        V = self.fcm.centers
        U = self.fcm.predict(X_test)
        k = self.fcm.n_clusters
        G = np.ndarray(shape=(n, k))
        C = np.zeros(shape=(k, m, m))
        for i in range(k):
            sm = 0
            for j in range(n):
                diff = np.array(X_test[j] - V[i])
                C[i] += (U[j, i]**m) * diff * (diff.transpose())
                sm += U[j, i]**m
            C[i] /= sm
        C = np.array([np.linalg.pinv(c) for c in C])
        for i in range(k):
            for j in range(n):
                diff = np.array(X_test[j] - V[i])
                G[j, i] = np.exp(-self.gamma *
                                 (diff.transpose().dot(C[i])).dot(diff))

        y_pred = np.argmax(G.dot(self.W), axis=1)
        return y_pred

    def get_accuracy(self, y_test, y_pred):
        return np.mean(np.equal(y_test.flatten(), y_pred.flatten()))
#!/usr/bin/env python

from fcm import FCM

# Topic Messaging

API_KEY = "your api key"

fcm = FCM(API_KEY)
data = {'param1': 'value1', 'param2': 'value2'}
condition = "'TopicA' in topics && ('TopicB' in topics || 'TopicC' in topics)"

response = fcm.send_topic_message(condition=condition, data=data)

print(response)
Esempio n. 8
0
#!/usr/bin/env python

from fcm import FCM

# JSON request

API_KEY = "your api key"

fcm = FCM(API_KEY)

registration_ids = ["your token 1", "your token 2"]

notification = {
    "title": "Awesome App Update",
    "body": "body",
}

response = fcm.json_request(
    registration_ids=registration_ids,
    notification=notification,
    # collapse_key='awesomeapp_update',
    # restricted_package_name="com.google.firebase.quickstart.fcm",
    priority='high',
    delay_while_idle=False)

# Successfully handled registration_ids
if response and 'success' in response:
    for reg_id, success_id in response['success'].items():
        print('Successfully sent notification for reg_id {0}'.format(reg_id))

# Handling errors
Esempio n. 9
0
import requests
import pywaves

from app_core import app, db, socketio, SERVER_MODE_WAVES, SERVER_MODE_PAYDB
from models import Role, User, WavesTx, Proposal, Payment, Topic, PushNotificationLocation
import utils
from fcm import FCM
from web_utils import bad_request, get_json_params, get_json_params_optional
import paydb_core
from reward_endpoint import reward, reward_create
# pylint: disable=unused-import
import admin

#jsonrpc = JSONRPC(app, "/api")
logger = logging.getLogger(__name__)
fcm = FCM(app.config["FIREBASE_CREDENTIALS"])

SERVER_MODE = app.config["SERVER_MODE"]
DEEP_LINK_SCHEME = app.config["DEEP_LINK_SCHEME"]
if SERVER_MODE == SERVER_MODE_WAVES:
    import tx_utils
    # our pywaves address object
    PW_ADDRESS = None
    # wave specific config settings
    NODE_BASE_URL = app.config["NODE_BASE_URL"]
    SEED = app.config["WALLET_SEED"]
    ADDRESS = app.config["WALLET_ADDRESS"]
    ASSET_ID = app.config["ASSET_ID"]
    TESTNET = app.config["TESTNET"]
    # master wallet blueprint
    from mw_endpoint import mw
Esempio n. 10
0
#!/usr/bin/env python3

from fcm import FCM

# Plain text request

API_KEY = "your api key"

fcm = FCM(API_KEY, debug=True)

registration_id = 'your push token'

data = {'param1': 'value1', 'param2': 'value2'}

response = fcm.plaintext_request(registration_id=registration_id, data=data)

print(response)
Esempio n. 11
0
#!/usr/bin/env python

from fcm import FCM

# Topic Messaging

API_KEY = "your api key"

fcm = FCM(API_KEY)
data = {'param1': 'value1', 'param2': 'value2'}
topic = 'your topic name'

response = fcm.send_topic_message(topic=topic, data=data)

print(response)
Esempio n. 12
0
class FCMPushSender(Sender):
    """
    FCM Push Sender uses python-FCM module: https://github.com/geeknam/python-FCM
    FCM documentation: https://developer.android.com/google/FCM/FCM.html
    """
    def __init__(self, config, log):
        Sender.__init__(self, config, log)
        self.base_deeplink_url = config.get('Messenger', 'base_deeplink_url')
        app = generate_fcm_app(
            config.get('Messenger', 'google_application_credentials'))
        self.FCM = FCM(app)
        self.canonical_ids = []
        self.unregistered_devices = []

    def pop_canonical_ids(self):
        items = self.canonical_ids
        self.canonical_ids = []
        return items

    def pop_unregistered_devices(self):
        items = self.unregistered_devices
        self.unregistered_devices = []
        return items

    def create_message(self, notification):
        expiry_seconds = (notification['time_to_live_ts_bigint'] -
                          int(round(time.time() * 1000))) / 1000
        if expiry_seconds < 0:
            self.log.warning(
                'FCM: expired notification with sending_id: {0}; expiry_seconds: {1}'
                .format(notification['sending_id'], expiry_seconds))
            notification['status'] = const.NOTIFICATION_EXPIRED
            return

        utm_source = 'pushnotification'
        utm_campaign = str(notification['campaign_id'])
        utm_medium = str(notification['message_id'])
        data = {
            'title':
            notification['title'],
            'message':
            notification['content'],
            'url':
            self.base_deeplink_url + '://' + notification['screen'] +
            '?utm_source=' + utm_source + '&utm_campaign=' + utm_campaign +
            '&utm_medium=' + utm_medium,
            'notifid':
            notification['campaign_id'],
        }
        msg = messaging.Message(
            data=data,
            token=notification['receiver_id'],
        )
        return msg

    def send(self, notification):
        dry_run = 'dry_run' in notification and notification['dry_run'] == True
        message = self.create_message(notification)
        response = self.FCM.send(message, dry_run)

        return response

    def send_batch(self):
        messages = []
        while len(self.queue):
            messages.append(self.create_message(self.queue.pop()))
        return self.FCM.send_batch(messages)
Esempio n. 13
0
import matplotlib.pyplot as plt
from fcm import FCM
import cv2
import numpy as np

if __name__ == "__main__":
    img = cv2.imread("colored_image.png", 1)
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    z = img.reshape(-1, 3)
    z = np.float32(z)
    #a= z.reshape(229,459,3)
    x = input("enter number of clusters: ")
    fcm = FCM(z, x, 100)  #create the fcm model
    fcm.initializeCenters()  #initialize the centers of clusters
    current = 0
    while ((current < fcm.max_iter) and (not fcm.membershipConvergence())
           ):  #while the membership values not converging
        print(current)
        fcm.updateMembershipDegrees()
        fcm.updateCenters()
        current += 1
    output1 = fcm.segmentImage()
    output1 = np.array(output1)
    output1 = output1.reshape(229, 459, 3)
    output1 = np.uint8(output1)
    output = [img, output1]
    titles = ["original", str(x) + " clusters segmentation"]
    for i in range(2):
        plt.subplot(2, 2, i + 1)
        plt.imshow(output[i])
        plt.title(titles[i])
Esempio n. 14
0
 def send_notification(self, news):
     status_code = FCM(news).send_notification()
     print("Sent notification: " + str(status_code))
Esempio n. 15
0
if __name__ == "__main__":
    data = []
    with open("Mall_Customers.csv",
              "r") as dataFile:  #dataset of mall_customers
        for line in dataFile:
            row = line.split(",")
            row[-1] = row[-1][:-2]
            data.append(row)
            line = dataFile.readline
    features = data[0][2:]
    #for row in data:  #uncomment this to see raw dataset
    #    print(row)
    data = prepareData(data)
    x = input("enter number of clusters: "
              )  #this dataset can be effectively devided only into 2 clusters
    fcm = FCM(data, x, 100)  #create the fcm model
    fcm.initializeCenters()  #initialize the centers of clusters
    current = 0
    while ((current < fcm.max_iter) and (not fcm.membershipConvergence())
           ):  #while the membership values not converging
        fcm.updateMembershipDegrees()
        fcm.updateCenters()
        current += 1
        """temporaryClusters=fcm.makeClusters()
        for item in temporaryClusters:
            if len(item)==0:
                maxrand=len(data)
                randomIndex=random.randint(10,maxrand)-11
                row = data[randomIndex] 
                item.append(row)"""
        #print(fcm.membershipMatrix[0][0])
Esempio n. 16
0
from fcm import FCM
from point import Point

f = open("sample1.csv", "r")
f.readline()
points = []
for line in f:
    pointLine = line.replace("\n","").split(",")
    value = []
    point = Point()
    for val in pointLine:
        value.append(float(val))
    point.setValue(value)
    points.append(point)

fcm = FCM(points, m=2, minCluster=2, maxCluster=10)
fcm.run()
Esempio n. 17
0
#!/usr/bin/env python

from fcm import FCM

# JSON request

API_KEY = "your api key"

fcm = FCM(API_KEY)

registration_ids = ["your token 1", "your token 2"]

notification = {
    "title": "Awesome App Update",
    "body": "body",
}

response = fcm.json_request(
    registration_ids=registration_ids,
    notification=notification,
    # collapse_key='awesomeapp_update',
    # restricted_package_name="com.google.firebase.quickstart.fcm",
    priority='high',
    delay_while_idle=False)

# Successfully handled registration_ids
if response and 'success' in response:
    for reg_id, success_id in response['success'].items():
        print('Successfully sent notification for reg_id {0}'.format(reg_id))

# Handling errors