[Python] Gaussian Class
Python Class
2023-09-14 09:00:47 时间
import math import matplotlib.pyplot as plt class Gaussian(): """ Gaussian distribution class for calculating and visualizing a Gaussian distribution. Attributes: mean (float) representing the mean value of the distribution stdev (float) representing the standard deviation of the distribution data_list (list of floats) a list of floats extracted from the data file """ def __init__(self, mu = 0, sigma = 1): self.mean = mu self.stdev = sigma self.data = [] def calculate_mean(self): """Function to calculate the mean of the data set. Args: None Returns: float: mean of the data set """ avg = 1.0 * sum(self.data) / len(self.data) self.mean = avg return self.mean def calculate_stdev(self, sample=True): """Function to calculate the standard deviation of the data set. Args: sample (bool): whether the data represents a sample or population Returns: float: standard deviation of the data set """ if sample: n = len(self.data) - 1 else: n = len(self.data) mean = self.mean sigma = 0 for d in self.data: sigma += (d - mean) ** 2 sigma = math.sqrt(sigma / n) self.stdev = sigma return self.stdev def read_data_file(self, file_name, sample=True): """Function to read in data from a txt file. The txt file should have one number (float) per line. The numbers are stored in the data attribute. After reading in the file, the mean and standard deviation are calculated Args: file_name (string): name of a file to read from Returns: None """ with open(file_name) as file: data_list = [] line = file.readline() while line: data_list.append(int(line)) line = file.readline() file.close() self.data = data_list self.mean = self.calculate_mean() self.stdev = self.calculate_stdev(sample) def plot_histogram(self): """Function to output a histogram of the instance variable data using matplotlib pyplot library. Args: None Returns: None """ plt.hist(self.data) plt.title('Histogram of Data') plt.xlabel('data') plt.ylabel('count') def pdf(self, x): """Probability density function calculator for the gaussian distribution. Args: x (float): point for calculating the probability density function Returns: float: probability density function output """ return (1.0 / (self.stdev * math.sqrt(2*math.pi))) * math.exp(-0.5*((x - self.mean) / self.stdev) ** 2) def plot_histogram_pdf(self, n_spaces = 50): """Function to plot the normalized histogram of the data and a plot of the probability density function along the same range Args: n_spaces (int): number of data points Returns: list: x values for the pdf plot list: y values for the pdf plot """ mu = self.mean sigma = self.stdev min_range = min(self.data) max_range = max(self.data) # calculates the interval between x values interval = 1.0 * (max_range - min_range) / n_spaces x = [] y = [] # calculate the x values to visualize for i in range(n_spaces): tmp = min_range + interval*i x.append(tmp) y.append(self.pdf(tmp)) # make the plots fig, axes = plt.subplots(2,sharex=True) fig.subplots_adjust(hspace=.5) axes[0].hist(self.data, density=True) axes[0].set_title('Normed Histogram of Data') axes[0].set_ylabel('Density') axes[1].plot(x, y) axes[1].set_title('Normal Distribution for \n Sample Mean and Sample Standard Deviation') axes[0].set_ylabel('Density') plt.show() return x, y
相关文章
- Python 极速入门教程
- python实现矩阵的转置_Python实现矩阵转置的方法分析
- aic准则python_Python数据科学:线性回归
- python移动app开发_神奇的Kivy,让Python快速开发移动app
- python识别文字位置_如何利用Python识别图片中的文字
- python人工智能学习笔记_[Python] 人工智能与自然语言处理学习笔记(1)[通俗易懂]
- python中dtype的使用规范_Python numpy.dtype() 使用实例
- python 生成EXE文件 并执行
- 云服务器上运行python程序(PyCharm本地编辑同步服务器+Anaconda)挂载跑实验详细教程[通俗易懂]
- 手机python 3.8解释器_Python 3.8 解释器安装教程
- 【说站】python ChainMap标准库的跟踪使用
- Python:利用python代码编程实现将视频的avi格式转换为MP4格式
- python装饰器
- Python实现图像与Base64格式互转
- Python使用platform库获取系统信息:操作系统信息、硬件信息、python环境信息
- 一步一步学会在Linux上运行Python程序(linux运行python程序)
- 新手学 python 选什么编辑器比较好呢?
- 如何在Linux上将Python脚本设置为后台运行?(linux后台运行python)
- 革命性技术:Python与MSSQL的携手合作(python和mssql)
- 利用Neo4j和Python进行无缝图形数据库支持(neo4j python)
- SublimeText2编译python出错的解决方法(Thesystemcannotfindthefilespecified)