Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # using logic
- import math
- def get_input():
- size = int(input("Enter length of array: "))
- num_data = []
- for i in range(size):
- number = int(input("Enter element {}: ".format(i+1)))
- num_data.append(number)
- return num_data
- def mean(data):
- return sum(data) / len(data)
- def variance(data):
- mu = mean(data)
- return sum((x - mu) ** 2 for x in data) / len(data)
- def std_deviation(data):
- return math.sqrt(variance(data))
- data = get_input()
- print("Mean:", mean(data))
- print("Variance:", variance(data))
- print("Standard Deviation:", std_deviation(data))
- #using library
- import numpy as np
- def get_input():
- size = int(input("Enter length of array: "))
- num_data = []
- for i in range(size):
- number = int(input("Enter element {}: ".format(i+1)))
- num_data.append(number)
- return num_data
- def mean(data):
- return np.mean(data)
- def variance(data):
- return np.var(data)
- def std_deviation(data):
- return np.std(data)
- data = get_input()
- print("Mean:", mean(data))
- print("Variance:", variance(data))
- print("Standard Deviation:", std_deviation(data))
- ################################Linear##################################
- import numpy as np
- import matplotlib.pyplot as plt
- def estimate_coef(x, y):
- # number of observations/points
- n = np.size(x)
- # mean of x and y vector
- m_x = np.mean(x)
- m_y = np.mean(y)
- # calculating cross-deviation and deviation about x
- SS_xy = np.sum(y * x) - n * m_y * m_x
- SS_xx = np.sum(x * x) - n * m_x * m_x
- # calculating regression coefficients
- b_1 = SS_xy / SS_xx
- b_0 = m_y - b_1 * m_x
- print("b_0", b_0)
- print("b_1", b_1)
- return (b_0, b_1)
- def plot_regression_line(x, y, b):
- # plotting the actual points as scatter plot
- plt.scatter(x, y, color="m", marker="o", s=30)
- # predicted response vector
- y_pred = b[0] + b[1] * x
- # plotting the regression line
- plt.plot(x, y_pred, color="g")
- # putting labels
- plt.xlabel('x')
- plt.ylabel('y')
- # observations / data
- x = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
- y = np.array([1, 3, 2, 5, 7, 8, 8, 9, 10, 12])
- # estimating coefficients
- b = estimate_coef(x, y)
- plot_regression_line(x, y, b)
- output:
- https://ibb.co/xmMGCbm
- # Predict the speed of a 10-year old car.
- import matplotlib.pyplot as plt
- from scipy import stats
- x = [5, 7, 8, 7, 2, 17, 2, 9, 4, 11, 12, 9, 6]
- y = [99, 86, 87, 88, 111, 86, 103, 87, 94, 78, 77, 85, 86]
- slope, intercept, r, p, std_err = stats.linregress(x, y)
- def myfunc(x):
- return slope * x + intercept
- mymodel = list(map(myfunc, x))
- plt.scatter(x, y)
- plt.plot(x, mymodel)
- plt.show()
- speed = myfunc(10)
- print(speed)
- # Example of bad-fit
- import matplotlib.pyplot as plt
- from scipy import stats
- x = [89,43,36,36,95,10,66,34,38,20,26,29,48,
- 64,6 ,5 ,36 ,66 ,72 ,40]
- y = [21 ,46 ,3 ,35 ,67 ,95 ,53 ,72 ,58 ,10 ,
- 26 ,34 ,90 ,33 ,38 ,20 ,56 ,2 ,47 ,15]
- slope, intercept,r,p,std_err = stats.linregress(x,y)
- def myfunc(x):
- return slope * x + intercept
- mymodel = list(map(myfunc,x))
- plt.scatter(x,y)
- plt.plot(x,mymodel)
- plt.show()
- print(r)
- ########################skewness###########################3
- import numpy as np
- import pandas as pd
- import seaborn as sns
- # Example dataset
- diamonds = sns.load_dataset("diamonds")
- diamond_prices = diamonds["price"]
- mean_price = diamond_prices.mean()
- median_price = diamond_prices.median()
- std = diamond_prices.std()
- skewness = (3 * (mean_price - median_price)) / std
- print(f"The Pierson's second skewness score of diamond prices distribution is {skewness:.5f}")
- #The Pierson's second skewness score of diamond prices distribution is 1.15189
- def moment_based_skew(distribution):
- n = len(distribution)
- mean = np.mean(distribution)
- std = np.std(distribution)
- # Divide the formula into two parts
- first_part = n / ((n - 1) * (n - 2))
- second_part = np.sum(((distribution - mean) / std) ** 3)
- skewness = first_part * second_part
- return skewness
- skew = moment_based_skew(diamond_prices)
- print("The moment_based skewness score of diamond prices distribution is ", skew)
- # Using Libraries
- # Pandas version
- print("The moment_based skewness skewness score of diamond prices distribution is ",
- diamond_prices.skew())
- # SciPy version
- from scipy.stats import skew
- print("The moment_based skewness skewness score of diamond prices distribution is ",
- skew(diamond_prices))
- # Visualization
- import matplotlib.pyplot as plt
- sns.kdeplot(diamond_prices)
- plt.title("Plot of diamond prices")
- plt.xlabel("Price ($)")
- ##############################simplex###############################3
- #Assignment: Write a Python Program to solve Linear Programming Problem using
- #Simplex Method
- import numpy as np
- def simplex_method(A, b, c):
- m, n = A.shape
- # Create the initial tableau
- tableau = np.hstack([A, np.eye(m), b.reshape(-1, 1)])
- tableau = np.vstack([tableau, np.concatenate([c, np.zeros(m + 1)])])
- while True:
- # Find the pivot column
- pivot_col = np.argmin(tableau[-1, :-1])
- # If all elements in the last row are non-negative, optimal solution found
- if np.all(tableau[-1, :-1] >= 0):
- break
- # Find the pivot row
- ratios = tableau[:-1, -1] / tableau[:-1, pivot_col]
- pivot_row = np.argmin(ratios)
- # Perform pivot operation
- tableau[pivot_row, :] /= tableau[pivot_row, pivot_col]
- for i in range(m + 1):
- if i != pivot_row:
- tableau[i, :] -= tableau[i, pivot_col] * tableau[pivot_row, :]
- return tableau[-1, -1], tableau[-1, :-1]
- A = np.array([[2, 1], [1, 2]])
- b = np.array([4, 3])
- c = np.array([-3, -5])
- optimal_value, optimal_solution = simplex_method(A, b, c)
- print("Optimal value:", optimal_value)
- print("Optimal solution:", optimal_solution)
- #Liner regression
- import numpy as np
- from sklearn.linear_model import LinearRegression
- years = np.array([[1], [2], [3], [4], [5]])
- speeds = np.array([30, 45, 45, 55, 65])
- model = LinearRegression()
- model.fit(years, speeds)
- x= 15
- predicted_speed = model.predict([[x]])
- print(f"Predicted speed after {x} years:", predicted_speed[0], "km/h")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement