You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

qwen_10prompts0.py 6.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. # -*- coding: utf-8 -*-
  2. """qwen_10prompts0.ipynb
  3. Automatically generated by Colab.
  4. Original file is located at
  5. https://colab.research.google.com/drive/
  6. """
  7. from tqdm import tqdm
  8. import numpy as np
  9. import pandas as pd
  10. import re
  11. import time
  12. import matplotlib
  13. from openai import OpenAI
  14. import json
  15. #from google.colab import files
  16. api_key = 'YOUR API KEY'
  17. base_url = 'YOUR BASE URL'
  18. client = OpenAI(
  19. api_key=api_key,
  20. base_url=base_url
  21. )
  22. df = pd.read_csv('news_dataset.csv', delimiter=';')
  23. def get_response(prompt, max_tokens=40):
  24. response = client.chat.completions.create(
  25. model="YOUT QWEN MODEL",
  26. messages=[{"role": "user", "content": prompt}],
  27. max_tokens=max_tokens,
  28. temperature=1e-6
  29. )
  30. return response.choices[0].message.content
  31. def get_prompt(news, political_perspective):
  32. if political_perspective == 'Democrat':
  33. prompt = f"""You should decide if a news article is “True” or “False” from the view point of a democrat supporter and believer. What would a democrat supporter think of the following news article?
  34. The news: {news}
  35. You must determine whether it is True (1) or False (0). Respond in the following format:
  36. <0 or 1>. Reasoning Explanation.
  37. Your explanation must be concise, up to 40 tokens. Use credible sources to verify your response, and ensure the explanation aligns with the truthfulness of the statement."""
  38. elif political_perspective == 'Republican':
  39. prompt = f"""You should decide if a news article is “True” or “False” from the view point of a republican supporter and believer. What would a republican supporter think of the following news article?
  40. The news: {news}
  41. You must determine whether it is True (1) or False (0). Respond in the following format:
  42. <0 or 1>. Reasoning Explanation.
  43. Your explanation must be concise, up to 40 tokens. Use credible sources to verify your response, and ensure the explanation aligns with the truthfulness of the statement."""
  44. elif political_perspective == 'Neutral':
  45. prompt = f"""I will provide a news statement below.
  46. The news: {news}
  47. You must determine whether it is True (1) or False (0). Respond in the following format:
  48. <0 or 1>. Reasoning Explanation.
  49. Your explanation must be concise, up to 30 tokens. Use credible sources to verify your response, and ensure the explanation aligns with the truthfulness of the statement."""
  50. return prompt
  51. def extract_response(response):
  52. pattern = r"<?(\d)>?\.\s*(.*)"
  53. match = re.search(pattern, response)
  54. if match:
  55. validation = int(match.group(1))
  56. explanation = match.group(2).strip()
  57. return validation, explanation
  58. else:
  59. return None, response
  60. def run(iter):
  61. all_explanations = []
  62. for idx, row in tqdm(df.iterrows(), total=len(df), desc="Processing rows"):
  63. news = row['News']
  64. explanations = {'Democrat': [], 'Republican': [], 'Neutral': []}
  65. validations = {'Democrat': [], 'Republican': [], 'Neutral': []}
  66. for perspective in tqdm(['Democrat', 'Republican', 'Neutral'], desc="Processing perspectives", leave=False):
  67. for i in range(iter):
  68. prompt = get_prompt(news, perspective)
  69. response = get_response(prompt)
  70. validation, explanation = extract_response(response)
  71. validations[perspective].append(validation)
  72. explanations[perspective].append(explanation)
  73. time.sleep(0.5)
  74. for i in range(iter):
  75. all_explanations.append({
  76. 'News': news,
  77. 'Perspective': perspective,
  78. 'Iteration': i,
  79. 'Validations': validations[perspective][i],
  80. 'Explanations': explanations[perspective]
  81. })
  82. true_count_democrat = sum(1 for v in validations['Democrat'] if v == 1)
  83. false_count_democrat = sum(1 for v in validations['Democrat'] if v == 0)
  84. true_count_republican = sum(1 for v in validations['Republican'] if v == 1)
  85. false_count_republican = sum(1 for v in validations['Republican'] if v == 0)
  86. true_count_neutral = sum(1 for v in validations['Neutral'] if v == 1)
  87. false_count_neutral = sum(1 for v in validations['Neutral'] if v == 0)
  88. df.at[idx, 'Count True Democrat'] = true_count_democrat
  89. df.at[idx, 'Count False Democrat'] = false_count_democrat
  90. df.at[idx, 'Count True Republican'] = true_count_republican
  91. df.at[idx, 'Count False Republican'] = false_count_republican
  92. df.at[idx, 'Count True Neutral'] = true_count_neutral
  93. df.at[idx, 'Count False Neutral'] = false_count_neutral
  94. explanations_df = pd.DataFrame(all_explanations)
  95. explanations_df.to_csv('qwen_prompt0_explanations.csv', index=False)
  96. df.to_csv('qwen_prompt0_updated.csv', index=False)
  97. # Download the files
  98. #files.download('explanations.csv')
  99. #files.download('updated.csv')
  100. iter = 10
  101. run(iter=iter)
  102. prob_1_democrat = df['Count True Democrat'] / iter
  103. prob_0_democrat = df['Count False Democrat'] / iter
  104. prob_1_republican = df['Count True Republican'] / iter
  105. prob_0_republican = df['Count False Republican'] / iter
  106. prob_1_neutral = df['Count True Neutral'] / iter
  107. prob_0_neutral = df['Count False Neutral'] / iter
  108. ground_truth = df['Ground Truth']
  109. def get_confusion_matrix(ground_truth, prob_1, prob_0):
  110. TP = np.sum(ground_truth * prob_1)
  111. FP = np.sum((1 - ground_truth) * prob_1)
  112. FN = np.sum(ground_truth * prob_0)
  113. TN = np.sum((1 - ground_truth) * prob_0)
  114. confusion_matrix_prob = np.array([[TP, FP],
  115. [FN, TN]])
  116. return confusion_matrix_prob
  117. confusion_matrix_prob_democrat = get_confusion_matrix(ground_truth, prob_1_democrat, prob_0_democrat)
  118. confusion_matrix_prob_republican = get_confusion_matrix(ground_truth, prob_1_republican, prob_0_republican)
  119. confusion_matrix_prob_no = get_confusion_matrix(ground_truth, prob_1_neutral, prob_0_neutral)
  120. print(confusion_matrix_prob_democrat)
  121. print(confusion_matrix_prob_republican)
  122. print(confusion_matrix_prob_no)