def prediction(): with tf.variable_scope("sec_lstm", reuse=tf.AUTO_REUSE): pred, _ = lstm(1) #预测时只输入[1,time_step,input_size]的测试数据 saver = tf.train.Saver(tf.global_variables()) with tf.Session() as sess: saver.restore(sess, 'model_save1\\modle.ckpt') #参数恢复 # I run the code in windows 10,so use 'model_save1\\modle.ckpt' # if you run it in Linux,please use 'model_save1/modle.ckpt' # 取训练集最后一行为测试样本。shape=[1,time_step,input_size] prev_seq = train_x[-1] predict = [] # 得到之后100个预测结果 for i in range(100): next_seq = sess.run(pred, feed_dict={X: [prev_seq]}) predict.append(next_seq[-1]) # 每次得到最后一个时间步的预测结果,与之前的数据加在一起,形成新的测试样本 prev_seq = np.vstack((prev_seq[1:], next_seq[-1])) # 以折线图表示结果 plt.figure() plt.plot(list(range(len(normalize_data))), normalize_data, color='b') plt.plot(list( range(len(normalize_data), len(normalize_data) + len(predict))), predict, color='r') plt.show()
def prediction(time_step=20): X = tf.placeholder(tf.float32, shape=[None, time_step, input_size]) mean, std, test_x, test_y = get_test_data(time_step) with tf.variable_scope("sec_lstm", reuse=tf.AUTO_REUSE): pred, _ = lstm(X) saver = tf.train.Saver(tf.global_variables()) with tf.Session() as sess: # 参数恢复 module_file = tf.train.latest_checkpoint('model_save2') saver.restore(sess, module_file) test_predict = [] for step in range(len(test_x) - 1): prob = sess.run(pred, feed_dict={X: [test_x[step]], keep_prob: 1}) predict = prob.reshape((-1)) test_predict.extend(predict) test_y = np.array(test_y) * std[7] + mean[7] test_predict = np.array(test_predict) * std[7] + mean[7] acc = np.average( np.abs(test_predict - test_y[:len(test_predict)]) / test_y[:len(test_predict)]) # 偏差程度 print("The accuracy of this predict:", acc) # 以折线图表示结果 plt.figure() plt.plot( list(range(len(test_predict))), test_predict, color='b', ) plt.plot(list(range(len(test_y))), test_y, color='r') plt.show()
def plot_results(xlog, ulog): t = [0.25 * x for x in range(xlog.shape[1])] plt.figure() plt.subplot(311) plt.plot(t, xlog[3, :], label="altitude", color="b") plt.ylabel('altitude') plt.subplot(312) plt.plot(t, xlog[1, :], label="pitch angle", color="r") plt.ylabel('pitch angle') plt.subplot(313) plt.plot(t, ulog[0, :], label="elevator angle", color="g") plt.ylabel('elevator angle') plt.show()
from pandas import read_csv from Example_matplotlib import pyplot # load dataset dataset = read_csv('pollution.csv', header=0, index_col=0) values = dataset.values # specify columns to plot groups = [0, 1, 2, 3, 5, 6, 7] i = 1 # plot each column pyplot.figure() for group in groups: pyplot.subplot(len(groups), 1, i) pyplot.plot(values[:, group]) pyplot.title(dataset.columns[group], y=0.5, loc='right') i += 1 pyplot.show()
# Encode and decode images from test set and visualize their reconstruction. n = 4 canvas_orig = np.empty((28 * n, 28 * n)) canvas_recon = np.empty((28 * n, 28 * n)) for i in range(n): # MNIST test set batch_x, _ = mnist.test.next_batch(n) # Encode and decode the digit image g = sess.run(decoder_op, feed_dict={X: batch_x}) # Display original images for j in range(n): # Draw the original digits canvas_orig[i * 28:(i + 1) * 28, j * 28:(j + 1) * 28] = \ batch_x[j].reshape([28, 28]) # Display reconstructed images for j in range(n): # Draw the reconstructed digits canvas_recon[i * 28:(i + 1) * 28, j * 28:(j + 1) * 28] = \ g[j].reshape([28, 28]) print("Original Images") plt.figure(figsize=(n, n)) plt.imshow(canvas_orig, origin="upper", cmap="gray") plt.show() print("Reconstructed Images") plt.figure(figsize=(n, n)) plt.imshow(canvas_recon, origin="upper", cmap="gray") plt.show()
print('Step %i, Loss: %f' % (i, l)) # Testing # Generator takes noise as input noise_input = tf.placeholder(tf.float32, shape=[None, latent_dim]) # Rebuild the decoder to create image from noise decoder = tf.matmul(noise_input, weights['decoder_h1']) + biases['decoder_b1'] decoder = tf.nn.tanh(decoder) decoder = tf.matmul(decoder, weights['decoder_out']) + biases['decoder_out'] decoder = tf.nn.sigmoid(decoder) # Building a manifold of generated digits n = 20 x_axis = np.linspace(-3, 3, n) y_axis = np.linspace(-3, 3, n) canvas = np.empty((28 * n, 28 * n)) for i, yi in enumerate(x_axis): for j, xi in enumerate(y_axis): z_mu = np.array([[xi, yi]] * batch_size) x_mean = sess.run(decoder, feed_dict={noise_input: z_mu}) canvas[(n - i - 1) * 28:(n - i) * 28, j * 28:(j + 1) * 28] = \ x_mean[0].reshape(28, 28) plt.figure(figsize=(8, 10)) Xi, Yi = np.meshgrid(x_axis, y_axis) plt.imshow(canvas, origin="upper", cmap="gray") plt.show()
#!usr/bin/env Python # -*- coding: utf-8 -*- """ Time:17/1/1 --------------------------- Question: 读取处理过的文件数据并绘图 --------------------------- """ import pandas as pd import Example_matplotlib.pyplot as plt from Air_Pollution_Forcast_Beijing.util import PROCESS_LEVEL1 pd.options.display.expand_frame_repr = False dataset = pd.read_csv(PROCESS_LEVEL1, header=0, index_col=0) # loads the 'pollution.csv' and treat each column as a separate subplot values = dataset.values groups = [0, 1, 2, 3, 5, 6, 7] i = 1 plt.figure() for group in groups: plt.subplot(len(groups), 1, i) plt.plot(values[:, group]) plt.title(dataset.columns[group], y=0.5, loc='right') i += 1 plt.show() # print(dataset.head())
# -*-coding:utf-8-*- # @Time : 2019/6/18 0018 16:13 # @Author :zhuxinquan # @File : matplotlib_03.py from mpl_toolkits.basemap import Basemap import Example_matplotlib.pyplot as plt plt.rcParams['font.sans-serif'] = ['KaiTi'] # 指定默认字体 plt.rcParams['axes.unicode_minus'] = False plt.figure(figsize=(20, 10)) # 长和宽 map = Basemap(projection='ortho', lat_0=0, lon_0=0) map.drawmapboundary(fill_color='aqua') map.fillcontinents(color='#cc9955', lake_color='aqua') map.drawcoastlines() lon = 50.4 lat = 1.4 x, y = map(lon, lat) plt.text(x, y, '哈哈哈哈哈哈哈', fontsize=12, fontweight='bold', ha='left', va='bottom', color='r')
# -*-coding:utf-8-*- # @Time : 2019/6/18 0018 10:58 # @Author :zhuxinquan # @File : matplotlib_01.py import Example_matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap plt.figure(1) # map=Basemap() map = Basemap(llcrnrlon=70, llcrnrlat=3, urcrnrlon=139, urcrnrlat=54) # 画中国 经135度2分30秒-东经73度40分,北纬3度52分-北纬53度33分 map.drawcoastlines() map.drawcountries() # 加海岸线 # map.drawrivers(color='blue', linewidth=0.3) # 加河流 CHN = r"C:\Users\Administrator\Downloads" map.readshapefile(CHN + r'\gadm36_CHN_shp\gadm36_CHN_1', 'states', drawbounds=True) # 加省界 # map.readshapefile(CHN+r'\gadm36_TWN_shp\gadm36_TWN_1', 'taiwan', drawbounds=True) # 加台湾 plt.title(r'$World\ Map$', fontsize=24) plt.show()
def pic_map(): import numpy as np import pandas as pd import Example_matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap from Example_matplotlib.patches import Polygon from Example_matplotlib.colors import rgb2hex from Example_matplotlib.collections import PatchCollection from Example_matplotlib import pylab plt.rcParams['font.sans-serif'] = ['KaiTi'] # 指定默认字体 plt.rcParams['axes.unicode_minus'] = False plt.figure(figsize=(20, 10)) # 长和宽 # m= Basemap(llcrnrlon=73, llcrnrlat=18, urcrnrlon=135, urcrnrlat=55) #指定中国的经纬度 m = Basemap(llcrnrlon=77, llcrnrlat=14, urcrnrlon=140, urcrnrlat=51, projection='lcc', lat_1=33, lat_2=45, lon_0=100) # ‘lcc'将投影方式设置为兰伯特投影 # projection='ortho' # 投影方式设置为正投影——类似地球仪 CHN = r'C:\Users\Administrator\Desktop\MyProject\Test_module\Test_matplotlib\data_base' m.readshapefile(CHN + r'\gadm36_CHN_shp\gadm36_CHN_1', 'states', drawbounds=True) # 加省界 # 读取数据 df = pd.read_csv('./data_base/data/chnpop.csv') df['省名'] = df.省名.str[:2] df.set_index('省名', inplace=True) # 把每个省的数据映射到colormap上 statenames = [] colors = {} patches = [] cmap = plt.cm.YlOrRd # 国旗色红黄色调 vmax = 10**8 vmin = 3 * 10**6 # 处理地图包里的省名 for shapedict in m.states_info: statename = shapedict['NL_NAME_1'] p = statename.split('|') if len(p) > 1: s = p[1] else: s = p[0] s = s[:2] if s == '黑龍': s = '黑龙' statenames.append(s) pop = df['人口数'][s] colors[s] = cmap(np.sqrt( (pop - vmin) / (vmax - vmin)))[:3] # 根据归一化后的人口数映射颜色 # exit() ax = plt.gca() for nshape, seg in enumerate(m.states): color = rgb2hex(colors[statenames[nshape]]) poly = Polygon(seg, facecolor=color, edgecolor=color) patches.append(poly) ax.add_patch(poly) # 图片绘制加上台湾(台湾不可或缺) m.readshapefile(CHN + '\gadm36_TWN_shp\gadm36_TWN_1', 'taiwan', drawbounds=True) for nshape, seg in enumerate(m.taiwan): poly = Polygon(seg, facecolor='w') patches.append(poly) ax.add_patch(poly) # 添加colorbar 渐变色legend colors1 = [i[1] for i in colors.values()] colorVotes = plt.cm.YlOrRd p = PatchCollection(patches, cmap=colorVotes) p.set_array(np.array(colors1)) pylab.colorbar(p) #4266831.094478747, 1662846.3046657 lon = 4097273.638675578 lat = 4008859.232616643 x, y = m(lon, lat) plt.text(x, y, '国都', fontsize=120, fontweight='bold', ha='left', va='bottom', color='k') m.scatter(x, y, s=200, marker='*', facecolors='r', edgecolors='B') # 绘制首都 plt.title(u'祝鑫泉画的World Map ', fontsize=24) plt.savefig("./data_base/result/Chinese_Map1.png", dpi=100) # 指定分辨率 plt.show()
# -*-coding:utf-8-*- # @Time : 2019/6/18 0018 13:53 # @Author :zhuxinquan # @File : matplotlib_pic_China.py import Example_matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap from Example_matplotlib.patches import Polygon plt.figure(figsize=(16, 8)) m = Basemap(llcrnrlon=77, llcrnrlat=14, urcrnrlon=140, urcrnrlat=51, projection='lcc', lat_1=33, lat_2=45, lon_0=100) m.drawcoastlines() # 画上海岸线 m.drawcountries(linewidth=1.5) # 画上国家 # 画上行政区 CHN = r'C:\Users\Administrator\Desktop\MyProject\Test_module\Test_matplotlib\data_base' m.readshapefile(CHN + r'\gadm36_CHN_shp\gadm36_CHN_1', 'states', drawbounds=True) # 加省界 # 上色 ax = plt.gca() for nshape, seg in enumerate(m.states):
# 构造函数原型__init__(self,n_components,perplexity,early_exaggeration,learning_rate,n_iter, # n_iter_without_progress,min_grad_norm,metric,init,verbose,random_state, # method,angle) tsne = TSNE(perplexity=30, n_components=2, init="pca", n_iter=5000) plot_only = 100 # 执行降维操作 # 函数原型TSNE.fit_transform(Self,X,y) low_dim_embs = tsne.fit_transform(final_embeddings[:plot_only, :]) labels = list() for i in range(plot_only): labels.append(reverse_dictionary[i]) # pyplot的figure()函数用于定义画布的大小,这里设为20x20,你也可以尝试其他大小 plt.figure(figsize=(20, 20)) for j, label in enumerate(labels): x, y = low_dim_embs[j, :] plt.scatter(x, y) plt.annotate(label, xy=(x, y), xytext=(5, 2), textcoords="offset points", ha="right", va="bottom") # 以png格式保存图片 plt.savefig("./after_tsne.png")