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 __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 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 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()
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
#!/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)
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
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])
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()
def send_notification(self, news): status_code = FCM(news).send_notification() print("Sent notification: " + str(status_code))
#!/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)
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])