def graph(ynew, h): # функция графика # Интервал изменения переменной по оси X xmin = a xmax = b dx = 0.01 # Шаг между точками # список координат по оиси X на отрезке [-xmin; xmax] xlist = pylab.frange(xmin, xmax, h) xlist2 = pylab.frange(xmin, xmax, dx) # значение функции в заданных точках ylist = ynew # построенная ylist2 = [real(x) for x in xlist2] # реальная # рисуем графики pylab.plot(xlist, ylist) pylab.plot(xlist2, ylist2) plt.grid(True) pylab.show() # Покажем график
def linear(data, kwargs='for_cv'): """ Linear interpolation of points set :param data: List of X, Y :param kwargs: Impacts on returning value. If 'for_cv, then returns linear function for given data. If 'for_plot', then returns standard triple for PLOT function. Default: 'for_cv'. :return: Initial points set, X, Y(X) """ x, y = data x_min = min(x) x_max = max(x) points = [x, y] x = array([[1, x[i][0]] for i in range(len(x))]) beta = find_betas(x, y) if kwargs == 'for_cv': def func(arg): return beta[0][0] + beta[1][0] * arg return func elif kwargs == 'for_plot': abscissa = frange(x_min, x_max, 0.01) ordinate = [beta[0][0] + beta[1][0] * arg for arg in abscissa] return points, abscissa, ordinate
def demo(): """Demonstrates solution for exercise: example of usage""" print "IterateLogistic Demo" print "Close plot to continue" print " Creating Bifurcation Diagram" BifurcationDiagram(logistic_map, 0.1, 500, 128, pylab.frange(0, 1, npts=600))
def plotposterior(cls, samples, prior_pdf, name, xmin, xmax): xs = mlab.frange(xmin, xmax, (xmax - xmin) / 100) ys = [prior_pdf(x) for x in xs] plt.plot(xs, ys, label='Prior Dist') plt.hist(samples, bins=30, normed=True, label='Posterior Dist') plt.title('Prior and Posterior of {}'.format(name)) plt.ylim(ymin=0) plt.xlim(xmin, xmax) plt.show()
def plot_posterior_hack(samples, prior_pdf, name, xmin, xmax): xs = mlab.frange(xmin, xmax, (xmax - xmin) / 100.0) ys = [prior_pdf(x) for x in xs] ts = stats.beta(3, 3) plt.plot(xs, ys, label='Prior Dist') plt.plot(xs, ts.pdf(xs)) plt.hist(samples, bins=100, normed=True, label='Posterior Dist') plt.title('Prior and Posterior of {}'.format(name)) plt.ylim(ymin=0) plt.xlim(xmin, xmax) plt.show()
def non_linear(data, functions, kwargs='for_cv'): """ Non-linear interpolation of points set :param data: List of X, Y :param functions: List of functions :param kwargs: Impacts on returning value. If 'for_cv, then returns polynomial function for given data. If 'for_plot', then returns standard triple for PLOT function Default: 'for_cv' :return: Initial points set, X, Y(X) """ x, y = data x_min = min(x) x_max = max(x) points = [x, y] # Making a Vandermonde's matrix of functions functions.insert(0, lambda arg: arg) functions.insert(0, lambda arg: 1) x_temp = [list() for _ in range(len(x))] for i in range(len(x)): for j in range(len(functions)): x_temp[i].append(functions[j](x[i][0])) x = array(x_temp) del x_temp beta = find_betas(x, y) if kwargs == 'for_cv': def func(arg): value = 0 for j in range(len(functions)): value += beta[j][0] * functions[j](arg) return value return func elif kwargs == 'for_plot': abscissa = frange(x_min, x_max, 0.01) ordinate = list() for arg in abscissa: value = 0 for j in range(len(functions)): value += beta[j][0] * functions[j](arg) ordinate.append(value) return points, abscissa, ordinate
def polynomial(data, k, kwargs='for_cv'): """ Polynomial interpolation of points set :param data: List of X, Y :param k: Degree of polynomial :param kwargs: Impacts on returning value. If 'for_cv, then returns polynomial function for given data. If 'for_plot', then returns standard triple for PLOT function. Default: 'for_cv'. :return: Initial points set, X, Y(X) """ x, y = data x_min = min(x) x_max = max(x) points = [x, y] # Making a Vandermonde's matrix x_temp = [list() for _ in range(len(x))] for i in range(len(x)): for j in range(k + 1): x_temp[i].append(x[i][0] ** j) x = array(x_temp) del x_temp beta = find_betas(x, y) if kwargs == 'for_cv': def func(arg): value = 0 for j in range(k + 1): value += beta[j][0] * (arg ** j) return value return func elif kwargs == 'for_plot': abscissa = frange(x_min, x_max, 0.01) ordinate = list() for arg in abscissa: value = 0 for j in range(k + 1): value += beta[j][0] * (arg ** j) ordinate.append(value) return points, abscissa, ordinate
from __future__ import print_function import sys import matplotlib matplotlib.use("TkAgg") from matplotlib import pyplot as plt from matplotlib import pylab as pl import numpy as np xval = [x for x in pl.frange(-3.0, 3.0, 0.1)] if (len(sys.argv) == 2): option = sys.argv[1] if (int(option) == 1): yval = [x for x in xval] elif (int(option) == 2): yval = [x**2 for x in xval] elif (int(option) == 3): yval = [x**3 for x in xval] elif (int(option) == 4): yval = [np.sin(x) for x in xval] elif (int(option) == 5): yval = [np.cos(x) for x in xval] elif (int(option) == 6): yval = [np.tan(x) for x in xval] elif (int(option) == 7): yval = [np.exp(x) for x in xval] elif (int(option) == 8): yval = [np.sqrt(abs(x)) for x in xval] else: print("""" Wrong argument list!!.
plt.title("Dot Plot by frequency") plt.plot(y_, x_, 'ro') plt.xlabel('Count') plt.ylabel('# PResidential Request') # min and max limits plt.xlim(min(y_)-1, max(y_)+1) plt.subplot(312) plt.title("Simple dot plot") plt.xlabel("# Presedential Request") plt.ylabel("Frequency") # prepare data for dot plot for key, value in x_freq.items(): x__ = np.repeat(key, value) y__ = frange(0.1, (value/10.0), 0.1) try: plt.plot(x__, y__, 'go') except ValueError: print x__.shape, y__.shape # set min and max plt.ylim(0.0, 0.4) plt.xlim(xmin=-1) plt.xticks(x_freq.keys()) plt.subplot(313) x_vals = [] x_labels = [] y_vals = [] x_tick = 1 for k,v in x_group.items():
# plt.subplot(311) plt.plot(y_, x_, 'ro') plt.title("Dot Plot by Frequency") plt.xlabel('Count') plt.ylabel('# Presedential Request') plt.xlim(min(y_) - 1, max(y_) + 1) plt.subplot(312) plt.title("Simple dot plot") plt.xlabel('# Presedential Request') plt.ylabel('Frequency') for key, value in x_freq.items(): x__ = np.repeat(key, value) y__ = frange(0.1, (value / 10.0), 0.1) try: plt.plot(x__, y__, 'go') except ValueError: print x__.shape, y__.shape # plt.ylim(0.0, 0.4) plt.xlim(xmin=-1) plt.xticks(x_freq.keys()) plt.subplot(313) x_vals = [] x_labels = [] y_vals = [] x_tick = 1 for k, v in x_group.items():
def demo(): """Demonstrates solution for exercise: example of usage""" print "IterateLogistic Demo" print "Close plot to continue" print " Creating Bifurcation Diagram" BifurcationDiagram(logistic_map, 0.1, 500, 128, pylab.frange(0,1,npts=600))
def plot(function, min_coords, bound): mpl.rcParams['legend.fontsize'] = 10 fig = plt.figure(figsize=(16, 9)) fig.set_facecolor((0.95, 0.95, 0.95)) fig.canvas.set_window_title('Gradient Descent') fig.suptitle('Gradient Descent', fontsize=28) ax = fig.gca() ax.set_axis_bgcolor(fig.get_facecolor()) ax.tick_params(axis='x', colors=(0.15, 0.15, 0.15)) ax.tick_params(axis='y', colors=(0.15, 0.15, 0.15)) x_min, x_max = bound[0], bound[1] x = np.linspace(x_min, x_max, 100) colors = ['red', 'green', 'yellow', 'cyan'] i = 0 n = len(min_coords[0][0]) if n == 2: ax = fig.gca(projection='3d') ax.tick_params(axis='z', colors=(0.15, 0.15, 0.15)) ax.set_axis_bgcolor(fig.get_facecolor()) y_min, y_max = x_min, x_max y = np.linspace(y_min, y_max, 100) z = function([x, y], n) ax.plot(xs=x, ys=y, zs=z) for coords in min_coords: xs = coords[0][0] ys = coords[0][1] zs = function([coords[0][0], coords[0][1]], n) label = coords[1] ax.scatter(xs=xs, ys=ys, zs=zs, label=label, c=colors[i]) i += 1 elif n == 1: ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) ax.spines['left'].set_color((0.75, 0.75, 0.75)) ax.spines['bottom'].set_color((0.75, 0.75, 0.75)) ax.tick_params(axis='x', colors=(0.15, 0.15, 0.15)) ax.tick_params(axis='y', colors=(0.15, 0.15, 0.15)) ax.set_axis_bgcolor(fig.get_facecolor()) ax.get_xaxis().tick_bottom() ax.get_yaxis().tick_left() plt.xlim(bound[0], bound[1]) x = plt.frange(x_min, x_max, 0.01) y = [function(xi, n) for xi in x] ax.plot(x, y, alpha=0.85) for coords in min_coords: ax.scatter(coords[0], function(coords[0], n), label=coords[1], c=colors[i], s=35, edgecolors='black', alpha=0.75) i += 1 else: return ax.legend() plt.show()