x0 = [0, -2] # minimization of the negative function x_min = fmin(neg_f, x0) delta = 3 x_knots = linspace(x_min[0] - delta, x_min[0] + delta, 41) y_knots = linspace(x_min[1] - delta, x_min[1] + delta, 41) X, Y = meshgrid(x_knots, y_knots) Z = zeros(X.shape) for i in range(Z.shape[0]): for j in range(Z.shape[1]): Z[i][j] = f([X[i, j], Y[i, j]]) ax = Axes3D(figure(figsize=(8, 5))) ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm, linewidth=0.4) # initial point ax.plot([x0[0]], [x0[1]], [f(x0)], color='r', marker='o', markersize=5, label='initial') # optimal point ax.plot([x_min[0]], [x_min[1]], [f(x_min)], color='k', marker='o', markersize=5, label='final')
import os import pylab as pl from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt from matplotlib import cm from matplotlib.ticker import LinearLocator, FormatStrFormatter import numpy as np os.system("clear") fig = pl.figure() axx = Axes3D(fig) raiz = np.sqrt ln = np.log Xa = np.arange(-10, 10, 0.1) Ya = np.arange(-10, 10, 0.1) l = 2 rho = 100 ik = 25 Electrodos = 8 E = Electrodos - 1 P = np.array([ [-4, -4], #Posicion electrodo A [0, -4], #Posicion electrodo B [4, -4], #Posicion electrodo C [-4, 0], #Posicion electrodo D [4, 0], #Posicion electrodo E [-4, 4], #Posicion electrodo F [0, 4], #Posicion electrodo G
centers = [[1, 1], [-1, -1], [1, -1]] iris = datasets.load_iris() X = iris.data y = iris.target estimators = { 'k_means_iris_3': KMeans(n_clusters=3), 'k_means_iris_8': KMeans(n_clusters=8), 'k_means_iris_bad_init': KMeans(n_clusters=3, n_init=1, init='random') } fignum = 1 for name, est in estimators.items(): fig = plt.figure(fignum, figsize=(4, 3)) plt.clf() ax = Axes3D(fig, rect=[0, 0, .95, 1], elev=48, azim=134) plt.cla() est.fit(X) labels = est.labels_ ax.scatter(X[:, 3], X[:, 0], X[:, 2], c=labels.astype(np.float)) ax.w_xaxis.set_ticklabels([]) ax.w_yaxis.set_ticklabels([]) ax.w_zaxis.set_ticklabels([]) ax.set_xlabel('Petal width') ax.set_ylabel('Sepal length') ax.set_zlabel('Petal length') fignum = fignum + 1
# print("Eigen Vectors", vectors) # print("Eigen Values", values) vectors = vectors[:-1, :] values = values[:-1] # print("Eigen Vectors", vectors) # print("Eigen Values", values) # # project data P = vectors.dot(x_train.T) # print(P.T) x_train = P.T #Visualization fig = plt.figure(1, figsize=(8, 6)) ax = Axes3D(fig, elev=-150, azim=110) for i in range(150): if i < 50: ax.scatter(x_train[i][0], x_train[i][1], x_train[i][2], c='r', cmap=plt.cm.Set1, edgecolor='k', s=40) elif i < 100: ax.scatter(x_train[i][0], x_train[i][1], x_train[i][2], c='g',
from matplotlib import pyplot as plt import numpy as np from mpl_toolkits.mplot3d import Axes3D figure = plt.figure() ax = Axes3D(figure) X = np.arange(0, 10, 1) Y = np.arange(0, 10, 1) Z = np.arange(-1000, 0, 1) #网格化数据 X, Y = np.meshgrid(X, Y) # R = np.sqrt(X**2 + Y**2) # Z = np.cos(R) Z = 4 * X * X + (13 / 2) * Y * Y + 10 * X * Y - 2 * X - 2 * Y ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='rainbow') plt.show()
def scatter_plot(x_vals, y_vals, z_vals): fig = pyplot.figure() ax = Axes3D(fig) ax.scatter(x_vals, y_vals, z_vals) pyplot.show() return
def calcurate_style_meanstd(): parser = argparse.ArgumentParser() parser.add_argument('config') parser.add_argument('--out', required=True) args = parser.parse_args() cfg = Config.from_file(args.config) npy_paths = collect_path(cfg.train.dataset) head, ext = os.path.splitext(cfg.train.dataset) head, data_name = os.path.split(head) # Prepare skelton skelton, non_end_bones, joints_to_index, permute_xyz_order = btoj.get_standard_format( cfg.standard_bvh) _, non_zero_joint_to_index = btoj.cut_zero_length_bone( skelton, joints_to_index) Lul_offset = np.array(skelton['LeftUpLeg']['offsets']) Rul_offset = np.array(skelton['RightUpLeg']['offsets']) Lul_index = non_zero_joint_to_index['LeftUpLeg'] Rul_index = non_zero_joint_to_index['RightUpLeg'] standard_vector = Lul_offset - Rul_offset standard_norm = np.sqrt((Lul_offset[0] - Rul_offset[0])**2 + (Lul_offset[2] - Rul_offset[2])**2) # Initialize result = { style: {joint: 0 for joint in non_zero_joint_to_index} for style in cfg.train.class_list } data = None for npy_path in npy_paths: motion = np.load(npy_path) # Cut zero from motion _, motion = btoj.cut_zero_length_bone_frames(motion, skelton, joints_to_index) # Convert trajectory to velocity motion = motion[1:] trajectory = motion[:, :3] velocity = trajectory[1:, :] - trajectory[:-1, :] motion = np.concatenate((velocity, motion[1:, 3:]), axis=1) # Get orientation ('xz' only) motion_oriented = np.zeros_like(motion) leftupleg = motion[:, Lul_index * 3:Lul_index * 3 + 3] rightupleg = motion[:, Rul_index * 3:Rul_index * 3 + 3] vector = leftupleg - rightupleg norm = np.sqrt(vector[:, 0]**2 + vector[:, 2]**2) cos = (vector[:, 0] * standard_vector[0] + vector[:, 2] * standard_vector[2]) / (norm * standard_norm) cos = np.clip(cos, -1, 1) sin = 1 - cos**2 for t in range(motion.shape[0]): rotation_mat = np.array([[cos[t], 0., -sin[t]], [0., 1., 0.], [sin[t], 0., cos[t]]]) motion_oriented[t, :] = np.dot( rotation_mat.T, motion[t, :].reshape(28, 3).T).T.reshape(-1, ) # Set class npy_name = os.path.splitext(os.path.split(npy_path)[1])[0] style = npy_name.split('_')[0] mean = np.mean(motion[1:], axis=0) std = np.std(motion[1:], axis=0) mean_oriented = np.mean(motion_oriented, axis=0) std_oriented = np.std(motion_oriented, axis=0) # Write for joint in non_zero_joint_to_index: ji = non_zero_joint_to_index[joint] result[style][joint] = { 'mean': mean_oriented[ji * 3:ji * 3 + 3], 'std': std_oriented[ji * 3:ji * 3 + 3] } with open(args.out, 'wb') as f: pickle.dump(result, f) ##t-SNE mean_data, std_data, label_data = [], [], [] for style in result.keys(): data = result[style] mean_data.append( [data[joint]['mean'] for joint in non_zero_joint_to_index]) std_data.append( [data[joint]['std'] for joint in non_zero_joint_to_index]) label_data.append(cfg.train.class_list.index(style)) mean_data = np.array(mean_data).reshape(len(mean_data), -1) std_data = np.array(std_data).reshape(len(mean_data), -1) label_data = np.array(label_data).reshape(len(mean_data), ) plt.figure(figsize=(30, 30), dpi=72) # joint mean mean_velocity = np.stack((mean_data[:, 6], mean_data[:, 7]), axis=1) plt.subplot(331) plt.scatter(mean_velocity[:, 0], mean_velocity[:, 1], s=25) plt.title('mean' + list(non_zero_joint_to_index.keys())[2]) for i in range(mean_velocity.shape[0]): point = mean_velocity[i] label = cfg.train.class_list[label_data[i]] plt.text(point[0], point[1], label, fontsize=8) # joint std std_velocity = np.stack((std_data[:, 6], std_data[:, 7]), axis=1) plt.subplot(332) plt.scatter(std_velocity[:, 0], std_velocity[:, 1], s=25) plt.title('std_' + list(non_zero_joint_to_index.keys())[2]) for i in range(std_velocity.shape[0]): point = std_velocity[i] label = cfg.train.class_list[label_data[i]] plt.text(point[0], point[1], label, fontsize=8) # PCA mean pca = PCA(n_components=2) mean_pca = pca.fit_transform(mean_data) plt.subplot(333) plt.scatter(mean_pca[:, 0], mean_pca[:, 1], s=25) plt.title('pca_mean') for i in range(mean_pca.shape[0]): point = mean_pca[i] label = cfg.train.class_list[label_data[i]] plt.text(point[0], point[1], label, fontsize=8) # joint mean mean_velocity = np.stack((mean_data[:, 36], mean_data[:, 37]), axis=1) plt.subplot(334) plt.scatter(mean_velocity[:, 0], mean_velocity[:, 1], s=25) plt.title('mean_' + list(non_zero_joint_to_index.keys())[12]) for i in range(mean_velocity.shape[0]): point = mean_velocity[i] label = cfg.train.class_list[label_data[i]] plt.text(point[0], point[1], label, fontsize=8) # joint std std_velocity = np.stack((std_data[:, 36], std_data[:, 37]), axis=1) plt.subplot(335) plt.scatter(std_velocity[:, 0], std_velocity[:, 1], s=25) plt.title('std_' + list(non_zero_joint_to_index.keys())[12]) for i in range(std_velocity.shape[0]): point = std_velocity[i] label = cfg.train.class_list[label_data[i]] plt.text(point[0], point[1], label, fontsize=8) # PCA mean pca = PCA(n_components=2) std_pca = pca.fit_transform(std_data) plt.subplot(336) plt.scatter(std_pca[:, 0], std_pca[:, 1], s=25) plt.title('pca_std') for i in range(std_pca.shape[0]): point = std_pca[i] label = cfg.train.class_list[label_data[i]] plt.text(point[0], point[1], label, fontsize=8) # joint mean mean_velocity = np.stack((mean_data[:, 60], mean_data[:, 61]), axis=1) plt.subplot(337) plt.scatter(mean_velocity[:, 0], mean_velocity[:, 1], s=25) plt.title('mean_' + list(non_zero_joint_to_index.keys())[20]) for i in range(mean_velocity.shape[0]): point = mean_velocity[i] label = cfg.train.class_list[label_data[i]] plt.text(point[0], point[1], label, fontsize=8) # joint std std_velocity = np.stack((std_data[:, 60], std_data[:, 61]), axis=1) plt.subplot(338) plt.scatter(std_velocity[:, 0], std_velocity[:, 1], s=25) plt.title('std_' + list(non_zero_joint_to_index.keys())[20]) for i in range(std_velocity.shape[0]): point = std_velocity[i] label = cfg.train.class_list[label_data[i]] plt.text(point[0], point[1], label, fontsize=8) # PCA mean and std pca = PCA(n_components=2) mean_std_pca = pca.fit_transform( np.concatenate((mean_data, std_data), axis=1)) plt.subplot(339) plt.scatter(mean_std_pca[:, 0], mean_std_pca[:, 1], s=25) plt.title('pca_mean_std') for i in range(mean_std_pca.shape[0]): point = mean_std_pca[i] label = cfg.train.class_list[label_data[i]] plt.text(point[0], point[1], label, fontsize=8) plt.savefig(os.path.splitext(args.out)[0] + '_tSNE.png') # 3D PCA mean and std fig = plt.figure(figsize=(10, 10), dpi=72) ax = Axes3D(fig) pca = PCA(n_components=3) mean_std_pca3d = pca.fit_transform( np.concatenate((mean_data, std_data), axis=1)) ax.scatter3D(mean_std_pca3d[:, 0], mean_std_pca3d[:, 1], mean_std_pca3d[:, 2], s=25) for i in range(mean_std_pca.shape[0]): point = mean_std_pca3d[i] label = cfg.train.class_list[label_data[i]] ax.text(point[0], point[1], point[2], label, fontsize=8) plt.savefig(os.path.splitext(args.out)[0] + '_PCA3D.png')
def printObstacleObbByNotZTest(name): # arr1 = [[1, 2, 3]] # arr2 = [[4, 0, 3]] # print(np.dot(np.transpose(arr1) ,arr2)) # print(np.dot(arr1 ,np.transpose(arr2))) fig = plt.figure() ax = Axes3D(fig) file_obj = open("E:\\graduateDesignTxt\\点云\\" + name + ".txt", encoding='UTF-8') x = [] y = [] z = [] for line in file_obj.readlines(): line = line.rstrip("\n") arr = line.split(",") # print(arr) x.append(float(arr[0])) y.append(float(arr[1])) z.append(float(arr[2])) size = len(x) # print(size) points = numpy.zeros((size, 3)) pointsNotZ = numpy.zeros((size, 2)) print(np.transpose(points)) # print(points) for i in range(size): points[i][0] = x[i] points[i][1] = y[i] points[i][2] = z[i] # print(points[i]) pointsNotZ[i][0] = x[i] pointsNotZ[i][1] = y[i] avg = np.array([0, 0]) # print(avg) # avg[0] = 0 # avg[1] = 0 # avg[2] = 0 for i in range(size): avg[0] += x[i] avg[1] += y[i] # avg[2] += z[i] avg[0] /= size avg[1] /= size # avg[2]/=size arr = numpy.linalg.eig(numpy.cov(np.transpose(pointsNotZ))) print(arr) # print(numpy.linalg.eig(numpy.cov(points))) maxL = -100000 maxW = -100000 maxH = -100000 minL = 100000 minW = 100000 minH = 100000 for point in points: maxL = max(maxL, np.dot(point[:2], np.transpose(arr[1][0]))) minL = min(minL, np.dot(point[:2], np.transpose(arr[1][0]))) maxW = max(maxW, np.dot(point[:2], np.transpose(arr[1][1]))) minW = min(minW, np.dot(point[:2], np.transpose(arr[1][1]))) maxH = max(maxH, point[2]) minH = min(minH, point[2]) # print(minL) tr = np.transpose(arr[1]) print(tr) pointA = [(maxL + minL) / 2, (maxW + minW) / 2, (maxH + minH) / 2] X = np.dot(pointA[:2], np.transpose(tr[0])) Y = np.dot(pointA[:2], np.transpose(tr[1])) Z = pointA[2] pointB = [X, Y, Z] print(X, Y, Z) arrVector = arr[1] print(arrVector) halfLengthA = [(maxL - minL) / 2, (maxW - minW) / 2, (maxH - minH) / 2] vector = [[arrVector[0][0], arrVector[0][1], 0], [arrVector[1][0], arrVector[1][1], 0], [0, 0, 1]] print(vector) printOct(halfLengthA, pointB, vector, ax) ax.scatter(x, y, z, s=1) plt.xlim(1000, 2500) plt.ylim(-1000, 1000) plt.show()
plot.render(plt.gcf()) if (do_plot_all == False): plt.close() # 2D KDE fig20 = plt.figure(20) plot = rplot.RPlot(tips_data, x='total_bill', y='tip') plot.add(rplot.TrellisGrid(['sex', 'smoker'])) plot.add(rplot.GeomScatter()) plot.add(rplot.GeomDensity2D()) plot.render(plt.gcf()) if (do_plot_all == False): plt.close() # 3D plotting of surfaces from mpl_toolkits.mplot3d import Axes3D fig21 = plt.figure(21) ax = Axes3D(fig21) X = np.arange(-4, 4, 0.25) Y = np.arange(-4, 4, 0.25) X, Y = np.meshgrid(X, Y) R = np.sqrt(X**2 + Y**2) Z = np.sin(R) # uncomment to adjust the view #ax.view_init(elev=0., azim=0) #ax.view_init(elev=50., azim=0) ax.view_init(elev=50., azim=30) ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='hot') if (do_plot_all == False): plt.close() ## plot all figures plt.show()
def plot_3D(x, y, z): fig = plt.figure() ax = Axes3D(fig) ax.scatter(xs=x, ys=y, zs=z, zdir='z') plt.show()
# load data iris = datasets.load_iris() # extract features (petal length, width, Sepal length, width) features = iris.data # three different types of iris (versicolor, Sentosa, Virginica) labels = iris.target # k means clustering kmeans = cluster.KMeans(n_clusters=5) kmeans.fit(features) centers = kmeans.labels_ # plot the cluster in color 3D plot fig = plt.figure(1, figsize=(8, 8)) plt.clf() ax = Axes3D(fig, rect=[0, 0, 1, 1], elev=8, azim=200) plt.cla() ax.scatter(features[:, 3], features[:, 0], features[:, 2], c=centers.astype(np.float)) ax.w_xaxis.set_ticklabels([]) ax.w_yaxis.set_ticklabels([]) ax.w_zaxis.set_ticklabels([]) ax.set_xlabel('Petal width') ax.set_ylabel('Sepal length') ax.set_zlabel('Petal length')
lis.append(eval(tmp[j])) dic[i]=lis df = pd.DataFrame(dic).T df.head(10) data=df.values # 0. raw data from mpl_toolkits.mplot3d import Axes3D #%matplotlib inline from sklearn.datasets.samples_generator import make_classification fig = plt.figure() ax = Axes3D(fig, rect=[0, 0, 1, 1], elev=30, azim=20) y=data[:,0] ax.scatter(data[:, 1], data[:, 2], data[:, 3],marker='o',c=y) plt.show() # 1. PCA X=data from sklearn.decomposition import PCA pca = PCA(n_components=2) pca.fit(X) X_new = pca.transform(X) plt.scatter(X_new[:, 0], X_new[:, 1],marker='o',c=y) plt.show() # 2. LDA y=data[:,0]
import matplotlib.pyplot as plt try: import numpy as np except: exit() from deap import benchmarks def untuple(sol): return benchmarks.himmelblau(sol)[0] fig = plt.figure() ax = Axes3D(fig, azim=-29, elev=49) X = np.arange(-6, 6, 0.1) Y = np.arange(-6, 6, 0.1) X, Y = np.meshgrid(X, Y) Z = np.array(list(map(untuple, zip(X, Y)))) ax.plot_surface(X, Y, Z, rstride=1, cstride=1, norm=LogNorm(), cmap=cm.jet, linewidth=0.2) plt.xlabel("x")
def plot_3d(df, style='scatter', show_plot=True, options='normal', animate=False, to_html5=False): ''' INPUT: (1) Pandas DataFrame with locations (2) string: denoting the style. 'scatter' or 'wireframe' 'scatter' looks significantly better. (3) boolean: show the plot? (4) string: 'mcp' or 'normal' corresponding to how to plot the points 'mcp' will split into mountain, city, plains, 'normal' will be all black (5) boolean: animate the plot? (6) boolean: return the animation as html5 tag? Plot all the locations in lat/lng/elev space. Just for fun to see all of the downloaded locations. ''' fig = plt.figure(figsize=(8, 8)) ax = Axes3D(fig) if show_plot: ax.set_xlabel('lat') ax.set_ylabel('lng') ax.set_zlabel('elevation (m)', rotation=90) cities = reduce(np.intersect1d, [ np.where(df['elev'] > 1300), np.where(df['elev'] < 2400), np.where(df['lat'] > 38.6), np.where(df['lng'] > -105.25), np.where(df['lng'] < -104.2) ]) not_cities = np.setdiff1d(np.arange(len(df)), cities) plains = reduce(np.intersect1d, [ not_cities, np.where(df['lng'] > -105.25), np.where(df['elev'] < 1800) ]) not_plains = np.setdiff1d(np.arange(len(df)), plains) mountains = reduce( np.intersect1d, [not_cities, not_plains, np.where(df['lng'] < -104.2)]) if animate: def show(): if style == 'scatter': if options == 'mcp': ax.scatter(df.lat[cities], df.lng[cities], df.elev[cities], color='k', s=1) ax.scatter(df.lat[plains], df.lng[plains], df.elev[plains], color='r', s=1) ax.scatter(df.lat[mountains], df.lng[mountains], df.elev[mountains], color='g', s=1) else: ax.scatter(df.lat, df.lng, df.elev, color='k', s=1) ax.set_xlabel('Latitude ($^{\circ}$)') ax.set_ylabel('Longitude ($^{\circ}$)') ax.set_zlabel('Elevation (meters)') plt.gca().invert_yaxis() if style == 'wireframe': ordered_lat = df.lat[np.lexsort( (df.lat.values, df.lng.values))].values ordered_lng = df.lng[np.lexsort( (df.lat.values, df.lng.values))].values xv, yv = np.meshgrid(ordered_lat, ordered_lng) ordered_elev = df.elev[np.lexsort( (df.lat.values, df.lng.values))].values xe, ye = np.meshgrid(ordered_elev, ordered_elev) ax.plot_trisurf(df.lat.values[::10], df.lng.values[::10], df.elev.values[::10], cmap=cm.jet, linewidth=0.2) plt.show() def animate(i): ax.view_init(elev=45., azim=i) anim = animation.FuncAnimation(fig, animate, init_func=show, frames=1080, interval=20, blit=False) anim.save('data_animation_rotation_dpi200_45deg_newlabels5.mp4', fps=30, extra_args=['-vcodec', 'libx264'], dpi=200) if to_html5: html5_anim = animation.Animation.to_html5_video(anim) return html5_anim
def Kmeans(X_pca, k, isPCA=True, normalize=True, bidimensional=False): """ Kmeans clustering method X_pca = dataset with PCA k = number of clusters isPCA = if the dataset comes from PCA normalize = if normalizing is needed bidimensional = if the dataset has only 2 variables """ from mpl_toolkits.mplot3d import Axes3D from sklearn.cluster import KMeans from sklearn import preprocessing import matplotlib.pyplot as plt import numpy as np import collections iterations = 10 max_iter = 300 tol = 1e-04 random_state = 0 init = "random" if (not isPCA): X_pca = X_pca.to_numpy() if (normalize): scaler = preprocessing.StandardScaler() X_pca = scaler.fit_transform(X_pca) km = KMeans(k, init, n_init=iterations, max_iter=max_iter, tol=tol, random_state=random_state) labels = km.fit_predict(X_pca) map = collections.Counter(labels) from sklearn import metrics print("Silhouette Score:\n" + str(metrics.silhouette_score(X_pca, labels))) print("\nCentroids with number of ocurrences:") for x in range(0, np.size(km.cluster_centers_, 0)): # print(str(km.cluster_centers_[x])+'\t\tlabel: '+str(x)+' number of ocurrences: '+str(map[x])) print('{:<40s} {:<30s}'.format( str(km.cluster_centers_[x]), 'label: ' + str(x) + ' number of ocurrences: ' + str(map[x]))) if (bidimensional): plt.xlabel('Roll') plt.ylabel('Pitch') x = X_pca[:, 0] y = X_pca[:, 1] plt.scatter(x, y, c=labels) # plotting centroids plt.scatter(km.cluster_centers_[:, 0], km.cluster_centers_[:, 1], c='red', s=50) plt.show() else: fig = plt.figure() ax = Axes3D(fig) x = X_pca[:, 0] y = X_pca[:, 1] z = X_pca[:, 2] # plt.scatter(km.cluster_centers_[:,0], km.cluster_centers_[:,1], km.cluster_centers_[:,2], c='red',s=50)# ax.scatter(km.cluster_centers_[:, 0], km.cluster_centers_[:, 1], km.cluster_centers_[:, 2], c='red', s=50) ax.scatter(x, y, z, c=labels) plt.show()
w = linspace(-pi * fmax, pi * fmax, N + 1) w = w[:-1] figure() subplot(2, 1, 1) plot(w, abs(Y_4), color='green') xlim([-100, 100]) subplot(2, 1, 2) plot(w, angle(Y_4), 'ro') xlim([-100, 100]) # -----Problem 5----- Y = [] for i in range(16): tlim_1 = -pi + 2 * pi * i / 16 tlim_2 = -pi + 2 * pi * (i + 1) / 16 t = linspace(tlim_1, tlim_2, 65) t = t[:-1] y = cos(16 * t * (1.5 + t / (2 * pi))) y[0] = 0 Y.append((fftshift(fft(y)) / 64)) Yd = array(Y) t1 = linspace(-pi, pi, 16) w = linspace(-pi * fmax / 2, pi * fmax / 2, 65) w = w[:-1] t1, w = meshgrid(t1, w) ax = Axes3D(figure()) surf = ax.plot_surface(t1, w, abs(Yd).T, rstride=1, cstride=1, cmap='viridis') xlabel('t') ylabel('w') show()
import pandas as pd import pylab from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy fig = pylab.figure() axes = Axes3D(fig) for i in 1, 2: kills = pd.read_csv("C:\\kills" + str(i) + ".csv") damage = pd.read_csv("C:\\damage_received" + str(i) + ".csv") res = kills.merge(damage, how='inner', left_on='killer_recording_id', right_on='attacker_recording_id') k_coordinates = kills.merge(damage, how='inner', on='victim_recording_id').drop_duplicates( subset='victim_recording_id', keep='first') x_data = k_coordinates['victim_pos_x'] y_data = k_coordinates['victim_pos_y'] z_data = k_coordinates['victim_pos_z'] x = x_data.as_matrix() y = y_data.as_matrix() z = z_data.as_matrix() plt.plot(x, y, z, 'o') pylab.show()
import pandas as pd data_path = '/Users/Xiaobang/jupyter/didi/' data = pd.read_csv(data_path + 'result_check.csv') data.head(5) from sklearn.decomposition import PCA from mpl_toolkits.mplot3d import Axes3D train_data = data.copy() label = train_data.label train_data = train_data.drop(['link_id', 'label'], axis=1) pca = PCA(n_components=3) pca.fit(train_data) new_data = pca.transform(train_data) new_df = pd.DataFrame(new_data) new_df = pd.concat([new_df, label], axis=1) new_df.columns = ['pca_f1', 'pca_f2', 'pca_f3', 'label'] new_df.to_csv(data_path + 'new_df.csv', index=False, header=False) fig = plt.figure(figsize=(20, 20)) ax = Axes3D(fig, elev=-30, azim=0) colors = ['black', 'blue', 'purple', 'yellow', 'red', 'green', 'cyan'] for i in range(6): sub_new_df = new_df[new_df['label'] == i] plt.scatter(sub_new_df.pca_f1, sub_new_df.pca_f2, sub_new_df.pca_f3, c=colors[i])
"""This generates four graphs for arcsin(z).""" # Original: Peter Halasz. 2010-09-14 # Enhanced: Ika. 2013-07-23 import numpy as np from pylab import * from mpl_toolkits.mplot3d import Axes3D graphs = {'abs': abs, 'real': real, 'imag': imag, 'angle': angle} for gr in graphs: ax = Axes3D(figure(), azim=-135, elev=45) X = arange(-2 * pi, 2 * pi, pi / 12) Y = arange(-4, 4, .2) X, Y = meshgrid(X, Y) fn = graphs[gr] Z = fn(arcsin(X + Y * 1j)) # abs, real, imag, angle. angle range [-pi, pi] ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.jet) ax.contour(X, Y, Z, zdir='z', offset=np.min(Z)) ax.set_xlabel("x") ax.set_ylabel("y") ax.set_zlabel(gr + '(sin(x+iy))') plt.savefig("complex_arcsin_" + gr + "_01_Pengo.jpg")
def ShowZ1A1Z2A2(): wb1 = WeightsBias(2, 2, 0.1, InitialMethod.Xavier) wb2 = WeightsBias(1, 2, 0.1, InitialMethod.Xavier) LoadWeights(wb1, wb2) print(wb1.toString()) print(wb2.toString()) dataReader = XOR_DataReader() dataReader.ReadData() Z1 = np.dot(wb1.W, dataReader.X) + wb1.B A1 = Sigmoid().forward(Z1) # layer 2 Z2 = np.dot(wb2.W, A1) + wb2.B A2 = Sigmoid().forward(Z2) print(Z1) print(A1) print(Z2) print(A2) for i in range(dataReader.num_example): if dataReader.Y[0, i] == 0: plt.plot(dataReader.X[0, i], dataReader.X[1, i], '^', c='r') else: plt.plot(dataReader.X[0, i], dataReader.X[1, i], 'o', c='g') plt.grid() plt.title("X1:X2") plt.show() fig = plt.figure() ax = Axes3D(fig) for i in range(dataReader.num_example): if dataReader.Y[0, i] == 0: ax.scatter(Z1[0, i], Z1[1, i], Z1[2, i], c='r') #ax.plot(Z1[0,i],Z1[1,i],Z1[2,i],c='r') else: ax.scatter(Z1[0, i], Z1[1, i], Z1[2, i], c='g') #ax.plot(Z1[0,i],Z1[1,i],Z1[2,i],c='g') plt.grid() plt.title("Z1") plt.show() fig = plt.figure() ax = Axes3D(fig) for i in range(dataReader.num_example): if dataReader.Y[0, i] == 0: ax.scatter(A1[0, i], A1[1, i], A1[2, i], '^', c='r') #plt.plot(A1[0,i],A1[1,i],A1[2,i],'^',c='r') else: ax.scatter(A1[0, i], A1[1, i], A1[2, i], 'o', c='g') #plt.plot(A1[0,i],A1[1,i],A1[2,i],'o',c='g') plt.grid() plt.title("A1") plt.show() x = np.linspace(-6, 6) a = Sigmoid().forward(x) plt.plot(x, a) for i in range(dataReader.num_example): if dataReader.Y[0, i] == 0: plt.plot(Z2[0, i], A2[0, i], '^', c='r') else: plt.plot(Z2[0, i], A2[0, i], 'o', c='g') plt.grid() plt.title("Z2:A2") plt.show()
def plot_poly_axes3d(file_name, poly_coordinates, magnitudes=None, title=None, limits=None, figure=None, figure_ax=None, width_scale=1): ''' PARAMETERS: file_name {string, -} File name with extension i.e. '.png'. Plot will be saved according to this name poly_coordinates {list float, -} It contains a list of polygon. i.e. [subpoly1, subpoly2, ...] Each 'subpoly' is defined by a sequence of coordinates. i.e. [[x1, y1, z1], [x2, y2, z2], ...] magnitudes {list float, -} A list of number REMARKS: 1. if figure_ax is not None, then it has to be an Axes3D object. ''' # instantiate figure if not figure_ax: fig = plt.figure(figsize=(width_scale * 8.3, width_scale * 8.3/1.3333333333)) fig_ax = Axes3D(fig) else: fig = figure fig_ax = figure_ax # set title if title: fig_ax.set_title(title) # set labels fig_ax.set_xlabel('x') fig_ax.set_ylabel('y') fig_ax.set_zlabel('z') # set limits if limits: fig_ax.set_xlim(limits[0]) fig_ax.set_ylim(limits[1]) fig_ax.set_zlim(limits[2]) # convert the current segment from vertex index to vertex coordinates # coordinates = [] # for each_segment in segments: # coordinates.append([tuple(vertices[each_vertex_index]) for each_vertex_index in each_segment]) plot_style_default = { 'facecolor': 'deepskyblue', 'linewidths': 1, 'alpha': 0.5, 'edgecolor': 'black', 'antialiaseds': True } # create colours for each segment if magnitudes is not None: max_magnitude = float(max(magnitudes)) min_magnitude = float(min(magnitudes)) magnitudes = [v - min_magnitude for v in magnitudes] magnitudes = [v/float(max(magnitudes)) for v in magnitudes] # scale 'magnitudes' to [0, 1] cmap = cm.get_cmap('Spectral') # define colour map magnitudes = cmap(magnitudes) plot_style_default['facecolor'] = magnitudes collection = Poly3DCollection(poly_coordinates, **plot_style_default) fig_ax.add_collection3d(collection) fig.savefig(file_name, format='png', dpi=300) return fig, fig_ax
# -*- coding: utf-8 -*- """ Created on 2018/10/10 @author: ni """ import cv2 import numpy as np from numpy import mat from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt if __name__ == '__main__': img1 = cv2.imread('(0 0 -1).png', cv2.IMREAD_COLOR) img1 = cv2.cvtColor(img1, cv2.COLOR_RGB2GRAY) img1 = np.array(img1) img2 = cv2.imread('(0 0.2 -1).png', cv2.IMREAD_COLOR) img2 = cv2.cvtColor(img2, cv2.COLOR_RGB2GRAY) img2 = np.array(img2) img3 = cv2.imread('(0 -0.2 -1).png', cv2.IMREAD_COLOR) img3 = cv2.cvtColor(img3, cv2.COLOR_RGB2GRAY) img3 = np.array(img3) img4 = cv2.imread('(0.2 0 -1).png', cv2.IMREAD_COLOR) img4 = cv2.cvtColor(img4, cv2.COLOR_RGB2GRAY) img4 = np.array(img4) s1 = (0, 0, -1) s2 = (0, 0.2, -1) s3 = (0, -0.2, -1) s4 = (0.2, 0, -1) n_map = np.zeros(shape=[img1.shape[0], img1.shape[1], 3]) img_i = mat(np.zeros(shape=[4, 1])) s = mat(np.array([s1, s2, s3, s4]))
def debugmode(self, depthMap, sfnormMap, intrinsics, extrinsics, rgb, semantics): viewInd = 0 depthFlat = depthMap.view([self.batchsize, -1]) pts3d = torch.stack([ self.xx * depthFlat, self.yy * depthFlat, depthFlat, torch.ones_like(depthFlat, device='cuda', dtype=torch.float) ], dim=1) projMtx = torch.inverse(torch.matmul(intrinsics, extrinsics)) pts3d = torch.matmul(projMtx, pts3d) pts3d_vec = pts3d.view(self.batchsize, 4, self.height, self.width)[:, 0:3, :, :].unsqueeze(1).expand( -1, self.surfaceType, -1, -1, -1) planeParams = torch.cat([ sfnormMap, torch.sum(-(sfnormMap * pts3d_vec), dim=2, keepdim=True) ], dim=2) # check # pts3d_check = pts3d.view(self.batchsize, 4, self.height, self.width) # pts3d_check = pts3d_check.unsqueeze(1).expand(-1,self.surfaceType,-1,-1,-1) # checked_val = torch.sum(planeParams * pts3d_check, dim=2) # checked_val = torch.mean(checked_val) # For interleave # a = torch.Tensor([[1,3], [9, 11]]) # b = torch.Tensor([[2,4], [10, 12]]) # c = torch.Tensor([[5,7], [13, 15]]) # d = torch.Tensor([[6,8], [14, 16]]) # m = torch.stack([a, b], dim=2).view(2, 4) # n = torch.stack([c, d], dim=2).view(2, 4) # mn = torch.stack([m, n], dim=1).view(4, 4) planeParams_ranged = planeParams.permute(0, 1, 3, 4, 2).contiguous().view( -1, 1, 4) projMtx_ranged = projMtx.view(self.batchsize, 1, 4, 4, 1, 1).expand( -1, self.surfaceType, -1, -1, self.height, self.width).permute(0, 1, 4, 5, 2, 3).contiguous().view(-1, 4, 4) # aMtx = torch.matmul(planeParams_ranged, projMtx_ranged) # aMtx = aMtx.view(self.batchsize, self.surfaceType, self.height, self.width, 1, 4) aMtx = torch.matmul(planeParams_ranged, projMtx_ranged).squeeze(1) xx_depthcomp = self.xx.view(self.batchsize, self.height, self.width).unsqueeze(1).expand( -1, self.surfaceType, -1, -1).contiguous().view(-1) yy_depthcomp = self.yy.view(self.batchsize, self.height, self.width).unsqueeze(1).expand( -1, self.surfaceType, -1, -1).contiguous().view(-1) deptha = -aMtx[:, 3] / (aMtx[:, 0] * (xx_depthcomp - 0.5) + aMtx[:, 1] * (yy_depthcomp - 0.5) + aMtx[:, 2] + 1e-10) deptha = deptha.view(self.batchsize, self.surfaceType, self.height, self.width) depthb = -aMtx[:, 3] / (aMtx[:, 0] * (xx_depthcomp + 0.5) + aMtx[:, 1] * (yy_depthcomp - 0.5) + aMtx[:, 2] + 1e-10) depthb = depthb.view(self.batchsize, self.surfaceType, self.height, self.width) depthc = -aMtx[:, 3] / (aMtx[:, 0] * (xx_depthcomp - 0.5) + aMtx[:, 1] * (yy_depthcomp + 0.5) + aMtx[:, 2] + 1e-10) depthc = depthc.view(self.batchsize, self.surfaceType, self.height, self.width) depthd = -aMtx[:, 3] / (aMtx[:, 0] * (xx_depthcomp + 0.5) + aMtx[:, 1] * (yy_depthcomp + 0.5) + aMtx[:, 2] + 1e-10) depthd = depthd.view(self.batchsize, self.surfaceType, self.height, self.width) # random check # channelind = torch.LongTensor(1).random_(0, self.batchsize)[0] # typeind = torch.LongTensor(1).random_(0, self.surfaceType)[0] # heightind = torch.LongTensor(1).random_(0, self.height)[0] # widthind = torch.LongTensor(1).random_(0, self.width)[0] # depthval = depthb[channelind, typeind, heightind, widthind] # planeParams_check = planeParams[channelind, typeind, :, heightind, widthind] # pts3d = torch.Tensor([(widthind.float() + 1) * 2 * depthval, heightind.float() * 2 * depthval, depthval, 1]).cuda() # pts3d = projMtx[channelind, :, :] @ pts3d.unsqueeze(1) # torch.sum(planeParams_check * pts3d.t()) depthab = torch.stack([deptha, depthb], dim=4).view(self.batchsize, self.surfaceType, self.height, int(self.width * 2)) depthcd = torch.stack([depthc, depthd], dim=4).view(self.batchsize, self.surfaceType, self.height, int(self.width * 2)) depthabcd = torch.stack([depthab, depthcd], dim=3).view(self.batchsize, self.surfaceType, int(self.height * 2), int(self.width * 2)) # downsample check # depthabcd_downsampled = F.interpolate(depthabcd, (self.height, self.width), mode='bilinear') # depthabcd_downsampled = torch.mean(depthabcd_downsampled, dim=1, keepdim=True) # depthabcd_downsampled[depthMap < 1e-1] = 0 # tensor2disp(depthabcd_downsampled, ind = viewInd, vmax=80).show() # tensor2disp(depthMap, ind = viewInd, vmax=80).show() # random check channelind = torch.LongTensor(1).random_(0, self.batchsize)[0] typeind = torch.LongTensor(1).random_(0, self.surfaceType)[0] heightind = torch.LongTensor(1).random_(0, int(self.height * 2))[0] widthind = torch.LongTensor(1).random_(0, int(self.width * 2))[0] depthval = depthabcd[channelind, typeind, heightind, widthind] planeParams_check = planeParams[channelind, typeind, :, int(torch.floor(heightind.float() / 2)), int(torch.floor(widthind.float() / 2))] pts3d_t = torch.Tensor([ widthind.float() * depthval, heightind.float() * depthval, depthval, 1 ]).cuda() pts3d_t = projMtx[channelind, :, :] @ pts3d_t.unsqueeze(1) torch.sum(planeParams_check * pts3d_t.t()) # random check # channelind = torch.LongTensor(1).random_(0, self.batchsize)[0] # typeind = torch.LongTensor(1).random_(0, self.surfaceType)[0] # heightind = torch.LongTensor(1).random_(0, self.height)[0] # widthind = torch.LongTensor(1).random_(0, self.width)[0] # deptha_t = deptha[channelind, typeind, heightind, widthind] # depthb_t = depthb[channelind, typeind, heightind, widthind] # depthc_t = depthc[channelind, typeind, heightind, widthind] # depthd_t = depthd[channelind, typeind, heightind, widthind] # depthabcd_t = depthabcd[channelind, typeind, int(heightind * 2) : int(heightind * 2) + 2, int(widthind * 2) : int(widthind * 2) + 2] # check # channelind = 10 # typeind = 5 # height = 30 # width = 50 # results = aMtx[channelind, typeind, height, width, 0, :] # check_results = planeParams[channelind, typeind, :, height, width] @ projMtx[channelind, :, :] # print(torch.sum((results - check_results)**2)) # for visualization objType = 19 self.colorMap = np.zeros((objType + 1, self.xx.shape[1], 3), dtype=np.uint8) for i in range(objType): if i == objType: k = 255 else: k = i self.colorMap[i, :, :] = np.repeat( np.expand_dims(np.array(trainId2label[k].color), 0), self.xx.shape[1], 0) self.colorMap = self.colorMap.astype(np.float) self.colorMap = self.colorMap / 255 semantics_flat = semantics[viewInd, 0, :, :].view(-1) semantics_flat[semantics_flat == 255] = objType - 1 semantics_flat = semantics_flat.cpu().numpy() colors = self.colorMap[semantics_flat, np.arange(self.xx.shape[1]), :] visuailize_mask = depthFlat[viewInd, :] > 1e-5 pts_to_show = pts3d[viewInd, :, :] pts_to_show = pts_to_show[:, visuailize_mask] pts_to_show = pts_to_show.cpu().numpy().T visuailize_mask = visuailize_mask.cpu().numpy() visuailize_mask = visuailize_mask == 1 colors = colors[visuailize_mask, :] fig = plt.figure() sampleDensity = 4 ax = Axes3D(fig) ax.view_init(elev=6., azim=170) ax.dist = 4 ax.scatter(pts_to_show[0::sampleDensity, 0], pts_to_show[0::sampleDensity, 1], pts_to_show[0::sampleDensity, 2], s=0.5, c=colors[0::sampleDensity, :]) ax.set_zlim(-10, 10) plt.ylim([-10, 10]) plt.xlim([10, 16]) set_axes_equal(ax) tensor2semantic(semantics, ind=viewInd).show() tensor2rgb(rgb, ind=viewInd).show() pts3d_interleaved = depth23dpts( depthabcd[viewInd, 0, :, :].detach().cpu().numpy(), intrinsics[viewInd, :, :].detach().cpu().numpy(), extrinsics[viewInd, :, :].detach().cpu().numpy()) fig = plt.figure() sampleDensity = 4 sampleDensity2 = 16 ax = Axes3D(fig) ax.view_init(elev=6., azim=170) ax.dist = 4 ax.scatter(pts_to_show[0::sampleDensity, 0], pts_to_show[0::sampleDensity, 1], pts_to_show[0::sampleDensity, 2], s=0.5, c=colors[0::sampleDensity, :]) ax.scatter(pts3d_interleaved[0::sampleDensity2, 0], pts3d_interleaved[0::sampleDensity2, 1], pts3d_interleaved[0::sampleDensity2, 2], s=0.5, c='r') ax.set_zlim(-10, 10) plt.ylim([-10, 10]) plt.xlim([10, 16]) set_axes_equal(ax) return depthabcd
def main(): parser = argparse.ArgumentParser() parser.add_argument("--data_name", help="csv file name", default="default.csv") parser.add_argument("--second_name", help="csv file name", default="default.csv") parser.add_argument("--joint_h", help="joint hierarchy file name", default="../joint_hierarchy.txt") parser.add_argument("--show_id", help="show skelton data id", default=0, type=int) parser.add_argument("--show_mode", help="show mode, single[0] or all[1], multi[2]", default=0, type=int) args = parser.parse_args() data = loading_file(args.data_name) hierarchy = loading_hierarchy(args.joint_h) data = np.array(data, dtype=float) print(args.show_mode) if args.show_mode == 0 or args.show_mode == 2: fig = plt.figure() ax = Axes3D(fig) for i in range(25): x = [ float(data[int(args.show_id), int(hierarchy[i, 0]), 0]), float(data[int(args.show_id), int(hierarchy[i, 1]), 0]) ] y = [ float(data[int(args.show_id), int(hierarchy[i, 0]), 1]), float(data[int(args.show_id), int(hierarchy[i, 1]), 1]) ] z = [ float(data[int(args.show_id), int(hierarchy[i, 0]), 2]), float(data[int(args.show_id), int(hierarchy[i, 1]), 2]) ] ax.plot(x, y, z, marker='.', markersize=1, color='r', linewidth=2.0) ax.plot(data[int(args.show_id), :, 0], data[int(args.show_id), :, 1], data[int(args.show_id), :, 2], marker='.', markersize=10, color='b', linestyle='None') if args.show_mode == 2: data_ = loading_file(args.second_name) data_ = np.array(data_, dtype=float) for i in range(25): x = [ float(data_[args.show_id, int(hierarchy[i, 0]), 0]), float(data_[args.show_id, int(hierarchy[i, 1]), 0]) ] y = [ float(data_[args.show_id, int(hierarchy[i, 0]), 1]), float(data_[args.show_id, int(hierarchy[i, 1]), 1]) ] z = [ float(data_[args.show_id, int(hierarchy[i, 0]), 2]), float(data_[args.show_id, int(hierarchy[i, 1]), 2]) ] ax.plot(x, y, z, marker='.', markersize=1, color='g', linewidth=2.0) ax.plot(data_[args.show_id, :, 0], data_[args.show_id, :, 1], data_[args.show_id, :, 2], marker='.', markersize=10, color='g', linestyle='None') ax.set_xlabel('x') ax.set_ylabel('y') ax.set_zlabel('z') plt.show() elif args.show_mode == 1: for j in range(data.shape[0]): fig = plt.figure() ax = Axes3D(fig) for i in range(25): x = [ float(data[j, int(hierarchy[i, 0]), 0]), float(data[j, int(hierarchy[i, 1]), 0]) ] y = [ float(data[j, int(hierarchy[i, 0]), 1]), float(data[j, int(hierarchy[i, 1]), 1]) ] z = [ float(data[j, int(hierarchy[i, 0]), 2]), float(data[j, int(hierarchy[i, 1]), 2]) ] ax.plot(x, y, z, marker='.', markersize=1, color='r', linewidth=2.0) ax.plot(data[j, :, 0], data[j, :, 1], data[j, :, 2], marker='.', markersize=20, color='r', linestyle='None') ax.set_xlabel('x') ax.set_ylabel('y') ax.set_zlabel('z') plt.show()
max_iters = 10 initial_centroids = kMeansInitCentroids(X, K) centroids, idx = runkMeans(X, initial_centroids, max_iters) # % Sample 1000 random indexes (since working with all the data is # % too expensive. If you have a fast computer, you may increase this. sel = np.random.permutation(1000) # % Setup Color Palette hsv_tuples = [(x * 1.0 / K, 0.5, 0.5) for x in range(K)] rgb_tuples = [colorsys.hsv_to_rgb(*x) for x in hsv_tuples] colors = [rgb_tuples[index - 1] for index in idx[sel, :].flatten()] # % Visualize the data and centroid memberships in 3D fig = plt.figure() ax = Axes3D(fig) ax.scatter(X[sel, 0], X[sel, 1], X[sel, 2], s=10, c=colors) ax.set_title('Pixel dataset plotted in 3D. Color shows centroid memberships') plt.show() # fprintf('Program paused. Press enter to continue.\n') # pause; # # %% === Part 8(b): Optional (ungraded) Exercise: PCA for Visualization === # % Use PCA to project this cloud to 2D for visualization # # % Subtract the mean to use PCA X_norm, mu, sigma = featureNormalize(X) # % PCA and project the data to 2D U, S = pca(X_norm) Z = projectData(X_norm, U, 2)
def HRC(df, original, components): """ Hierarchical clusteing method df = dataset to work on original = original dataset to compare later with labels componenets = number of attributes """ import pandas as pd from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as np from sklearn import preprocessing min_max_scaler = preprocessing.MinMaxScaler() datanorm = min_max_scaler.fit_transform(df) from sklearn.decomposition import PCA estimator = PCA(n_components=components) X_pca = estimator.fit_transform(datanorm) #3. Hierarchical Clustering # 3.1. Compute the similarity matrix import sklearn.neighbors dist = sklearn.neighbors.DistanceMetric.get_metric('euclidean') matsim = dist.pairwise(datanorm) # 3.2. Building the Dendrogram from scipy import cluster # method linkage: simple, ward, complete clusters = cluster.hierarchy.linkage(matsim, method='complete') # http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.cluster.hierarchy.dendrogram.html # color_threshold a 16 para coger 10 clusters en OrientacionMEAN .4 # color_threshold a 18 para coger 7 clusters en OrientacionMEAN .4 # color_threshold a 10 para coger 7 clusters en OrientacionMEAN .4 X_PCA cluster.hierarchy.dendrogram(clusters, color_threshold=11) plt.show() cut = 11 # !!!! ad-hoc labels = cluster.hierarchy.fcluster(clusters, cut, criterion='distance') print('Number of clusters %d' % (len(set(labels)))) print(labels) colors = np.array([x for x in 'bgrcmykbgrcmykbgrcmykbgrcmyk']) colors = np.hstack([colors] * 20) fig, ax = plt.subplots() plt.xlim(-1, 1.5) plt.ylim(-1.5, 1) for i in range(len(X_pca)): plt.text(X_pca[i][0], X_pca[i][1], 'x', color=colors[labels[i]]) ax.grid(True) fig.tight_layout() plt.show() #3D Plot if (components == 3): fig = plt.figure() ax = Axes3D(fig) x = X_pca[:, 0] y = X_pca[:, 1] z = X_pca[:, 2] ax.scatter(x, y, z, c=labels) plt.show() #np array to dataframe if (components == 3): data = pd.DataFrame({ 'Column1': X_pca[:, 0], 'Column2': X_pca[:, 1], 'Column3': X_pca[:, 2] }) elif (components == 2): data = pd.DataFrame({'Column1': X_pca[:, 0], 'Column2': X_pca[:, 1]}) #Mean data by group print("\nNormalized data means by group") print(data.groupby(labels).mean()) #Plot with original data and labeled x = original.iloc[:, 0] y = original.iloc[:, 1] if (components == 3): fig = plt.figure() ax = Axes3D(fig) z = original.iloc[:, 2] ax.scatter(x, y, z, c=labels) elif (components == 2): plt.scatter(x, y, c=labels, cmap="Set1") plt.show() #Dataframe to np to pass labels original = original.to_numpy() for i in range(len(original)): plt.text(original[i][0], original[i][1], 'x', color=colors[labels[i]]) #Back to dataframe to print group means if (components == 3): original = pd.DataFrame({ 'Azimut': original[:, 0], 'Roll': original[:, 1], 'Pitch': original[:, 2] }) elif (components == 2): original = pd.DataFrame({ 'Roll': original[:, 0], 'Pitch': original[:, 1], }) print("\nOriginal data means by group") print(original.groupby(labels).mean())
# Edit the following time variable to suit your needs. time = ['2018-12-19T23:00:00.000Z', '2018-12-20T00:00:00.000Z'] result = ssc.get_locations(['dmspf18'], time) data = result['Data'][0] coords = data['Coordinates'][0] print(coords['X']) # ... try: import matplotlib as mpl import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from packaging import version fig = plt.figure() if version.parse(mpl.__version__) < version.parse('3.4'): ax = fig.gca(projection='3d') else: ax = Axes3D(fig, auto_add_to_figure=False) fig.add_axes(ax) ax.set_xlabel('X (km)') ax.set_ylabel('Y (km)') ax.set_zlabel('Z (km)') title = data['Id'] + ' Orbit (' + coords['CoordinateSystem'].value.upper() + ')' ax.plot(coords['X'], coords['Y'], coords['Z'], label=title) ax.legend() plt.show() except ImportError: print('To see the plot, do') print('pip install packaging matplotlib') except Exception as e: print(e)
def DBScan(df, bidimiensional=True): """ DBScan clustering algorithm df = dataset to work with bidimiensional = if the dataset has 2 columns """ from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt X = df.to_numpy() # 1. Setting Parameters # 1.1 Compute the similarity/distance matrix (high cost) import sklearn.neighbors dist = sklearn.neighbors.DistanceMetric.get_metric('manhattan') matsim = dist.pairwise(X) # 1.2 Compute the k-nearest neighboors minPts = 7 # ln(2000) ~= 7,6 from sklearn.neighbors import kneighbors_graph A = kneighbors_graph(X, minPts, include_self=False) Ar = A.toarray() seq = [] for i, s in enumerate(X): for j in range(len(X)): if Ar[i][j] != 0: seq.append(matsim[i][j]) seq.sort() plt.plot(seq) plt.show() # 2. DBSCAN execution from sklearn.cluster import DBSCAN import numpy #Analyze range to find best eps for eps in numpy.arange(2, 30, 2): db = DBSCAN(eps, min_samples=minPts).fit(X) core_samples_mask = numpy.zeros_like(db.labels_, dtype=bool) core_samples_mask[db.core_sample_indices_] = True labels = db.labels_ n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0) n_outliers = list(labels).count(-1) print("%6.2f, %d, %d" % (eps, n_clusters_, n_outliers)) # how are chosen eps and minpts?? db = DBSCAN(eps=8, min_samples=minPts, metric='manhattan') y_db = db.fit_predict(X) #3. Validation/Evaluation # Only using silhouette coefficient from sklearn import metrics print("Silhouette Coefficient: %0.3f" % metrics.silhouette_score(X, y_db)) # 4. Plot results labels = db.labels_ if (bidimiensional): plt.scatter(X[:, 0], X[:, 1], c=labels, s=50, cmap="Set1") else: fig = plt.figure() ax = Axes3D(fig) ax.scatter(X[:, 0], X[:, 1], X[:, 2], c=labels, s=50, cmap="Set1") plt.show()
def animate_result(title, array_time, geometry, force, scaling): # just for testing, where to get the undeformed structure? # # First set up the figure, the axis, and the plot element we want to # animate # TODO: animation needs a step and the number of frames in animate needs to take this into consideration # make more generic and robust step = 5 fig = plt.figure() ax = Axes3D(fig) # fig.gca(projection='3d') # TODO: animate needs scaling as well # set min and max values #xmin = displacement_time_history.min() #xmax = displacement_time_history.max() #xmin = xmin - ceil((xmax-xmin)/10) #xmax = xmax + ceil((xmax-xmin)/10) # TODO extend and use plot limits geometry["deformed"] = [ geometry["deformation"][0] * scaling["deformation"] + geometry["undeformed"][0][:, np.newaxis], geometry["deformation"][1] * scaling["deformation"] + geometry["undeformed"][1][:, np.newaxis], geometry["deformation"][2] * scaling["deformation"] + geometry["undeformed"][2][:, np.newaxis] ] xmin = np.min(geometry["deformed"][0]) xmax = np.max(geometry["deformed"][0]) # xmin = xmin - ceil((xmax-xmin)/30) # xmax = xmax + ceil((xmax-xmin)/30) ymin = np.min(geometry["deformed"][1]) ymax = np.max(geometry["deformed"][1]) # ymin = ymin - ceil((ymax-ymin)/30) # ymax = ymax + ceil((ymax-ymin)/30) zmin = np.min(geometry["deformed"][2]) zmax = np.max(geometry["deformed"][2]) # zmin = zmin - ceil((zmax-zmin)/30) # zmax = zmax + ceil((zmax-zmin)/30) ax.set_xlim3d(xmin, xmax) ax.set_ylim3d(ymin, ymax) ax.set_zlim3d(zmax, zmin) # text = ax.text(0.02, 0.90, '', transform=ax.transAxes) # text_mode = ax.text(0.02, 0.95, '', transform=ax.transAxes) ax.set_xlabel("x") ax.set_ylabel("y") ax.set_zlabel("z") ax.set_title(title) ax.grid(True) # ax.set_ylim(-0.0005,0.0005) # #ax.set_zlim(0,1.1) # TODO: clear if this part or init is at all neded or both together redundant # NOTE: Adding the comma un-packs the length one list into undeformed_line, = ax.plot( geometry["undeformed"][0], geometry["undeformed"][1], geometry["undeformed"][2], label='undeformed', color=LINE_TYPE_SETUP["color"][0], linestyle=LINE_TYPE_SETUP["linestyle"][0], marker=LINE_TYPE_SETUP["marker"][0], markeredgecolor=LINE_TYPE_SETUP["markeredgecolor"][0], markerfacecolor=LINE_TYPE_SETUP["markerfacecolor"][0], markersize=LINE_TYPE_SETUP["markersize"][0]) # NOTE: Can't pass empty arrays into 3d version of plot() # NOTE: Adding the comma un-packs the length one list into deformed_line, = ax.plot( [], [], [], color=LINE_TYPE_SETUP["color"][1], linestyle=LINE_TYPE_SETUP["linestyle"][1], marker=LINE_TYPE_SETUP["marker"][1], markeredgecolor=LINE_TYPE_SETUP["markeredgecolor"][1], markerfacecolor=LINE_TYPE_SETUP["markerfacecolor"][1], markersize=LINE_TYPE_SETUP["markersize"][1]) text = ax.text(10, 0, 0, 'init', color='red') # initialization function: plot the background of each frame def init(): undeformed_line.set_data([], []) deformed_line.set_data([], []) # NOTE: there is no .set_data() for 3 dim data... undeformed_line.set_3d_properties([]) deformed_line.set_3d_properties([]) text.set_text('') return undeformed_line, deformed_line, text # animation function. This is called sequentially def animate(i): undeformed_line.set_data(geometry["undeformed"][0], geometry["undeformed"][1]) deformed_line.set_data(geometry["deformed"][0][:, step * i], geometry["deformed"][1][:, step * i]) # NOTE: there is no .set_data() for 3 dim data... undeformed_line.set_3d_properties(geometry["undeformed"][2]) deformed_line.set_3d_properties(geometry["deformed"][2][:, step * i]) text.set_text('{0:.2f}'.format(array_time[i]) + "[s]") return undeformed_line, deformed_line, text # call the animator. blit=True means only re-draw the parts that have # changed. # frames = number of columns in result animation.FuncAnimation(fig, animate, init_func=init, frames=len(array_time[::step]) - 1, interval=20, blit=True) plt.show()
y = get_int("y: ") sprawdzenie = x % y == 0 funkcja = 'X dzieli się przez Y' if sprawdzenie else 'X nie dzieli się przez Y' print(funkcja) print('-' * 20) print("zad4") x = get_int("x: ") y = get_int("y: ") print(f"{x/y:.2f}") print('-' * 20) print("zad5") x = get_int("x: ") y = get_int("y: ") x_knots = np.linspace(0, x, 200) y_knots = np.linspace(0, y, 200) X, Y = np.meshgrid(x_knots, y_knots) R = np.sqrt(X**3 + 1 + Y**3 + 1) Z = np.cos(R)**3 * np.exp(-0.1 * R) ax = Axes3D(plt.figure(figsize=(10, 8))) ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.cm.coolwarm, linewidth=0.4) plt.show()