Python取讀csv文件做dbscan分析
1.讀取csv數(shù)據(jù)做dbscan分析
讀取csv文件中相應的列,然后進行轉化,處理為本算法需要的格式,然后進行dbscan運算,目前公開的代碼也比較多,本文根據(jù)公開代碼修改,
具體代碼如下:
from sklearn import datasets
import numpy as np
import random
import matplotlib.pyplot as plt
import time
import copy
import pandas as pd
# from sklearn.datasets import load_iris
?
def find_neighbor(j, x, eps):
? ? N = list()
? ? for i in range(x.shape[0]):
? ? ? ? temp = np.sqrt(np.sum(np.square(x[j] - x[i]))) ?# 計算歐式距離
? ? ? ? if temp <= eps:
? ? ? ? ? ? N.append(i)
? ? return set(N)
?
?
def DBSCAN(X, eps, min_Pts):
? ? k = -1
? ? neighbor_list = [] ?# 用來保存每個數(shù)據(jù)的鄰域
? ? omega_list = [] ?# 核心對象集合
? ? gama = set([x for x in range(len(X))]) ?# 初始時將所有點標記為未訪問
? ? cluster = [-1 for _ in range(len(X))] ?# 聚類
? ? for i in range(len(X)):
? ? ? ? neighbor_list.append(find_neighbor(i, X, eps))
? ? ? ? if len(neighbor_list[-1]) >= min_Pts:
? ? ? ? ? ? omega_list.append(i) ?# 將樣本加入核心對象集合
? ? omega_list = set(omega_list) ?# 轉化為集合便于操作
? ? while len(omega_list) > 0:
? ? ? ? gama_old = copy.deepcopy(gama)
? ? ? ? j = random.choice(list(omega_list)) ?# 隨機選取一個核心對象
? ? ? ? k = k + 1
? ? ? ? Q = list()
? ? ? ? Q.append(j)
? ? ? ? gama.remove(j)
? ? ? ? while len(Q) > 0:
? ? ? ? ? ? q = Q[0]
? ? ? ? ? ? Q.remove(q)
? ? ? ? ? ? if len(neighbor_list[q]) >= min_Pts:
? ? ? ? ? ? ? ? delta = neighbor_list[q] & gama
? ? ? ? ? ? ? ? deltalist = list(delta)
? ? ? ? ? ? ? ? for i in range(len(delta)):
? ? ? ? ? ? ? ? ? ? Q.append(deltalist[i])
? ? ? ? ? ? ? ? ? ? gama = gama - delta
? ? ? ? Ck = gama_old - gama
? ? ? ? Cklist = list(Ck)
? ? ? ? for i in range(len(Ck)):
? ? ? ? ? ? cluster[Cklist[i]] = k
? ? ? ? omega_list = omega_list - Ck
? ? return cluster
?
# X = load_iris().data
data = pd.read_csv("testdata.csv")
x,y=data['Time (sec)'],data['Height (m HAE)']
print(type(x))
n=len(x)
x=np.array(x)
x=x.reshape(n,1)
y=np.array(y)
y=y.reshape(n,1)
X = np.hstack((x, y))
cluster_std=[[.1]], random_state=9)
?
eps = 0.08
min_Pts = 5
begin = time.time()
C = DBSCAN(X, eps, min_Pts)
end = time.time()
plt.figure()
plt.scatter(X[:, 0], X[:, 1], c=C)
plt.show()2.輸出結果顯示

修改參數(shù)顯示:
eps = 0.8 min_Pts = 5


3.計算效率
采用少量數(shù)據(jù)計算的時候效率問題不明顯,隨著數(shù)據(jù)量增大,計算效率問題就變得尤為明顯,難以滿足大量數(shù)據(jù)的計算需求了,后期將想辦法優(yōu)化計算方法或者收集C++代碼進行優(yōu)化了。
到此這篇關于Python取讀csv文件做dbscan分析的文章就介紹到這了,更多相關Python dbscan分析內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Python2和Python3中@abstractmethod使用方法
這篇文章主要介紹了Python2和Python3中@abstractmethod使用方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-02-02
Python使用metaclass實現(xiàn)Singleton模式的方法
這篇文章主要介紹了Python使用metaclass實現(xiàn)Singleton模式的方法,實例分析了Python基于metaclass實現(xiàn)單例模式的相關技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-05-05
pytorch中的model=model.to(device)使用說明
這篇文章主要介紹了pytorch中的model=model.to(device)使用說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-05-05

