<jupyter_start><jupyter_text>Advanced fMRI data analysis  General Linear Model 1In this assignment, your task is to complete a few linear regression excercises in Python.You can choose to answer in Polish or English (it will not affect your grade).**DEADLINE:** 08-05-2020-------------------  Linear regression analysis with signals of non-neuronal origin *Confounds* (or nuisance regressors) are variables representing fluctuations with a potential non-neuronal origin. Such non-neuronal fluctuations may drive spurious results in fMRI data analysis, including standard activation GLM and functional connectivity analyses. Read [more](https://fmriprep.readthedocs.io/en/stable/outputs.htmlconfounds).Run simple and multiple linear regression to investigate associations between regressors.Confounds regressors calculated with *fMRIPrep* are stored in data folder (`/data/sub-01_task-rhymejudgment_desc-confounds_regressors.tsv`)  Task 1Investigate linear relationship between *global signal* (signal from the whole brain) and signal from *white matter*.<jupyter_code># Load libraries
import nipype.interfaces.fsl as fsl
import nipype.interfaces.spm as spm
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

# Load DataFrame with confounds
confounds_path = "data/sub-01_task-rhymejudgment_desc-confounds_regressors.tsv"
confounds = pd.read_csv(confounds_path, delimiter="\t")

# Print all column names (use df.columns.values)
confounds.columns.values

# Select columns representing global signal and white matter signal
b = confounds[["global_signal","white_matter"]]

# Plot association between these signals using on scatterplot
plt.scatter(confounds["global_signal"], confounds["white_matter"])
# Run simple linear regression for global signal and white matter signal
from sklearn.linear_model import LinearRegression
a = confounds["global_signal"].values
c= confounds["white_matter"].values
linear_regression = LinearRegression() 
linear_regression.fit(a.reshape(-1, 1), c.reshape(-1, 1))

# Print intercept and beta values
intercept = linear_regression.intercept_
beta = linear_regression.coef_

print("intercept:", intercept)
print("beta:", beta)
# Make a scatterplot representing association between signals with fitted linear regression line

x = np.linspace(517,528,100)
y = beta*x+intercept
y = np.squeeze(y)

plt.scatter(a,c)
plt.plot(x,y)<jupyter_output><empty_output><jupyter_text>Task 2*Framewise displacement* variable in confounds table (stored as `framewise_displacement`) is a quantification of the estimated bulk-head motion. Run multiple linear regression to predict `framewise_displacement` from six motion parameters (3 rotations, 3 translations). Use previously loaded confounds table.<jupyter_code># Filter dataframe to store only 6 motion parameters

six_motion = confounds[["trans_x", "trans_y", "trans_z", "rot_x", "rot_y", "rot_z"]].drop(six_motion.index[0])
print(six_motion.shape)
# Print firt 5 rows of motion parameters
print(six_motion.head())

# Filter dataframe to store framewise displacement
frame_disp = confounds[["framewise_displacement"]].drop(frame_disp.index[0])



print(frame_disp)
# Fit multiple linear regression model 

regr = LinearRegression()
regr.fit(six_motion, frame_disp)

# Print intercept and beta values
intercept = regr.intercept_
beta = regr.coef_

print("intercept:", intercept)
print("beta:", beta)<jupyter_output>intercept: [0.10217716]
beta: [[-0.40116933 -0.15608601 -0.08604222 -3.47703684 -3.29403679  7.3812089 ]]<jupyter_text>Which of the 6 motion parameter values has highest corresponding beta value?**Answer**: Translation Z --------  Linear regression on movie/TV series characters profile pictures  Task 3 In folder `data/characters` you can find pictures of 5 characters from Harry Potter movie stored as 400$\times$400 numpy arrays (RED channel). Add your favourite movie/TV character from previous homework to the folder (array has to have the same dimension) and run multiple regression to predict your character from other other characters pictures. You can load more pictures to improve your prediction!!!<jupyter_code># Load image of your favoutite character
path = "data/characters/hulk-cgi.jpg.npy"
hulk = np.load(path)


# Load pictures of other characters


path0 = "data/characters/harry.npy"
harry = np.load(path0)
path1 = "data/characters/james.npy"
james = np.load(path1)
path2= "data/characters/lilly.npy"
lilly = np.load(path2)
path3 = "data/characters/syrius.npy"
syrius = np.load(path3)
path4= "data/characters/voldemort.npy"
voldemort = np.load(path4)


# Plot all pictures on a one figure (use plt.subplots)

fig, (ax1, ax2, ax3, ax4, ax5, ax6) = plt.subplots(1,6, figsize=(20, 20))
ax1.imshow(hulk)
ax2.imshow(harry)
ax3.imshow(james)
ax4.imshow(lilly)
ax5.imshow(syrius)
ax6.imshow(voldemort)
# Make a matrix of characters (remember to change matrices to vectors and transpose).

characters_matrix = []
characters=[hulk, harry,james,lilly,syrius,voldemort]
for char in characters:
    characters_matrix.append(char.flatten())

characters_matrix = np.array(characters_matrix)
characters_matrix = characters_matrix.T
print(characters_matrix.shape)

# Fit multiple linear regression to predict your favourite character from other characters
linear_regression = LinearRegression()
linear_regression.fit(characters_matrix[:,1:], characters_matrix[:,0])


# Print intercept and beta values
beta = linear_regression.coef_
intercept = linear_regression.intercept_
print(beta, intercept)

# Calculate your predicted character

predict = beta[0]*harry + beta[1]*james + beta[2]*lilly + beta[3]*syrius + beta[4]*voldemort + intercept
# Plot your original character and predicted character on a one plot (use plt.subplots)

fig, (ax1, ax2) = plt.subplots(1,2, figsize=(10,10))
ax1.imshow(hulk)
ax2.imshow(predict)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.0983074029748675, 'fraction_numerical': 0.025645409471704565, 'mean_word_length': 6.0823244552058116, 'pattern_counts': {'":': 0, '<': 12, '<?xml version=': 0, '>': 12, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '3', 'dir': 'jupyter-structured-clean-dedup', 'id': '510375', 'license': 'MIT', 'n_tokens_mistral': 1913, 'n_tokens_neox': 1766, 'n_words': 562, 'path': '03-fMRIDA_homework.ipynb', 'repo_name': 'ifzerostop/homework-3', 'size': '5849'}